@bleedingdev/modern-js-plugin-i18n 3.2.0-ultramodern.12 → 3.2.0-ultramodern.121

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 (119) hide show
  1. package/README.md +221 -11
  2. package/dist/cjs/cli/index.js +32 -5
  3. package/dist/cjs/runtime/I18nLink.js +17 -28
  4. package/dist/cjs/runtime/Link.js +264 -0
  5. package/dist/cjs/runtime/canonicalRoutes.js +18 -0
  6. package/dist/cjs/runtime/context.js +41 -10
  7. package/dist/cjs/runtime/hooks.js +17 -10
  8. package/dist/cjs/runtime/i18n/backend/config.js +9 -5
  9. package/dist/cjs/runtime/i18n/backend/defaults.js +15 -10
  10. package/dist/cjs/runtime/i18n/backend/defaults.node.js +47 -8
  11. package/dist/cjs/runtime/i18n/backend/index.js +9 -5
  12. package/dist/cjs/runtime/i18n/backend/middleware.common.js +9 -5
  13. package/dist/cjs/runtime/i18n/backend/middleware.js +9 -5
  14. package/dist/cjs/runtime/i18n/backend/middleware.node.js +13 -9
  15. package/dist/cjs/runtime/i18n/backend/sdk-backend.js +9 -5
  16. package/dist/cjs/runtime/i18n/backend/sdk-event.js +16 -11
  17. package/dist/cjs/runtime/i18n/detection/config.js +9 -5
  18. package/dist/cjs/runtime/i18n/detection/index.js +9 -5
  19. package/dist/cjs/runtime/i18n/detection/middleware.js +9 -5
  20. package/dist/cjs/runtime/i18n/detection/middleware.node.js +9 -5
  21. package/dist/cjs/runtime/i18n/index.js +9 -5
  22. package/dist/cjs/runtime/i18n/instance.js +17 -37
  23. package/dist/cjs/runtime/i18n/react-i18next.js +53 -0
  24. package/dist/cjs/runtime/i18n/utils.js +9 -17
  25. package/dist/cjs/runtime/index.js +50 -15
  26. package/dist/cjs/runtime/localizedPaths.js +102 -0
  27. package/dist/cjs/runtime/routerAdapter.js +167 -0
  28. package/dist/cjs/runtime/utils.js +80 -97
  29. package/dist/cjs/server/index.js +62 -14
  30. package/dist/cjs/shared/deepMerge.js +12 -8
  31. package/dist/cjs/shared/detection.js +9 -5
  32. package/dist/cjs/shared/localisedUrls.js +351 -0
  33. package/dist/cjs/shared/utils.js +15 -11
  34. package/dist/esm/cli/index.mjs +23 -0
  35. package/dist/esm/runtime/I18nLink.mjs +7 -22
  36. package/dist/esm/runtime/Link.mjs +221 -0
  37. package/dist/esm/runtime/canonicalRoutes.mjs +0 -0
  38. package/dist/esm/runtime/context.mjs +34 -7
  39. package/dist/esm/runtime/hooks.mjs +9 -6
  40. package/dist/esm/runtime/i18n/backend/defaults.mjs +1 -1
  41. package/dist/esm/runtime/i18n/backend/defaults.node.mjs +24 -3
  42. package/dist/esm/runtime/i18n/backend/middleware.node.mjs +3 -3
  43. package/dist/esm/runtime/i18n/instance.mjs +1 -19
  44. package/dist/esm/runtime/i18n/react-i18next.mjs +15 -0
  45. package/dist/esm/runtime/i18n/utils.mjs +0 -12
  46. package/dist/esm/runtime/index.mjs +23 -13
  47. package/dist/esm/runtime/localizedPaths.mjs +55 -0
  48. package/dist/esm/runtime/routerAdapter.mjs +129 -0
  49. package/dist/esm/runtime/utils.mjs +19 -31
  50. package/dist/esm/server/index.mjs +46 -8
  51. package/dist/esm/shared/localisedUrls.mjs +283 -0
  52. package/dist/esm-node/cli/index.mjs +23 -0
  53. package/dist/esm-node/runtime/I18nLink.mjs +7 -22
  54. package/dist/esm-node/runtime/Link.mjs +222 -0
  55. package/dist/esm-node/runtime/canonicalRoutes.mjs +1 -0
  56. package/dist/esm-node/runtime/context.mjs +34 -7
  57. package/dist/esm-node/runtime/hooks.mjs +9 -6
  58. package/dist/esm-node/runtime/i18n/backend/defaults.mjs +1 -1
  59. package/dist/esm-node/runtime/i18n/backend/defaults.node.mjs +24 -3
  60. package/dist/esm-node/runtime/i18n/backend/middleware.node.mjs +3 -3
  61. package/dist/esm-node/runtime/i18n/instance.mjs +1 -19
  62. package/dist/esm-node/runtime/i18n/react-i18next.mjs +16 -0
  63. package/dist/esm-node/runtime/i18n/utils.mjs +0 -12
  64. package/dist/esm-node/runtime/index.mjs +23 -13
  65. package/dist/esm-node/runtime/localizedPaths.mjs +56 -0
  66. package/dist/esm-node/runtime/routerAdapter.mjs +130 -0
  67. package/dist/esm-node/runtime/utils.mjs +19 -31
  68. package/dist/esm-node/server/index.mjs +46 -8
  69. package/dist/esm-node/shared/localisedUrls.mjs +284 -0
  70. package/dist/types/cli/index.d.ts +1 -0
  71. package/dist/types/runtime/I18nLink.d.ts +6 -0
  72. package/dist/types/runtime/Link.d.ts +66 -0
  73. package/dist/types/runtime/canonicalRoutes.d.ts +60 -0
  74. package/dist/types/runtime/context.d.ts +3 -0
  75. package/dist/types/runtime/hooks.d.ts +4 -2
  76. package/dist/types/runtime/i18n/backend/defaults.node.d.ts +3 -2
  77. package/dist/types/runtime/i18n/backend/middleware.node.d.ts +1 -1
  78. package/dist/types/runtime/i18n/instance.d.ts +4 -6
  79. package/dist/types/runtime/i18n/react-i18next.d.ts +7 -0
  80. package/dist/types/runtime/index.d.ts +6 -1
  81. package/dist/types/runtime/localizedPaths.d.ts +39 -0
  82. package/dist/types/runtime/routerAdapter.d.ts +26 -0
  83. package/dist/types/runtime/types.d.ts +1 -1
  84. package/dist/types/runtime/utils.d.ts +13 -9
  85. package/dist/types/server/index.d.ts +6 -0
  86. package/dist/types/shared/localisedUrls.d.ts +36 -0
  87. package/dist/types/shared/type.d.ts +14 -0
  88. package/package.json +24 -24
  89. package/rstest.config.mts +44 -0
  90. package/src/cli/index.ts +44 -1
  91. package/src/runtime/I18nLink.tsx +14 -51
  92. package/src/runtime/Link.tsx +430 -0
  93. package/src/runtime/canonicalRoutes.ts +93 -0
  94. package/src/runtime/context.tsx +45 -7
  95. package/src/runtime/hooks.ts +13 -4
  96. package/src/runtime/i18n/backend/defaults.node.ts +40 -2
  97. package/src/runtime/i18n/backend/defaults.ts +3 -1
  98. package/src/runtime/i18n/backend/middleware.node.ts +1 -1
  99. package/src/runtime/i18n/instance.ts +3 -30
  100. package/src/runtime/i18n/react-i18next.ts +25 -0
  101. package/src/runtime/i18n/utils.ts +4 -26
  102. package/src/runtime/index.tsx +47 -12
  103. package/src/runtime/localizedPaths.ts +107 -0
  104. package/src/runtime/routerAdapter.tsx +332 -0
  105. package/src/runtime/types.ts +1 -1
  106. package/src/runtime/utils.ts +33 -38
  107. package/src/server/index.ts +108 -11
  108. package/src/shared/localisedUrls.ts +623 -0
  109. package/src/shared/type.ts +14 -0
  110. package/tests/backendDefaults.test.ts +51 -0
  111. package/tests/i18nUtils.test.ts +59 -0
  112. package/tests/link.test.tsx +525 -0
  113. package/tests/linkTypes.test.ts +28 -0
  114. package/tests/localisedUrls.test.ts +536 -0
  115. package/tests/routerAdapter.test.tsx +456 -0
  116. package/tests/type-fixture/linkTypes.fixture.tsx +51 -0
  117. package/tests/type-fixture/tsconfig.json +15 -0
  118. package/dist/esm/rslib-runtime.mjs +0 -18
  119. package/dist/esm-node/rslib-runtime.mjs +0 -19
@@ -0,0 +1,222 @@
1
+ import "node:module";
2
+ import { jsx } from "react/jsx-runtime";
3
+ import { useMemo } from "react";
4
+ import { useModernI18n } from "./context.mjs";
5
+ import { canonicalPath } from "./localizedPaths.mjs";
6
+ import { useI18nRouterAdapter } from "./routerAdapter.mjs";
7
+ import { buildLocalizedUrl, splitUrlTarget } from "./utils.mjs";
8
+ const EXTERNAL_TARGET_RE = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
9
+ const warnedTargets = new Set();
10
+ const warnOnce = (key, message)=>{
11
+ if ('development' !== process.env.NODE_ENV || warnedTargets.has(key)) return;
12
+ warnedTargets.add(key);
13
+ console.warn(message);
14
+ };
15
+ const interpolateRouteParams = (pathname, params)=>{
16
+ if (!/[$:*{]/.test(pathname)) return pathname;
17
+ const resolveParam = (name)=>{
18
+ const value = params?.[name];
19
+ return void 0 === value ? void 0 : String(value);
20
+ };
21
+ const segments = pathname.split('/').map((segment)=>{
22
+ if (!segment) return segment;
23
+ if (segment.startsWith('{-$') && segment.endsWith('}')) {
24
+ const value = resolveParam(segment.slice(3, -1));
25
+ return void 0 === value ? null : encodeURIComponent(value);
26
+ }
27
+ if ('$' === segment || '*' === segment) {
28
+ const value = resolveParam('_splat') ?? resolveParam('*');
29
+ return void 0 === value ? null : value.split('/').map(encodeURIComponent).join('/');
30
+ }
31
+ if (segment.startsWith('$')) {
32
+ const value = resolveParam(segment.slice(1));
33
+ if (void 0 === value) {
34
+ warnOnce(`missing-param:${pathname}:${segment}`, `[plugin-i18n] <Link to="${pathname}"> is missing required param "${segment.slice(1)}".`);
35
+ return segment;
36
+ }
37
+ return encodeURIComponent(value);
38
+ }
39
+ if (segment.startsWith(':')) {
40
+ const optional = segment.endsWith('?');
41
+ const name = segment.slice(1, optional ? -1 : void 0);
42
+ const value = resolveParam(name);
43
+ if (void 0 === value) {
44
+ if (optional) return null;
45
+ warnOnce(`missing-param:${pathname}:${segment}`, `[plugin-i18n] <Link to="${pathname}"> is missing required param "${name}".`);
46
+ return segment;
47
+ }
48
+ return encodeURIComponent(value);
49
+ }
50
+ return segment;
51
+ }).filter((segment)=>null !== segment);
52
+ return segments.join('/') || '/';
53
+ };
54
+ const normalizeSearch = (search, searchFromTo)=>{
55
+ if (search && 'object' == typeof search) {
56
+ const entries = Object.entries(search).filter(([, value])=>null != value);
57
+ const searchObject = Object.fromEntries(entries.map(([key, value])=>[
58
+ key,
59
+ String(value)
60
+ ]));
61
+ const params = new URLSearchParams(searchObject);
62
+ const serialized = params.toString();
63
+ return {
64
+ searchString: serialized ? `?${serialized}` : '',
65
+ searchObject
66
+ };
67
+ }
68
+ const raw = 'string' == typeof search && search ? search : searchFromTo;
69
+ if (!raw) return {
70
+ searchString: '',
71
+ searchObject: void 0
72
+ };
73
+ const searchString = raw.startsWith('?') ? raw : `?${raw}`;
74
+ const searchObject = {};
75
+ new URLSearchParams(searchString).forEach((value, key)=>{
76
+ searchObject[key] = value;
77
+ });
78
+ return {
79
+ searchString,
80
+ searchObject
81
+ };
82
+ };
83
+ const splitActiveProps = (active, activeProps)=>{
84
+ if (!active || !activeProps) return {};
85
+ return activeProps;
86
+ };
87
+ const mergeClassNames = (...values)=>{
88
+ const classNames = values.filter((value)=>'string' == typeof value && value.length > 0);
89
+ return classNames.length > 0 ? classNames.join(' ') : void 0;
90
+ };
91
+ const Link = (props)=>{
92
+ const { to, params, children, hash: hashProp, search: searchProp, hashScrollIntoView, activeOptions, activeProps, prefetch, preload, ...rest } = props;
93
+ const adapter = useI18nRouterAdapter();
94
+ const { language, supportedLanguages, localisedUrls } = useModernI18n();
95
+ const config = {
96
+ languages: supportedLanguages,
97
+ localisedUrls
98
+ };
99
+ const isExternal = EXTERNAL_TARGET_RE.test(to);
100
+ const isBareHash = to.startsWith('#');
101
+ const target = useMemo(()=>{
102
+ if (isExternal || isBareHash) return null;
103
+ const { pathname, search: searchFromTo, hash: hashFromTo } = splitUrlTarget(to);
104
+ const interpolated = interpolateRouteParams(pathname || '/', params);
105
+ const firstSegment = interpolated.split('/').filter(Boolean)[0];
106
+ if (firstSegment && supportedLanguages.includes(firstSegment)) warnOnce(`lang-prefix:${to}`, `[plugin-i18n] <Link to="${to}"> starts with a language prefix. Write language-agnostic canonical paths; the Link localizes them automatically.`);
107
+ const localizedPathname = buildLocalizedUrl(interpolated, language, supportedLanguages, localisedUrls);
108
+ const hash = hashProp ?? (hashFromTo ? hashFromTo.slice(1) : '');
109
+ const { searchString, searchObject } = normalizeSearch(searchProp, searchFromTo);
110
+ return {
111
+ canonicalPathname: interpolated,
112
+ localizedPathname,
113
+ hash,
114
+ searchString,
115
+ searchObject,
116
+ href: `${localizedPathname}${searchString}${hash ? `#${hash}` : ''}`
117
+ };
118
+ }, [
119
+ to,
120
+ params,
121
+ hashProp,
122
+ searchProp,
123
+ isExternal,
124
+ isBareHash,
125
+ language,
126
+ supportedLanguages,
127
+ localisedUrls
128
+ ]);
129
+ const isActive = useMemo(()=>{
130
+ if (!target || !adapter.location) return false;
131
+ const current = canonicalPath(adapter.location.pathname, config);
132
+ const targetCanonical = canonicalPath(target.canonicalPathname, config);
133
+ const exact = activeOptions?.exact ?? '/' === targetCanonical;
134
+ if (current === targetCanonical) return true;
135
+ if (exact) return false;
136
+ return current.startsWith('/' === targetCanonical ? '/' : `${targetCanonical}/`);
137
+ }, [
138
+ target,
139
+ adapter.location,
140
+ activeOptions?.exact,
141
+ supportedLanguages,
142
+ localisedUrls
143
+ ]);
144
+ const resolvedActiveProps = splitActiveProps(isActive, activeProps);
145
+ const activeAttributes = isActive ? {
146
+ 'data-status': 'active',
147
+ 'aria-current': rest['aria-current'] ?? resolvedActiveProps['aria-current'] ?? 'page'
148
+ } : {};
149
+ if (!target) {
150
+ const { replace: _replace, ...anchorProps } = rest;
151
+ return /*#__PURE__*/ jsx("a", {
152
+ href: to,
153
+ ...anchorProps,
154
+ children: children
155
+ });
156
+ }
157
+ const { Link: RouterLink, hasRouter, framework } = adapter;
158
+ if (!hasRouter || !RouterLink) {
159
+ const { replace: _replace, ...anchorProps } = rest;
160
+ const { className: activeClassName, style: activeStyle, ...activeRest } = resolvedActiveProps;
161
+ return /*#__PURE__*/ jsx("a", {
162
+ href: target.href,
163
+ ...anchorProps,
164
+ ...activeRest,
165
+ ...activeAttributes,
166
+ className: mergeClassNames(rest.className, activeClassName),
167
+ style: {
168
+ ...rest.style,
169
+ ...activeStyle
170
+ },
171
+ children: children
172
+ });
173
+ }
174
+ const { className: activeClassName, style: activeStyle, ...activeRest } = resolvedActiveProps;
175
+ const mergedClassName = mergeClassNames(rest.className, activeClassName);
176
+ const mergedStyle = {
177
+ ...rest.style,
178
+ ...activeStyle
179
+ };
180
+ if ('tanstack' === framework) {
181
+ const tanstackPreload = void 0 !== preload ? preload : void 0 === prefetch ? void 0 : 'none' === prefetch ? false : prefetch;
182
+ return /*#__PURE__*/ jsx(RouterLink, {
183
+ to: target.localizedPathname,
184
+ ...target.searchObject ? {
185
+ search: target.searchObject
186
+ } : {},
187
+ ...target.hash ? {
188
+ hash: target.hash
189
+ } : {},
190
+ ...void 0 === hashScrollIntoView ? {} : {
191
+ hashScrollIntoView
192
+ },
193
+ ...void 0 === tanstackPreload ? {} : {
194
+ preload: tanstackPreload
195
+ },
196
+ ...rest,
197
+ ...activeRest,
198
+ ...activeAttributes,
199
+ className: mergedClassName,
200
+ style: mergedStyle,
201
+ children: children
202
+ });
203
+ }
204
+ return /*#__PURE__*/ jsx(RouterLink, {
205
+ to: target.href,
206
+ ...void 0 === prefetch ? {} : {
207
+ prefetch
208
+ },
209
+ ...void 0 === preload ? {} : {
210
+ preload
211
+ },
212
+ ...rest,
213
+ ...activeRest,
214
+ ...activeAttributes,
215
+ className: mergedClassName,
216
+ style: mergedStyle,
217
+ children: children
218
+ });
219
+ };
220
+ const runtime_Link = Link;
221
+ export default runtime_Link;
222
+ export { Link, interpolateRouteParams };
@@ -0,0 +1 @@
1
+ import "node:module";
@@ -1,9 +1,10 @@
1
1
  import "node:module";
2
2
  import { jsx } from "react/jsx-runtime";
3
3
  import { isBrowser } from "@modern-js/runtime";
4
- import { createContext, useCallback, useContext, useMemo } from "react";
4
+ import { createContext, useCallback, useContext, useEffect, useMemo } from "react";
5
5
  import { cacheUserLanguage } from "./i18n/detection/index.mjs";
6
- import { buildLocalizedUrl, detectLanguageFromPath, getEntryPath, shouldIgnoreRedirect, useRouterHooks } from "./utils.mjs";
6
+ import { useI18nRouterAdapter } from "./routerAdapter.mjs";
7
+ import { buildLocalizedUrl, detectLanguageFromPath, getEntryPath, shouldIgnoreRedirect } from "./utils.mjs";
7
8
  const ModernI18nContext = /*#__PURE__*/ createContext(null);
8
9
  const ModernI18nProvider = ({ children, value })=>/*#__PURE__*/ jsx(ModernI18nContext.Provider, {
9
10
  value: value,
@@ -12,9 +13,33 @@ const ModernI18nProvider = ({ children, value })=>/*#__PURE__*/ jsx(ModernI18nCo
12
13
  const useModernI18n = ()=>{
13
14
  const context = useContext(ModernI18nContext);
14
15
  if (!context) throw new Error('useModernI18n must be used within a ModernI18nProvider');
15
- const { language: contextLanguage, i18nInstance, languages, localePathRedirect, ignoreRedirectRoutes, updateLanguage } = context;
16
- const { navigate, location, hasRouter } = useRouterHooks();
17
- const currentLanguage = contextLanguage;
16
+ const { language: contextLanguage, i18nInstance, languages, localePathRedirect, ignoreRedirectRoutes, localisedUrls, updateLanguage } = context;
17
+ const { navigate, location, hasRouter } = useI18nRouterAdapter();
18
+ const pathLanguage = useMemo(()=>{
19
+ if (!localePathRedirect || !location?.pathname) return;
20
+ const detected = detectLanguageFromPath(location.pathname, languages || [], localePathRedirect);
21
+ return detected.detected ? detected.language : void 0;
22
+ }, [
23
+ languages,
24
+ localePathRedirect,
25
+ location?.pathname
26
+ ]);
27
+ const currentLanguage = pathLanguage || contextLanguage;
28
+ useEffect(()=>{
29
+ if (!pathLanguage || pathLanguage === contextLanguage) return;
30
+ updateLanguage?.(pathLanguage);
31
+ i18nInstance?.setLang?.(pathLanguage);
32
+ i18nInstance?.changeLanguage?.(pathLanguage);
33
+ if (isBrowser()) {
34
+ const detectionOptions = i18nInstance.options?.detection;
35
+ cacheUserLanguage(i18nInstance, pathLanguage, detectionOptions);
36
+ }
37
+ }, [
38
+ contextLanguage,
39
+ i18nInstance,
40
+ pathLanguage,
41
+ updateLanguage
42
+ ]);
18
43
  const changeLanguage = useCallback(async (newLang)=>{
19
44
  try {
20
45
  if (!newLang || 'string' != typeof newLang) throw new Error('Language must be a non-empty string');
@@ -31,7 +56,7 @@ const useModernI18n = ()=>{
31
56
  const pathLanguage = detectLanguageFromPath(currentPath, languages || [], localePathRedirect);
32
57
  if (pathLanguage.detected && pathLanguage.language === newLang) return;
33
58
  if (!shouldIgnoreRedirect(relativePath, languages || [], ignoreRedirectRoutes)) {
34
- const newPath = buildLocalizedUrl(relativePath, newLang, languages || []);
59
+ const newPath = buildLocalizedUrl(relativePath, newLang, languages || [], localisedUrls);
35
60
  const newUrl = entryPath + newPath + location.search + location.hash;
36
61
  await navigate(newUrl, {
37
62
  replace: true
@@ -44,7 +69,7 @@ const useModernI18n = ()=>{
44
69
  const pathLanguage = detectLanguageFromPath(currentPath, languages || [], localePathRedirect);
45
70
  if (pathLanguage.detected && pathLanguage.language === newLang) return;
46
71
  if (!shouldIgnoreRedirect(relativePath, languages || [], ignoreRedirectRoutes)) {
47
- const newPath = buildLocalizedUrl(relativePath, newLang, languages || []);
72
+ const newPath = buildLocalizedUrl(relativePath, newLang, languages || [], localisedUrls);
48
73
  const newUrl = entryPath + newPath + window.location.search + window.location.hash;
49
74
  window.history.pushState(null, '', newUrl);
50
75
  }
@@ -59,6 +84,7 @@ const useModernI18n = ()=>{
59
84
  updateLanguage,
60
85
  localePathRedirect,
61
86
  ignoreRedirectRoutes,
87
+ localisedUrls,
62
88
  languages,
63
89
  hasRouter,
64
90
  navigate,
@@ -99,6 +125,7 @@ const useModernI18n = ()=>{
99
125
  changeLanguage,
100
126
  i18nInstance,
101
127
  supportedLanguages: languages || [],
128
+ localisedUrls,
102
129
  isLanguageSupported,
103
130
  isResourcesReady
104
131
  };
@@ -3,7 +3,8 @@ import { isBrowser } from "@modern-js/runtime";
3
3
  import { useEffect, useRef } from "react";
4
4
  import { I18N_SDK_RESOURCES_LOADED_EVENT, getI18nSdkBackendId } from "./i18n/backend/sdk-event.mjs";
5
5
  import { cacheUserLanguage } from "./i18n/detection/index.mjs";
6
- import { buildLocalizedUrl, detectLanguageFromPath, getEntryPath, getPathname, shouldIgnoreRedirect, useRouterHooks } from "./utils.mjs";
6
+ import { useI18nRouterAdapter } from "./routerAdapter.mjs";
7
+ import { buildLocalizedUrl, detectLanguageFromPath, getEntryPath, getPathname, shouldIgnoreRedirect } from "./utils.mjs";
7
8
  function createMinimalI18nInstance(language) {
8
9
  const minimalInstance = {
9
10
  language,
@@ -15,7 +16,7 @@ function createMinimalI18nInstance(language) {
15
16
  };
16
17
  return minimalInstance;
17
18
  }
18
- function createContextValue(lang, i18nInstance, entryName, languages, localePathRedirect, ignoreRedirectRoutes, setLang) {
19
+ function createContextValue(lang, i18nInstance, entryName, languages, localePathRedirect, ignoreRedirectRoutes, localisedUrls, setLang) {
19
20
  const instance = i18nInstance || createMinimalI18nInstance(lang);
20
21
  return {
21
22
  language: lang,
@@ -24,6 +25,7 @@ function createContextValue(lang, i18nInstance, entryName, languages, localePath
24
25
  languages,
25
26
  localePathRedirect,
26
27
  ignoreRedirectRoutes,
28
+ localisedUrls,
27
29
  updateLanguage: setLang
28
30
  };
29
31
  }
@@ -73,9 +75,9 @@ function useSdkResourcesLoader(i18nInstance, setForceUpdate) {
73
75
  setForceUpdate
74
76
  ]);
75
77
  }
76
- function useClientSideRedirect(i18nInstance, localePathRedirect, languages, fallbackLanguage, ignoreRedirectRoutes) {
78
+ function useClientSideRedirect(i18nInstance, localePathRedirect, languages, fallbackLanguage, ignoreRedirectRoutes, localisedUrls) {
77
79
  const hasRedirectedRef = useRef(false);
78
- const { navigate, location, hasRouter } = useRouterHooks();
80
+ const { navigate, location, hasRouter } = useI18nRouterAdapter();
79
81
  useEffect(()=>{
80
82
  if ('browser' !== process.env.MODERN_TARGET) return;
81
83
  if (!localePathRedirect || !i18nInstance) return;
@@ -94,7 +96,7 @@ function useClientSideRedirect(i18nInstance, localePathRedirect, languages, fall
94
96
  const pathDetection = detectLanguageFromPath(currentPathname, languages, localePathRedirect);
95
97
  if (pathDetection.detected) return;
96
98
  const targetLanguage = i18nInstance.language || fallbackLanguage || languages[0] || 'en';
97
- const newPath = buildLocalizedUrl(relativePath, targetLanguage, languages);
99
+ const newPath = buildLocalizedUrl(relativePath, targetLanguage, languages, localisedUrls);
98
100
  const newUrl = entryPath + newPath + currentSearch + currentHash;
99
101
  if (newUrl !== currentPathname + currentSearch + currentHash) {
100
102
  hasRedirectedRef.current = true;
@@ -111,7 +113,8 @@ function useClientSideRedirect(i18nInstance, localePathRedirect, languages, fall
111
113
  i18nInstance,
112
114
  languages,
113
115
  fallbackLanguage,
114
- ignoreRedirectRoutes
116
+ ignoreRedirectRoutes,
117
+ localisedUrls
115
118
  ]);
116
119
  }
117
120
  function useLanguageSync(i18nInstance, localePathRedirect, languages, runtimeContextRef, prevLangRef, setLang) {
@@ -5,7 +5,7 @@ const DEFAULT_I18NEXT_BACKEND_OPTIONS = {
5
5
  };
6
6
  function convertPath(path) {
7
7
  if (!path) return path;
8
- if (path.startsWith('/')) return `${window.__assetPrefix__ || ''}${path}`;
8
+ if (path.startsWith('/')) return "u" < typeof window ? path : `${window.__assetPrefix__ || ''}${path}`;
9
9
  return path;
10
10
  }
11
11
  function convertBackendOptions(options) {
@@ -1,7 +1,28 @@
1
1
  import "node:module";
2
+ import fs from "fs";
3
+ import path_0 from "path";
4
+ const CONVENTIONAL_LOCALES_DIRS = [
5
+ './locales',
6
+ './config/public/locales'
7
+ ];
8
+ const isDirectory = (dirPath)=>{
9
+ try {
10
+ return fs.statSync(dirPath).isDirectory();
11
+ } catch {
12
+ return false;
13
+ }
14
+ };
15
+ const resolveDefaultLocalesDir = (cwd = process.cwd())=>{
16
+ for (const dir of CONVENTIONAL_LOCALES_DIRS)if (isDirectory(path_0.resolve(cwd, dir))) return dir;
17
+ return CONVENTIONAL_LOCALES_DIRS[0];
18
+ };
2
19
  const DEFAULT_I18NEXT_BACKEND_OPTIONS = {
3
- loadPath: './locales/{{lng}}/{{ns}}.json',
4
- addPath: './locales/{{lng}}/{{ns}}.json'
20
+ get loadPath () {
21
+ return `${resolveDefaultLocalesDir()}/{{lng}}/{{ns}}.json`;
22
+ },
23
+ get addPath () {
24
+ return `${resolveDefaultLocalesDir()}/{{lng}}/{{ns}}.json`;
25
+ }
5
26
  };
6
27
  function convertPath(path) {
7
28
  if (!path) return path;
@@ -17,4 +38,4 @@ function convertBackendOptions(options) {
17
38
  if (converted.addPath) converted.addPath = convertPath(converted.addPath);
18
39
  return converted;
19
40
  }
20
- export { DEFAULT_I18NEXT_BACKEND_OPTIONS, convertBackendOptions };
41
+ export { DEFAULT_I18NEXT_BACKEND_OPTIONS, convertBackendOptions, resolveDefaultLocalesDir };
@@ -1,9 +1,9 @@
1
1
  import "node:module";
2
- import i18next_fs_backend from "i18next-fs-backend";
2
+ import cjs from "i18next-fs-backend/cjs";
3
3
  import { useI18nextBackendCommon } from "./middleware.common.mjs";
4
- class FsBackendWithSave extends i18next_fs_backend {
4
+ class FsBackendWithSave extends cjs {
5
5
  save(_language, _namespace, _data) {}
6
6
  }
7
7
  const HttpBackendWithSave = FsBackendWithSave;
8
- const useI18nextBackend = (i18nInstance, backend)=>useI18nextBackendCommon(i18nInstance, FsBackendWithSave, i18next_fs_backend, backend);
8
+ const useI18nextBackend = (i18nInstance, backend)=>useI18nextBackendCommon(i18nInstance, FsBackendWithSave, cjs, backend);
9
9
  export { FsBackendWithSave, HttpBackendWithSave, useI18nextBackend };
@@ -41,14 +41,6 @@ async function createI18nextInstance() {
41
41
  return null;
42
42
  }
43
43
  }
44
- async function tryImportReactI18next() {
45
- try {
46
- const reactI18next = await import("react-i18next");
47
- return reactI18next;
48
- } catch (error) {
49
- return null;
50
- }
51
- }
52
44
  function getI18nextInstanceForProvider(instance) {
53
45
  if (isI18nWrapperInstance(instance)) {
54
46
  const i18nextInstance = getI18nWrapperI18nextInstance(instance);
@@ -65,14 +57,4 @@ async function getI18nInstance(userInstance) {
65
57
  if (i18nextInstance) return i18nextInstance;
66
58
  throw new Error('No i18n instance found');
67
59
  }
68
- async function getInitReactI18next() {
69
- const reactI18nextModule = await tryImportReactI18next();
70
- if (reactI18nextModule) return reactI18nextModule.initReactI18next;
71
- return null;
72
- }
73
- async function getI18nextProvider() {
74
- const reactI18nextModule = await tryImportReactI18next();
75
- if (reactI18nextModule) return reactI18nextModule.I18nextProvider;
76
- return null;
77
- }
78
- export { getActualI18nextInstance, getI18nInstance, getI18nWrapperI18nextInstance, getI18nextInstanceForProvider, getI18nextProvider, getInitReactI18next, isI18nInstance, isI18nWrapperInstance };
60
+ export { getActualI18nextInstance, getI18nInstance, getI18nWrapperI18nextInstance, getI18nextInstanceForProvider, isI18nInstance, isI18nWrapperInstance };
@@ -0,0 +1,16 @@
1
+ import "node:module";
2
+ async function tryImportReactI18next() {
3
+ try {
4
+ return await import("react-i18next");
5
+ } catch (error) {
6
+ return null;
7
+ }
8
+ }
9
+ async function getReactI18nextIntegration() {
10
+ const reactI18nextModule = await tryImportReactI18next();
11
+ return {
12
+ I18nextProvider: reactI18nextModule?.I18nextProvider ?? null,
13
+ initReactI18next: reactI18nextModule?.initReactI18next ?? null
14
+ };
15
+ }
16
+ export { getReactI18nextIntegration };
@@ -101,18 +101,6 @@ const initializeI18nInstance = async (i18nInstance, finalLanguage, fallbackLangu
101
101
  };
102
102
  }
103
103
  }
104
- if (mergedBackend && hasOptions(i18nInstance)) {
105
- const defaultNS = initOptions.defaultNS || initOptions.ns || 'translation';
106
- const ns = Array.isArray(defaultNS) ? defaultNS[0] : defaultNS;
107
- let retries = 20;
108
- while(retries > 0){
109
- const actualInstance = getActualI18nextInstance(i18nInstance);
110
- const store = actualInstance.store;
111
- if (store?.data?.[finalLanguage]?.[ns]) break;
112
- await new Promise((resolve)=>setTimeout(resolve, 100));
113
- retries--;
114
- }
115
- }
116
104
  }
117
105
  };
118
106
  function hasOptions(instance) {
@@ -11,26 +11,31 @@ import { mergeBackendOptions } from "./i18n/backend/index.mjs";
11
11
  import { useI18nextBackend } from "./i18n/backend/middleware.mjs";
12
12
  import { detectLanguageWithPriority, exportServerLngToWindow, mergeDetectionOptions } from "./i18n/detection/index.mjs";
13
13
  import { useI18nextLanguageDetector } from "./i18n/detection/middleware.mjs";
14
- import { getI18nextInstanceForProvider, getI18nextProvider, getInitReactI18next } from "./i18n/instance.mjs";
14
+ import { getI18nextInstanceForProvider } from "./i18n/instance.mjs";
15
15
  import { changeI18nLanguage, ensureLanguageMatch, initializeI18nInstance, setupClonedInstance } from "./i18n/utils.mjs";
16
- import { getPathname } from "./utils.mjs";
16
+ import { buildLocalizedUrl, getPathname, splitUrlTarget } from "./utils.mjs";
17
17
  import "./types.mjs";
18
18
  const i18nPlugin = (options)=>({
19
19
  name: '@modern-js/plugin-i18n',
20
20
  setup: (api)=>{
21
- const { entryName, i18nInstance: userI18nInstance, initOptions, localeDetection, backend, htmlLangAttr = false } = options;
22
- const { localePathRedirect = false, i18nextDetector = true, languages = [], fallbackLanguage = 'en', detection, ignoreRedirectRoutes } = localeDetection || {};
21
+ const { entryName, i18nInstance: userI18nInstance, initOptions, localeDetection, backend, htmlLangAttr = false, reactI18next = true } = options;
22
+ const { localePathRedirect = false, i18nextDetector = true, languages = [], fallbackLanguage = 'en', detection, ignoreRedirectRoutes, localisedUrls } = localeDetection || {};
23
23
  const { enabled: backendEnabled = false } = backend || {};
24
24
  let latestI18nInstance;
25
25
  let I18nextProvider;
26
+ const loadReactI18nextIntegration = async ()=>{
27
+ if (!reactI18next) return null;
28
+ const { getReactI18nextIntegration } = await import("./i18n/react-i18next.mjs");
29
+ return getReactI18nextIntegration();
30
+ };
26
31
  api.onBeforeRender(async (context)=>{
27
32
  let i18nInstance = await getI18nInstance(userI18nInstance);
28
33
  const { i18n: otherConfig } = api.getRuntimeConfig();
29
34
  const { initOptions: otherInitOptions } = otherConfig || {};
30
35
  const userInitOptions = merge(otherInitOptions || {}, initOptions || {});
31
- const initReactI18next = await getInitReactI18next();
32
- I18nextProvider = await getI18nextProvider();
33
- if (initReactI18next) i18nInstance.use(initReactI18next);
36
+ const reactI18nextIntegration = await loadReactI18nextIntegration();
37
+ I18nextProvider = reactI18nextIntegration?.I18nextProvider ?? null;
38
+ if (reactI18nextIntegration?.initReactI18next) i18nInstance.use(reactI18nextIntegration.initReactI18next);
34
39
  const pathname = getPathname(context);
35
40
  if (i18nextDetector) useI18nextLanguageDetector(i18nInstance);
36
41
  const mergedDetection = mergeDetectionOptions(i18nextDetector, detection, localePathRedirect, userInitOptions);
@@ -90,16 +95,18 @@ const i18nPlugin = (options)=>({
90
95
  ]);
91
96
  useSdkResourcesLoader(i18nInstance, setForceUpdate);
92
97
  useLanguageSync(i18nInstance, localePathRedirect, languages, runtimeContextRef, prevLangRef, setLang);
93
- useClientSideRedirect(i18nInstance, localePathRedirect, languages, fallbackLanguage, ignoreRedirectRoutes);
94
- const contextValue = useMemo(()=>createContextValue(lang, i18nInstance, entryName, languages, localePathRedirect, ignoreRedirectRoutes, setLang), [
98
+ useClientSideRedirect(i18nInstance, localePathRedirect, languages, fallbackLanguage, ignoreRedirectRoutes, localisedUrls);
99
+ const contextValue = useMemo(()=>createContextValue(lang, i18nInstance, entryName, languages, localePathRedirect, ignoreRedirectRoutes, localisedUrls, setLang), [
95
100
  lang,
96
101
  i18nInstance,
97
102
  entryName,
98
103
  languages,
99
104
  localePathRedirect,
100
105
  ignoreRedirectRoutes,
106
+ localisedUrls,
101
107
  forceUpdate
102
108
  ]);
109
+ const children = props.children;
103
110
  const appContent = /*#__PURE__*/ jsxs(Fragment, {
104
111
  children: [
105
112
  Boolean(htmlLangAttr) && /*#__PURE__*/ jsx(Helmet, {
@@ -109,9 +116,10 @@ const i18nPlugin = (options)=>({
109
116
  }),
110
117
  /*#__PURE__*/ jsx(ModernI18nProvider, {
111
118
  value: contextValue,
112
- children: /*#__PURE__*/ jsx(App, {
113
- ...props
114
- })
119
+ children: App ? /*#__PURE__*/ jsx(App, {
120
+ ...props,
121
+ children: children
122
+ }) : children
115
123
  })
116
124
  ]
117
125
  });
@@ -129,5 +137,7 @@ const i18nPlugin = (options)=>({
129
137
  });
130
138
  const runtime = i18nPlugin;
131
139
  export { I18nLink } from "./I18nLink.mjs";
140
+ export { Link } from "./Link.mjs";
141
+ export { canonicalPath, localizePath, useLocalizedLocation, useLocalizedPaths } from "./localizedPaths.mjs";
132
142
  export default runtime;
133
- export { i18nPlugin, useModernI18n };
143
+ export { buildLocalizedUrl, i18nPlugin, splitUrlTarget, useModernI18n };
@@ -0,0 +1,56 @@
1
+ import "node:module";
2
+ import { useMemo } from "react";
3
+ import { canonicalTargetPathname } from "../shared/localisedUrls.mjs";
4
+ import { useModernI18n } from "./context.mjs";
5
+ import { useI18nRouterAdapter } from "./routerAdapter.mjs";
6
+ import { buildLocalizedUrl, splitUrlTarget } from "./utils.mjs";
7
+ const localizePath = (pathname, language, config)=>buildLocalizedUrl(pathname, language, config.languages, config.localisedUrls);
8
+ const canonicalPath = (target, config)=>{
9
+ const { pathname, search, hash } = splitUrlTarget(target);
10
+ const resolvedPath = canonicalTargetPathname(pathname, config.languages, config.localisedUrls);
11
+ return `${resolvedPath}${search}${hash}`;
12
+ };
13
+ const useLocalizedPaths = ()=>{
14
+ const { supportedLanguages, localisedUrls } = useModernI18n();
15
+ return useMemo(()=>{
16
+ const config = {
17
+ languages: supportedLanguages,
18
+ localisedUrls
19
+ };
20
+ return {
21
+ localizePath: (pathname, language)=>localizePath(pathname, language, config),
22
+ canonicalPath: (pathname)=>canonicalPath(pathname, config)
23
+ };
24
+ }, [
25
+ supportedLanguages,
26
+ localisedUrls
27
+ ]);
28
+ };
29
+ const useLocalizedLocation = ()=>{
30
+ const { language, supportedLanguages, localisedUrls } = useModernI18n();
31
+ const { location } = useI18nRouterAdapter();
32
+ const pathname = location?.pathname ?? '/';
33
+ const search = location?.search ?? '';
34
+ const hash = location?.hash ?? '';
35
+ return useMemo(()=>{
36
+ const config = {
37
+ languages: supportedLanguages,
38
+ localisedUrls
39
+ };
40
+ const alternates = {};
41
+ for (const supportedLanguage of supportedLanguages)alternates[supportedLanguage] = `${localizePath(pathname, supportedLanguage, config)}${search}${hash}`;
42
+ return {
43
+ language,
44
+ canonical: canonicalPath(pathname, config),
45
+ alternates
46
+ };
47
+ }, [
48
+ language,
49
+ supportedLanguages,
50
+ localisedUrls,
51
+ pathname,
52
+ search,
53
+ hash
54
+ ]);
55
+ };
56
+ export { canonicalPath, localizePath, useLocalizedLocation, useLocalizedPaths };