@bleedingdev/modern-js-plugin-i18n 3.5.0-ultramodern.30 → 3.5.0-ultramodern.31

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 (161) hide show
  1. package/dist/cjs/cli/index.js +2 -1
  2. package/dist/cjs/runtime/Link.js +8 -89
  3. package/dist/cjs/runtime/context.js +18 -82
  4. package/dist/cjs/runtime/contextHelpers.js +137 -0
  5. package/dist/cjs/runtime/core.js +29 -132
  6. package/dist/cjs/runtime/i18n/detection/cache.js +149 -0
  7. package/dist/cjs/runtime/i18n/detection/detector.js +100 -0
  8. package/dist/cjs/runtime/i18n/detection/index.js +8 -263
  9. package/dist/cjs/runtime/i18n/detection/initOptions.js +69 -0
  10. package/dist/cjs/runtime/i18n/detection/language.js +62 -0
  11. package/dist/cjs/runtime/i18n/detection/path.js +49 -0
  12. package/dist/cjs/runtime/i18n/detection/priority.js +66 -0
  13. package/dist/cjs/runtime/i18n/detection/ssr.js +70 -0
  14. package/dist/cjs/runtime/i18n/detection/types.js +18 -0
  15. package/dist/cjs/runtime/linkHelpers.js +148 -0
  16. package/dist/cjs/runtime/pluginSetup.js +102 -0
  17. package/dist/cjs/runtime/providerComposition.js +113 -0
  18. package/dist/cjs/runtime/reactI18next.js +43 -0
  19. package/dist/cjs/server/apiPrefix.js +72 -0
  20. package/dist/cjs/server/detectorOptions.js +97 -0
  21. package/dist/cjs/server/index.js +17 -152
  22. package/dist/cjs/server/redirectPolicy.js +102 -0
  23. package/dist/cjs/shared/localisedUrls/config.js +49 -0
  24. package/dist/cjs/shared/localisedUrls/index.js +75 -0
  25. package/dist/cjs/shared/localisedUrls/normalise.js +87 -0
  26. package/dist/cjs/shared/localisedUrls/pathname.js +65 -0
  27. package/dist/cjs/shared/localisedUrls/patterns.js +130 -0
  28. package/dist/cjs/shared/localisedUrls/resolve.js +91 -0
  29. package/dist/cjs/shared/localisedUrls/routes.js +129 -0
  30. package/dist/cjs/shared/localisedUrls/types.js +18 -0
  31. package/dist/cjs/shared/localisedUrls.js +13 -294
  32. package/dist/esm/cli/index.mjs +2 -1
  33. package/dist/esm/runtime/Link.mjs +1 -82
  34. package/dist/esm/runtime/context.mjs +18 -82
  35. package/dist/esm/runtime/contextHelpers.mjs +84 -0
  36. package/dist/esm/runtime/core.mjs +30 -133
  37. package/dist/esm/runtime/i18n/detection/cache.mjs +102 -0
  38. package/dist/esm/runtime/i18n/detection/detector.mjs +62 -0
  39. package/dist/esm/runtime/i18n/detection/index.mjs +4 -260
  40. package/dist/esm/runtime/i18n/detection/initOptions.mjs +28 -0
  41. package/dist/esm/runtime/i18n/detection/language.mjs +21 -0
  42. package/dist/esm/runtime/i18n/detection/path.mjs +11 -0
  43. package/dist/esm/runtime/i18n/detection/priority.mjs +28 -0
  44. package/dist/esm/runtime/i18n/detection/ssr.mjs +26 -0
  45. package/dist/esm/runtime/i18n/detection/types.mjs +0 -0
  46. package/dist/esm/runtime/linkHelpers.mjs +98 -0
  47. package/dist/esm/runtime/pluginSetup.mjs +64 -0
  48. package/dist/esm/runtime/providerComposition.mjs +75 -0
  49. package/dist/esm/runtime/reactI18next.mjs +5 -0
  50. package/dist/esm/server/apiPrefix.mjs +31 -0
  51. package/dist/esm/server/detectorOptions.mjs +59 -0
  52. package/dist/esm/server/index.mjs +4 -139
  53. package/dist/esm/server/redirectPolicy.mjs +52 -0
  54. package/dist/esm/shared/localisedUrls/config.mjs +11 -0
  55. package/dist/esm/shared/localisedUrls/index.mjs +6 -0
  56. package/dist/esm/shared/localisedUrls/normalise.mjs +37 -0
  57. package/dist/esm/shared/localisedUrls/pathname.mjs +24 -0
  58. package/dist/esm/shared/localisedUrls/patterns.mjs +86 -0
  59. package/dist/esm/shared/localisedUrls/resolve.mjs +50 -0
  60. package/dist/esm/shared/localisedUrls/routes.mjs +88 -0
  61. package/dist/esm/shared/localisedUrls/types.mjs +0 -0
  62. package/dist/esm/shared/localisedUrls.mjs +1 -283
  63. package/dist/esm-node/cli/index.mjs +2 -1
  64. package/dist/esm-node/runtime/Link.mjs +1 -82
  65. package/dist/esm-node/runtime/context.mjs +18 -82
  66. package/dist/esm-node/runtime/contextHelpers.mjs +85 -0
  67. package/dist/esm-node/runtime/core.mjs +30 -133
  68. package/dist/esm-node/runtime/i18n/detection/cache.mjs +103 -0
  69. package/dist/esm-node/runtime/i18n/detection/detector.mjs +63 -0
  70. package/dist/esm-node/runtime/i18n/detection/index.mjs +4 -260
  71. package/dist/esm-node/runtime/i18n/detection/initOptions.mjs +29 -0
  72. package/dist/esm-node/runtime/i18n/detection/language.mjs +22 -0
  73. package/dist/esm-node/runtime/i18n/detection/path.mjs +12 -0
  74. package/dist/esm-node/runtime/i18n/detection/priority.mjs +29 -0
  75. package/dist/esm-node/runtime/i18n/detection/ssr.mjs +27 -0
  76. package/dist/esm-node/runtime/i18n/detection/types.mjs +1 -0
  77. package/dist/esm-node/runtime/linkHelpers.mjs +99 -0
  78. package/dist/esm-node/runtime/pluginSetup.mjs +65 -0
  79. package/dist/esm-node/runtime/providerComposition.mjs +76 -0
  80. package/dist/esm-node/runtime/reactI18next.mjs +6 -0
  81. package/dist/esm-node/server/apiPrefix.mjs +32 -0
  82. package/dist/esm-node/server/detectorOptions.mjs +60 -0
  83. package/dist/esm-node/server/index.mjs +4 -139
  84. package/dist/esm-node/server/redirectPolicy.mjs +53 -0
  85. package/dist/esm-node/shared/localisedUrls/config.mjs +12 -0
  86. package/dist/esm-node/shared/localisedUrls/index.mjs +7 -0
  87. package/dist/esm-node/shared/localisedUrls/normalise.mjs +38 -0
  88. package/dist/esm-node/shared/localisedUrls/pathname.mjs +25 -0
  89. package/dist/esm-node/shared/localisedUrls/patterns.mjs +87 -0
  90. package/dist/esm-node/shared/localisedUrls/resolve.mjs +51 -0
  91. package/dist/esm-node/shared/localisedUrls/routes.mjs +89 -0
  92. package/dist/esm-node/shared/localisedUrls/types.mjs +1 -0
  93. package/dist/esm-node/shared/localisedUrls.mjs +1 -283
  94. package/dist/types/runtime/Link.d.ts +3 -7
  95. package/dist/types/runtime/context.d.ts +2 -2
  96. package/dist/types/runtime/contextHelpers.d.ts +28 -0
  97. package/dist/types/runtime/core.d.ts +3 -7
  98. package/dist/types/runtime/i18n/detection/cache.d.ts +14 -0
  99. package/dist/types/runtime/i18n/detection/detector.d.ts +8 -0
  100. package/dist/types/runtime/i18n/detection/index.d.ts +5 -50
  101. package/dist/types/runtime/i18n/detection/initOptions.d.ts +10 -0
  102. package/dist/types/runtime/i18n/detection/language.d.ts +11 -0
  103. package/dist/types/runtime/i18n/detection/path.d.ts +5 -0
  104. package/dist/types/runtime/i18n/detection/priority.d.ts +10 -0
  105. package/dist/types/runtime/i18n/detection/ssr.d.ts +9 -0
  106. package/dist/types/runtime/i18n/detection/types.d.ts +29 -0
  107. package/dist/types/runtime/i18n/react-i18next.d.ts +1 -6
  108. package/dist/types/runtime/linkHelpers.d.ts +17 -0
  109. package/dist/types/runtime/pluginSetup.d.ts +32 -0
  110. package/dist/types/runtime/providerComposition.d.ts +15 -0
  111. package/dist/types/runtime/reactI18next.d.ts +7 -0
  112. package/dist/types/server/apiPrefix.d.ts +7 -0
  113. package/dist/types/server/detectorOptions.d.ts +21 -0
  114. package/dist/types/server/index.d.ts +1 -6
  115. package/dist/types/server/redirectPolicy.d.ts +16 -0
  116. package/dist/types/shared/localisedUrls/config.d.ts +9 -0
  117. package/dist/types/shared/localisedUrls/index.d.ts +7 -0
  118. package/dist/types/shared/localisedUrls/normalise.d.ts +10 -0
  119. package/dist/types/shared/localisedUrls/pathname.d.ts +3 -0
  120. package/dist/types/shared/localisedUrls/patterns.d.ts +5 -0
  121. package/dist/types/shared/localisedUrls/resolve.d.ts +8 -0
  122. package/dist/types/shared/localisedUrls/routes.d.ts +3 -0
  123. package/dist/types/shared/localisedUrls/types.d.ts +14 -0
  124. package/dist/types/shared/localisedUrls.d.ts +2 -42
  125. package/package.json +10 -10
  126. package/src/cli/index.ts +3 -2
  127. package/src/runtime/Link.tsx +11 -138
  128. package/src/runtime/context.tsx +42 -196
  129. package/src/runtime/contextHelpers.ts +232 -0
  130. package/src/runtime/core.tsx +42 -273
  131. package/src/runtime/i18n/detection/cache.ts +175 -0
  132. package/src/runtime/i18n/detection/detector.ts +157 -0
  133. package/src/runtime/i18n/detection/index.ts +10 -641
  134. package/src/runtime/i18n/detection/initOptions.ts +74 -0
  135. package/src/runtime/i18n/detection/language.ts +64 -0
  136. package/src/runtime/i18n/detection/path.ts +41 -0
  137. package/src/runtime/i18n/detection/priority.ts +82 -0
  138. package/src/runtime/i18n/detection/ssr.ts +47 -0
  139. package/src/runtime/i18n/detection/types.ts +33 -0
  140. package/src/runtime/i18n/react-i18next.ts +1 -6
  141. package/src/runtime/linkHelpers.ts +174 -0
  142. package/src/runtime/pluginSetup.ts +189 -0
  143. package/src/runtime/providerComposition.tsx +142 -0
  144. package/src/runtime/reactI18next.ts +20 -0
  145. package/src/server/apiPrefix.ts +67 -0
  146. package/src/server/detectorOptions.ts +105 -0
  147. package/src/server/index.ts +12 -327
  148. package/src/server/redirectPolicy.ts +152 -0
  149. package/src/shared/localisedUrls/config.ts +18 -0
  150. package/src/shared/localisedUrls/index.ts +13 -0
  151. package/src/shared/localisedUrls/normalise.ts +67 -0
  152. package/src/shared/localisedUrls/pathname.ts +57 -0
  153. package/src/shared/localisedUrls/patterns.ts +160 -0
  154. package/src/shared/localisedUrls/resolve.ts +118 -0
  155. package/src/shared/localisedUrls/routes.ts +226 -0
  156. package/src/shared/localisedUrls/types.ts +18 -0
  157. package/src/shared/localisedUrls.ts +20 -629
  158. package/tests/link.test.tsx +111 -0
  159. package/tests/localisedUrls.test.ts +50 -0
  160. package/tests/reactI18nextRuntimeBoundary.test.ts +5 -2
  161. package/tests/routerAdapter.test.tsx +56 -0
@@ -1,284 +1,2 @@
1
1
  import "node:module";
2
- const LOCALE_PARAM_NAMES = new Set([
3
- 'lang',
4
- 'locale',
5
- 'language'
6
- ]);
7
- const normaliseSlashes = (path)=>{
8
- const withoutDuplicateSlashes = path.replace(/\/+/g, '/');
9
- const withLeadingSlash = withoutDuplicateSlashes.startsWith('/') ? withoutDuplicateSlashes : `/${withoutDuplicateSlashes}`;
10
- return withLeadingSlash.length > 1 ? withLeadingSlash.replace(/\/+$/, '') : withLeadingSlash;
11
- };
12
- const normalisePathPattern = (path)=>normaliseSlashes(path).replace(/\[(.+?)\]/g, ':$1');
13
- const normalisePathname = (pathname)=>normaliseSlashes(pathname);
14
- const normaliseRoutePath = (path)=>{
15
- const normalized = normalisePathPattern(path);
16
- return '/' === normalized ? '' : normalized.slice(1);
17
- };
18
- const getLocaleParamSegment = (segment)=>{
19
- if (!segment.startsWith(':')) return null;
20
- const paramName = segment.slice(1).replace(/\?$/, '');
21
- return LOCALE_PARAM_NAMES.has(paramName) ? segment : null;
22
- };
23
- const splitPathSegments = (path)=>{
24
- if (!path) return [];
25
- return normalisePathPattern(path).split('/').filter(Boolean);
26
- };
27
- const stripLeadingLocaleParam = (path)=>{
28
- const segments = splitPathSegments(path);
29
- const leadingLocaleParam = getLocaleParamSegment(segments[0] || '');
30
- if (!leadingLocaleParam) return path;
31
- const remainingPath = segments.slice(1).join('/');
32
- return remainingPath ? `/${remainingPath}` : void 0;
33
- };
34
- const getLeadingLocaleParam = (path)=>{
35
- const segments = splitPathSegments(path);
36
- return getLocaleParamSegment(segments[0] || '');
37
- };
38
- const resolveLocalisedUrlsConfig = (option)=>{
39
- if (option && 'object' == typeof option && Object.keys(option).length > 0) return {
40
- enabled: true,
41
- map: option
42
- };
43
- return {
44
- enabled: false,
45
- map: {}
46
- };
47
- };
48
- const isLocalisableRoutePath = (path)=>{
49
- const pathWithoutLocale = stripLeadingLocaleParam(path);
50
- if (!pathWithoutLocale || '/' === pathWithoutLocale || '*' === pathWithoutLocale) return false;
51
- return true;
52
- };
53
- const joinPath = (parentPath, routePath)=>{
54
- if (!isLocalisableRoutePath(routePath)) return parentPath;
55
- const segment = normaliseRoutePath(stripLeadingLocaleParam(routePath) || '');
56
- return normalisePathPattern(`${parentPath}/${segment}`);
57
- };
58
- const ensureLocalisedUrlsForPath = (canonicalPath, languages, localisedUrls)=>{
59
- const entry = localisedUrls[canonicalPath];
60
- if (!entry) throw new Error(`localisedUrls is enabled, but route "${canonicalPath}" does not define localised URLs for languages: ${languages.join(', ')}. Add localisedUrls["${canonicalPath}"] or set localeDetection.localisedUrls to false.`);
61
- const missingLanguages = languages.filter((language)=>!entry[language]);
62
- if (missingLanguages.length > 0) throw new Error(`localisedUrls["${canonicalPath}"] is missing languages: ${missingLanguages.join(', ')}. Every configured language must have a localised URL.`);
63
- return entry;
64
- };
65
- const validateLocalisedUrls = (routes, languages, localisedUrls)=>{
66
- const visit = (route, parentPath)=>{
67
- const canonicalPath = joinPath(parentPath, route.path);
68
- if (isLocalisableRoutePath(route.path)) ensureLocalisedUrlsForPath(canonicalPath, languages, localisedUrls);
69
- if ('children' in route && route.children) route.children.forEach((child)=>visit(child, canonicalPath));
70
- };
71
- routes.forEach((route)=>visit(route, ''));
72
- };
73
- const getLocalisedRoutePaths = (canonicalPath, parentLocalisedPaths, languages, entry)=>{
74
- const paths = languages.map((language)=>{
75
- const fullPath = normalisePathPattern(entry[language]);
76
- const parentPath = normalisePathPattern(parentLocalisedPaths[language] || '/');
77
- if ('/' === parentPath) return normaliseRoutePath(fullPath) || void 0;
78
- const parentPrefix = `${parentPath}/`;
79
- if (!fullPath.startsWith(parentPrefix)) throw new Error(`localisedUrls["${canonicalPath}"].${language} must be nested under "${parentPath}" because its parent route is localised there.`);
80
- return normaliseRoutePath(fullPath.slice(parentPath.length));
81
- });
82
- return Array.from(new Set(paths.filter(Boolean)));
83
- };
84
- const transformLocalisedRoute = (route, parentCanonicalPath, parentLocalisedPaths, languages, localisedUrls)=>{
85
- const canonicalPath = joinPath(parentCanonicalPath, route.path);
86
- const localisedUrlEntry = isLocalisableRoutePath(route.path) ? ensureLocalisedUrlsForPath(canonicalPath, languages, localisedUrls) : void 0;
87
- const routeLocalisedPaths = localisedUrlEntry ? languages.reduce((acc, language)=>{
88
- acc[language] = normalisePathPattern(localisedUrlEntry[language]);
89
- return acc;
90
- }, {}) : parentLocalisedPaths;
91
- const children = 'children' in route && route.children ? route.children.flatMap((child)=>transformLocalisedRoute(child, canonicalPath, routeLocalisedPaths, languages, localisedUrls)) : void 0;
92
- const baseRoute = {
93
- ...route,
94
- ...children ? {
95
- children
96
- } : {}
97
- };
98
- if (!localisedUrlEntry) return [
99
- baseRoute
100
- ];
101
- return getLocalisedRoutePaths(canonicalPath, parentLocalisedPaths, languages, localisedUrlEntry).map((localisedPath, index)=>cloneRouteWithLocalisedPath(baseRoute, localisedPath, index, canonicalPath));
102
- };
103
- const legalRouteIdPart = (value)=>value.replace(/[^a-zA-Z0-9_$-]+/g, '_').replace(/^_+|_+$/g, '') || 'index';
104
- const suffixRouteIds = (route, suffix)=>{
105
- const children = 'children' in route && route.children ? route.children.map((child)=>suffixRouteIds(child, suffix)) : void 0;
106
- return {
107
- ...route,
108
- ...route.id ? {
109
- id: `${route.id}__localised_${suffix}`
110
- } : {},
111
- ...children ? {
112
- children
113
- } : {}
114
- };
115
- };
116
- const cloneRouteWithLocalisedPath = (route, path, index, canonicalPath)=>{
117
- const leadingLocaleParam = getLeadingLocaleParam(route.path);
118
- const localisedPath = leadingLocaleParam ? normaliseRoutePath(`${leadingLocaleParam}/${path}`) : path;
119
- const routeWithPath = {
120
- ...route,
121
- path: localisedPath
122
- };
123
- routeWithPath.modernCanonicalPath = canonicalPath;
124
- return 0 === index ? routeWithPath : suffixRouteIds(routeWithPath, legalRouteIdPart(localisedPath));
125
- };
126
- const applyLocalisedUrlsToRoutes = (routes, languages, localisedUrls)=>{
127
- const rootLocalisedPaths = languages.reduce((acc, language)=>{
128
- acc[language] = '/';
129
- return acc;
130
- }, {});
131
- validateLocalisedUrls(routes, languages, localisedUrls);
132
- return routes.flatMap((route)=>transformLocalisedRoute(route, '', rootLocalisedPaths, languages, localisedUrls));
133
- };
134
- const escapeRegExp = (value)=>value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
135
- const getParamName = (segment)=>segment.slice(1).replace(/\?$/, '');
136
- const compiledPathPatternCache = new Map();
137
- const compilePathPattern = (pattern)=>{
138
- const normalizedPattern = normalisePathPattern(pattern);
139
- const cached = compiledPathPatternCache.get(normalizedPattern);
140
- if (cached) return cached;
141
- const names = [];
142
- const segments = normalizedPattern.split('/').filter(Boolean);
143
- const source = segments.map((segment)=>{
144
- if (segment.startsWith(':')) {
145
- names.push(getParamName(segment));
146
- const paramPattern = '([^/]+)';
147
- return segment.endsWith('?') ? `(?:/${paramPattern})?` : `/${paramPattern}`;
148
- }
149
- if ('*' === segment) {
150
- names.push('*');
151
- return '/(.*)';
152
- }
153
- return `/${escapeRegExp(segment)}`;
154
- }).join('');
155
- const compiled = {
156
- names,
157
- regexp: new RegExp(`^${source || '/'}$`)
158
- };
159
- compiledPathPatternCache.set(normalizedPattern, compiled);
160
- return compiled;
161
- };
162
- const getPatternSpecificity = (pattern)=>{
163
- const segments = normalisePathPattern(pattern).split('/').filter(Boolean);
164
- let staticSegments = 0;
165
- let dynamicSegments = 0;
166
- let splatSegments = 0;
167
- for (const segment of segments)if ('*' === segment) splatSegments++;
168
- else if (segment.startsWith(':')) dynamicSegments++;
169
- else staticSegments++;
170
- return {
171
- staticSegments,
172
- dynamicSegments,
173
- splatSegments,
174
- totalSegments: segments.length
175
- };
176
- };
177
- const comparePatternSpecificity = (left, right)=>{
178
- const a = getPatternSpecificity(left);
179
- const b = getPatternSpecificity(right);
180
- return b.staticSegments - a.staticSegments || b.totalSegments - a.totalSegments || a.splatSegments - b.splatSegments || a.dynamicSegments - b.dynamicSegments;
181
- };
182
- const sortPatternsBySpecificity = (patterns)=>patterns.map((pattern, index)=>({
183
- pattern,
184
- index
185
- })).sort((left, right)=>comparePatternSpecificity(left.pattern.pattern, right.pattern.pattern) || left.index - right.index).map(({ pattern })=>pattern);
186
- const decodePathParam = (value)=>{
187
- try {
188
- return decodeURIComponent(value);
189
- } catch {
190
- return null;
191
- }
192
- };
193
- const matchPathPattern = (pathname, pattern)=>{
194
- const { names, regexp } = compilePathPattern(pattern);
195
- const match = regexp.exec(normalisePathname(pathname));
196
- if (!match) return null;
197
- const params = {};
198
- for(let index = 0; index < names.length; index++){
199
- const decoded = decodePathParam(match[index + 1] || '');
200
- if (null === decoded) return null;
201
- params[names[index]] = decoded;
202
- }
203
- return params;
204
- };
205
- const buildPathFromPattern = (pattern, params)=>{
206
- const segments = normalisePathPattern(pattern).split('/').filter(Boolean);
207
- const path = segments.map((segment)=>{
208
- if (segment.startsWith(':')) {
209
- const param = params[getParamName(segment)];
210
- return param ? encodeURIComponent(param) : '';
211
- }
212
- if ('*' === segment) return params['*'] || '';
213
- return segment;
214
- }).filter(Boolean).join('/');
215
- return `/${path}`;
216
- };
217
- const resolveLocalisedPath = (pathname, targetLanguage, languages, localisedUrls)=>{
218
- const normalizedPathname = normalisePathname(pathname);
219
- const canonicalCandidates = sortPatternsBySpecificity(Object.entries(localisedUrls).map(([canonicalPattern, localisedUrlEntry])=>({
220
- pattern: canonicalPattern,
221
- canonicalPattern,
222
- localisedUrlEntry
223
- })));
224
- for (const { canonicalPattern, localisedUrlEntry } of canonicalCandidates){
225
- const targetPattern = localisedUrlEntry[targetLanguage];
226
- if (!targetPattern) continue;
227
- const params = matchPathPattern(normalizedPathname, canonicalPattern);
228
- if (params) return buildPathFromPattern(targetPattern, params);
229
- }
230
- const localisedCandidates = sortPatternsBySpecificity(Object.values(localisedUrls).flatMap((localisedUrlEntry)=>{
231
- const targetPattern = localisedUrlEntry[targetLanguage];
232
- if (!targetPattern) return [];
233
- return languages.map((language)=>localisedUrlEntry[language]).filter((sourcePattern)=>Boolean(sourcePattern)).map((sourcePattern)=>({
234
- pattern: sourcePattern,
235
- sourcePattern,
236
- targetPattern
237
- }));
238
- }));
239
- for (const { sourcePattern, targetPattern } of localisedCandidates){
240
- const params = matchPathPattern(normalizedPathname, sourcePattern);
241
- if (params) return buildPathFromPattern(targetPattern, params);
242
- }
243
- return normalizedPathname;
244
- };
245
- const resolveCanonicalLocalisedPath = (pathname, languages, localisedUrls)=>{
246
- const normalizedPathname = normalisePathname(pathname);
247
- const canonicalCandidates = sortPatternsBySpecificity(Object.entries(localisedUrls).map(([canonicalPattern, localisedUrlEntry])=>({
248
- pattern: canonicalPattern,
249
- canonicalPattern,
250
- localisedUrlEntry
251
- })));
252
- for (const { canonicalPattern, localisedUrlEntry } of canonicalCandidates){
253
- const canonicalParams = matchPathPattern(normalizedPathname, canonicalPattern);
254
- if (canonicalParams) return buildPathFromPattern(canonicalPattern, canonicalParams);
255
- for (const language of languages){
256
- const sourcePattern = localisedUrlEntry[language];
257
- if (!sourcePattern) continue;
258
- const params = matchPathPattern(normalizedPathname, sourcePattern);
259
- if (params) return buildPathFromPattern(canonicalPattern, params);
260
- }
261
- }
262
- return normalizedPathname;
263
- };
264
- const stripLanguagePrefix = (pathname, languages)=>{
265
- const segments = pathname.split('/').filter(Boolean);
266
- if (segments.length > 0 && languages.includes(segments[0])) return `/${segments.slice(1).join('/')}`;
267
- return pathname || '/';
268
- };
269
- const localiseTargetPathname = (pathname, language, languages, localisedUrls)=>{
270
- const pathWithoutLanguage = stripLanguagePrefix(pathname, languages);
271
- const localisedUrlsConfig = resolveLocalisedUrlsConfig(localisedUrls);
272
- const resolvedPath = localisedUrlsConfig.enabled ? resolveLocalisedPath(pathWithoutLanguage, language, languages, localisedUrlsConfig.map) : pathWithoutLanguage;
273
- const resolvedSegments = resolvedPath.split('/').filter(Boolean);
274
- return `/${[
275
- language,
276
- ...resolvedSegments
277
- ].join('/')}`;
278
- };
279
- const canonicalTargetPathname = (pathname, languages, localisedUrls)=>{
280
- const pathWithoutLanguage = stripLanguagePrefix(pathname, languages);
281
- const localisedUrlsConfig = resolveLocalisedUrlsConfig(localisedUrls);
282
- return localisedUrlsConfig.enabled ? resolveCanonicalLocalisedPath(pathWithoutLanguage, languages, localisedUrlsConfig.map) : pathWithoutLanguage;
283
- };
284
- export { applyLocalisedUrlsToRoutes, buildPathFromPattern, canonicalTargetPathname, localiseTargetPathname, matchPathPattern, normalisePathPattern, normalisePathname, resolveCanonicalLocalisedPath, resolveLocalisedPath, resolveLocalisedUrlsConfig, validateLocalisedUrls };
2
+ export { applyLocalisedUrlsToRoutes, buildPathFromPattern, canonicalTargetPathname, localiseTargetPathname, matchPathPattern, normalisePathPattern, normalisePathname, resolveCanonicalLocalisedPath, resolveLocalisedPath, resolveLocalisedUrlsConfig, validateLocalisedUrls } from "./localisedUrls/index.mjs";
@@ -1,12 +1,8 @@
1
1
  import type React from 'react';
2
2
  import type { LinkParamsProp, LinkTargetPathname, ValidateLinkTo } from './canonicalRoutes';
3
- export type LinkParams = Record<string, string | number | undefined>;
4
- /**
5
- * Interpolate `$param`, `:param`, optional (`{-$param}` / `:param?`) and splat
6
- * (`$` / `*`) segments with concrete values before localization, so
7
- * pattern-mapped slugs localize correctly.
8
- */
9
- export declare const interpolateRouteParams: (pathname: string, params?: LinkParams) => string;
3
+ import { interpolateRouteParams, type LinkParams } from './linkHelpers';
4
+ export type { LinkParams };
5
+ export { interpolateRouteParams };
10
6
  export interface LinkActiveOptions {
11
7
  /**
12
8
  * `true`: active only when the location matches the target exactly.
@@ -32,9 +32,9 @@ export interface UseModernI18nReturn {
32
32
  * This hook provides:
33
33
  * - Current language from URL params or i18n context
34
34
  * - changeLanguage function that updates both i18n instance and URL
35
- * - Direct access to the i18n instance
35
+ * - Direct access to i18n instance
36
36
  * - List of supported languages
37
- * - Helper function to check if a language is supported
37
+ * - Helper function to check if language is supported
38
38
  *
39
39
  * @param options - Optional configuration to override context settings
40
40
  * @returns Object containing i18n functionality and utilities
@@ -0,0 +1,28 @@
1
+ import type { LocalisedUrlsOption } from '../shared/localisedUrls';
2
+ import type { I18nInstance } from './i18n';
3
+ type Navigate = (url: string, options?: {
4
+ replace?: boolean;
5
+ }) => Promise<void> | void;
6
+ type LocationLike = {
7
+ pathname: string;
8
+ search: string;
9
+ hash: string;
10
+ };
11
+ export declare function getPathLanguage(pathname: string | undefined, languages: string[] | undefined, localePathRedirect: boolean | undefined): string | undefined;
12
+ export declare function cacheI18nLanguage(i18nInstance: I18nInstance, language: string): void;
13
+ export interface ChangeModernI18nLanguageOptions {
14
+ i18nInstance: I18nInstance;
15
+ updateLanguage?: (newLang: string) => void;
16
+ localePathRedirect?: boolean;
17
+ ignoreRedirectRoutes?: string[] | ((pathname: string) => boolean);
18
+ localisedUrls?: LocalisedUrlsOption;
19
+ languages?: string[];
20
+ hasRouter: boolean;
21
+ navigate?: Navigate | null;
22
+ location?: LocationLike | null;
23
+ }
24
+ export declare function changeModernI18nLanguage(newLang: string, options: ChangeModernI18nLanguageOptions): Promise<void>;
25
+ export declare function translateI18n(i18nInstance: I18nInstance, key: string | string[], ...args: any[]): string;
26
+ export declare function isI18nLanguageSupported(languages: string[] | undefined, lang: string): boolean;
27
+ export declare function isI18nResourcesReady(i18nInstance: I18nInstance, currentLanguage: string): boolean;
28
+ export {};
@@ -1,10 +1,11 @@
1
- import { type RuntimePlugin } from '@modern-js/runtime';
2
- import type React from 'react';
1
+ import type { RuntimePlugin } from '@modern-js/runtime';
3
2
  import type { BaseBackendOptions, BaseLocaleDetectionOptions } from '../shared/type';
4
3
  import type { I18nInitOptions, I18nInstance } from './i18n';
4
+ import { type LoadReactI18nextIntegration } from './reactI18next';
5
5
  import './types';
6
6
  export type { I18nSdkLoader, I18nSdkLoadOptions } from '../shared/type';
7
7
  export type { Resources } from './i18n/instance';
8
+ export type { LoadReactI18nextIntegration, ReactI18nextIntegration, } from './reactI18next';
8
9
  export interface I18nPluginOptions {
9
10
  entryName?: string;
10
11
  localeDetection?: BaseLocaleDetectionOptions;
@@ -16,11 +17,6 @@ export interface I18nPluginOptions {
16
17
  reactI18next?: boolean;
17
18
  [key: string]: any;
18
19
  }
19
- export interface ReactI18nextIntegration {
20
- I18nextProvider: React.ComponentType<any> | null;
21
- initReactI18next: any | null;
22
- }
23
- export type LoadReactI18nextIntegration = () => Promise<ReactI18nextIntegration | null>;
24
20
  export declare const createI18nPlugin: (loadReactI18nextIntegration?: LoadReactI18nextIntegration) => ((options: I18nPluginOptions) => RuntimePlugin);
25
21
  export type { AllowedLinkTarget, CanonicalRoutePath, UltramodernCanonicalRoutes, } from './canonicalRoutes';
26
22
  export { useModernI18n } from './context';
@@ -0,0 +1,14 @@
1
+ import type { I18nInitOptions, I18nInstance, LanguageDetectorOptions } from '../instance';
2
+ interface DetectorCacheEntry {
3
+ instance: I18nInstance;
4
+ isTemporary: boolean;
5
+ configKey: string;
6
+ }
7
+ export declare const detectorInstanceCache: WeakMap<I18nInstance, DetectorCacheEntry>;
8
+ export declare const buildDetectorConfigKey: (languages: string[], fallbackLanguage: string, mergedDetection: LanguageDetectorOptions) => string;
9
+ export declare const pickSafeDetectionOptions: (userInitOptions?: I18nInitOptions) => Partial<I18nInitOptions> & Record<string, any>;
10
+ export declare const createDetectorInstance: (baseInstance: I18nInstance, configKey: string) => {
11
+ instance: I18nInstance;
12
+ isTemporary: boolean;
13
+ };
14
+ export {};
@@ -0,0 +1,8 @@
1
+ import type { I18nInstance } from '../instance';
2
+ import type { BaseLanguageDetectionOptions } from './types';
3
+ /**
4
+ * Priority 3: Detect language using i18next detector
5
+ */
6
+ export declare const detectLanguageFromI18nextDetector: (i18nInstance: I18nInstance, options: BaseLanguageDetectionOptions & {
7
+ ssrContext?: any;
8
+ }) => Promise<string | undefined>;
@@ -1,50 +1,5 @@
1
- import { type TRuntimeContext } from '@modern-js/runtime';
2
- import type { I18nInitOptions, I18nInstance, LanguageDetectorOptions } from '../instance';
3
- import { cacheUserLanguage } from './middleware';
4
- export { cacheUserLanguage };
5
- export declare function exportServerLngToWindow(context: TRuntimeContext, lng: string): void;
6
- export declare const getLanguageFromSSRData: (window: Window) => string | undefined;
7
- export interface BaseLanguageDetectionOptions {
8
- languages: string[];
9
- fallbackLanguage: string;
10
- localePathRedirect: boolean;
11
- i18nextDetector: boolean;
12
- detection?: LanguageDetectorOptions;
13
- userInitOptions?: I18nInitOptions;
14
- mergedBackend?: any;
15
- }
16
- export interface LanguageDetectionOptions extends BaseLanguageDetectionOptions {
17
- pathname: string;
18
- ssrContext?: any;
19
- }
20
- export interface LanguageDetectionResult {
21
- detectedLanguage?: string;
22
- finalLanguage: string;
23
- }
24
- /**
25
- * Detect language with priority:
26
- * Priority 1: SSR data (try window._SSR_DATA first, works for both SSR and CSR)
27
- * Priority 2: Path detection
28
- * Priority 3: i18next detector (reads from cookie/localStorage)
29
- * Priority 4: User config language or fallback
30
- */
31
- export declare const detectLanguageWithPriority: (i18nInstance: I18nInstance, options: LanguageDetectionOptions) => Promise<LanguageDetectionResult>;
32
- /**
33
- * Options for building i18n init options
34
- */
35
- export interface BuildInitOptionsParams {
36
- finalLanguage: string;
37
- fallbackLanguage: string;
38
- languages: string[];
39
- userInitOptions?: I18nInitOptions;
40
- mergedDetection?: any;
41
- mergeBackend?: any;
42
- }
43
- /**
44
- * Build i18n initialization options
45
- */
46
- export declare const buildInitOptions: (params: BuildInitOptionsParams) => I18nInitOptions;
47
- /**
48
- * Merge detection and backend options
49
- */
50
- export declare const mergeDetectionOptions: (i18nextDetector: boolean, detection?: LanguageDetectorOptions, localePathRedirect?: boolean, userInitOptions?: I18nInitOptions) => LanguageDetectorOptions;
1
+ export { buildInitOptions, mergeDetectionOptions } from './initOptions';
2
+ export { cacheUserLanguage } from './middleware';
3
+ export { detectLanguageWithPriority } from './priority';
4
+ export { exportServerLngToWindow, getLanguageFromSSRData } from './ssr';
5
+ export type { BaseLanguageDetectionOptions, BuildInitOptionsParams, LanguageDetectionOptions, LanguageDetectionResult, } from './types';
@@ -0,0 +1,10 @@
1
+ import type { I18nInitOptions, LanguageDetectorOptions } from '../instance';
2
+ import type { BuildInitOptionsParams } from './types';
3
+ /**
4
+ * Build i18n initialization options
5
+ */
6
+ export declare const buildInitOptions: (params: BuildInitOptionsParams) => I18nInitOptions;
7
+ /**
8
+ * Merge detection and backend options
9
+ */
10
+ export declare const mergeDetectionOptions: (i18nextDetector: boolean, detection?: LanguageDetectorOptions, localePathRedirect?: boolean, userInitOptions?: I18nInitOptions) => LanguageDetectorOptions;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Check if a language is supported
3
+ * Also checks the base language code (e.g., 'zh-CN' matches 'zh')
4
+ */
5
+ export declare const isLanguageSupported: (language: string | undefined, supportedLanguages: string[]) => boolean;
6
+ /**
7
+ * Get the supported language that matches the given language
8
+ * Returns the exact match if available, otherwise returns the base language code match
9
+ * Returns undefined if no match is found
10
+ */
11
+ export declare const getSupportedLanguage: (language: string | undefined, supportedLanguages: string[]) => string | undefined;
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Priority 2: Detect language from URL path
3
+ * Only returns a language if the path explicitly contains a language prefix
4
+ */
5
+ export declare const detectLanguageFromPathPriority: (pathname: string, languages: string[], localePathRedirect: boolean) => string | undefined;
@@ -0,0 +1,10 @@
1
+ import { type I18nInstance } from '../instance';
2
+ import type { LanguageDetectionOptions, LanguageDetectionResult } from './types';
3
+ /**
4
+ * Detect language with priority:
5
+ * Priority 1: Path detection
6
+ * Priority 2: SSR data (try window._SSR_DATA first, works for both SSR and CSR)
7
+ * Priority 3: i18next detector (reads from cookie/localStorage)
8
+ * Priority 4: User config language or fallback
9
+ */
10
+ export declare const detectLanguageWithPriority: (i18nInstance: I18nInstance, options: LanguageDetectionOptions) => Promise<LanguageDetectionResult>;
@@ -0,0 +1,9 @@
1
+ import { type TRuntimeContext } from '@modern-js/runtime';
2
+ export declare function exportServerLngToWindow(context: TRuntimeContext, lng: string): void;
3
+ export declare const getLanguageFromSSRData: (window: Window) => string | undefined;
4
+ /**
5
+ * Priority 1: Detect language from SSR data
6
+ * Try to get language from window._SSR_DATA first (both SSR and CSR projects)
7
+ * Returns undefined if SSR data is not available or invalid
8
+ */
9
+ export declare const detectLanguageFromSSR: (languages: string[]) => string | undefined;
@@ -0,0 +1,29 @@
1
+ import type { I18nInitOptions, LanguageDetectorOptions } from '../instance';
2
+ export interface BaseLanguageDetectionOptions {
3
+ languages: string[];
4
+ fallbackLanguage: string;
5
+ localePathRedirect: boolean;
6
+ i18nextDetector: boolean;
7
+ detection?: LanguageDetectorOptions;
8
+ userInitOptions?: I18nInitOptions;
9
+ mergedBackend?: any;
10
+ }
11
+ export interface LanguageDetectionOptions extends BaseLanguageDetectionOptions {
12
+ pathname: string;
13
+ ssrContext?: any;
14
+ }
15
+ export interface LanguageDetectionResult {
16
+ detectedLanguage?: string;
17
+ finalLanguage: string;
18
+ }
19
+ /**
20
+ * Options for building i18n init options
21
+ */
22
+ export interface BuildInitOptionsParams {
23
+ finalLanguage: string;
24
+ fallbackLanguage: string;
25
+ languages: string[];
26
+ userInitOptions?: I18nInitOptions;
27
+ mergedDetection?: any;
28
+ mergeBackend?: any;
29
+ }
@@ -1,7 +1,2 @@
1
- import type React from 'react';
2
- interface ReactI18nextIntegration {
3
- I18nextProvider: React.ComponentType<any> | null;
4
- initReactI18next: any | null;
5
- }
1
+ import type { ReactI18nextIntegration } from '../reactI18next';
6
2
  export declare function getReactI18nextIntegration(): Promise<ReactI18nextIntegration>;
7
- export {};
@@ -0,0 +1,17 @@
1
+ export declare const warnOnce: (key: string, message: string) => void;
2
+ export type LinkParams = Record<string, string | number | undefined>;
3
+ type NormalizedSearchValue = string | string[];
4
+ /**
5
+ * Interpolate `$param`, `:param`, optional (`{-$param}` / `:param?`) and splat
6
+ * (`$` / `*`) segments with concrete values before localization, so
7
+ * pattern-mapped slugs localize correctly.
8
+ */
9
+ export declare const interpolateRouteParams: (pathname: string, params?: LinkParams) => string;
10
+ export declare const normalizeSearch: (search: string | Record<string, unknown> | undefined, searchFromTo: string) => {
11
+ searchString: string;
12
+ searchObject: Record<string, NormalizedSearchValue> | undefined;
13
+ };
14
+ type ActivePropsResult<TActiveProps extends Record<string, unknown>> = Record<string, unknown> & Partial<TActiveProps>;
15
+ export declare const splitActiveProps: <TActiveProps extends Record<string, unknown>>(active: boolean, activeProps?: TActiveProps) => ActivePropsResult<TActiveProps>;
16
+ export declare const mergeClassNames: (...values: Array<unknown>) => string | undefined;
17
+ export {};
@@ -0,0 +1,32 @@
1
+ import type { TInternalRuntimeContext } from '@modern-js/runtime/internal';
2
+ import type { BaseBackendOptions, BaseLocaleDetectionOptions } from '../shared/type';
3
+ import type { I18nInitOptions, I18nInstance } from './i18n';
4
+ import type { ReactI18nextIntegration } from './reactI18next';
5
+ interface RuntimeConfigWithI18n {
6
+ i18n?: {
7
+ initOptions?: I18nInitOptions;
8
+ };
9
+ }
10
+ interface I18nRuntimeApi {
11
+ getRuntimeConfig: () => RuntimeConfigWithI18n;
12
+ }
13
+ export interface RuntimeContextWithI18n extends TInternalRuntimeContext {
14
+ i18nInstance?: I18nInstance;
15
+ changeLanguage?: (lang: string) => Promise<void>;
16
+ }
17
+ export interface SetupI18nBeforeRenderOptions {
18
+ api: I18nRuntimeApi;
19
+ userI18nInstance?: I18nInstance;
20
+ initOptions?: I18nInitOptions;
21
+ backend?: BaseBackendOptions;
22
+ backendEnabled: boolean;
23
+ i18nextDetector: boolean;
24
+ detection?: BaseLocaleDetectionOptions['detection'];
25
+ localePathRedirect: boolean;
26
+ languages: string[];
27
+ fallbackLanguage: string;
28
+ resolveReactI18nextIntegration: () => Promise<ReactI18nextIntegration | null>;
29
+ setI18nextProvider: (provider: ReactI18nextIntegration['I18nextProvider']) => void;
30
+ }
31
+ export declare function setupI18nBeforeRender(context: RuntimeContextWithI18n, options: SetupI18nBeforeRenderOptions): Promise<I18nInstance>;
32
+ export {};
@@ -0,0 +1,15 @@
1
+ import type React from 'react';
2
+ import type { BaseLocaleDetectionOptions } from '../shared/type';
3
+ import type { I18nInstance } from './i18n';
4
+ export interface I18nRootWrapperOptions {
5
+ entryName?: string;
6
+ htmlLangAttr: boolean;
7
+ localePathRedirect: boolean;
8
+ languages: string[];
9
+ fallbackLanguage: string;
10
+ ignoreRedirectRoutes?: BaseLocaleDetectionOptions['ignoreRedirectRoutes'];
11
+ localisedUrls?: BaseLocaleDetectionOptions['localisedUrls'];
12
+ getLatestI18nInstance: () => I18nInstance | undefined;
13
+ getI18nextProvider: () => React.ComponentType<any> | null | undefined;
14
+ }
15
+ export declare const createI18nRootWrapper: (options: I18nRootWrapperOptions) => (App: React.ComponentType<any>) => (props: Record<string, unknown>) => React.JSX.Element;
@@ -0,0 +1,7 @@
1
+ import type React from 'react';
2
+ export interface ReactI18nextIntegration {
3
+ I18nextProvider: React.ComponentType<any> | null;
4
+ initReactI18next: any | null;
5
+ }
6
+ export type LoadReactI18nextIntegration = () => Promise<ReactI18nextIntegration | null>;
7
+ export declare const resolveReactI18nextIntegration: (reactI18next: boolean, loadReactI18nextIntegration?: LoadReactI18nextIntegration) => Promise<ReactI18nextIntegration | null>;
@@ -0,0 +1,7 @@
1
+ type ApiPrefixInput = string | string[] | undefined;
2
+ export declare const collectApiPrefixes: (routes: Array<{
3
+ isApi?: boolean;
4
+ urlPath?: string;
5
+ }>, bffPrefix?: ApiPrefixInput) => string[];
6
+ export declare const matchesApiPrefix: (pathname: string, apiPrefixes: string[]) => boolean;
7
+ export {};
@@ -0,0 +1,21 @@
1
+ import type { LanguageDetectorOptions } from '../runtime/i18n/instance';
2
+ /**
3
+ * Convert i18next detection options to hono languageDetector options
4
+ */
5
+ export declare const convertToHonoLanguageDetectorOptions: (languages: string[], fallbackLanguage: string, detectionOptions?: LanguageDetectorOptions) => {
6
+ supportedLanguages: string[];
7
+ fallbackLanguage: string;
8
+ order: ("cookie" | "header" | "path" | "querystring")[];
9
+ lookupQueryString: string;
10
+ lookupCookie: string;
11
+ lookupFromHeaderKey: string;
12
+ caches?: false | ["cookie"] | undefined;
13
+ cookieOptions?: {
14
+ maxAge: number;
15
+ sameSite: "Lax" | "None" | "Strict";
16
+ secure: boolean;
17
+ httpOnly: boolean;
18
+ domain?: string | undefined;
19
+ } | undefined;
20
+ ignoreCase: boolean;
21
+ };