@bleedingdev/modern-js-i18n-runtime-extensions 3.8.3-ultramodern.2

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 (70) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cjs/index.js +76 -0
  3. package/dist/cjs/language-sync/controller.js +241 -0
  4. package/dist/cjs/language-sync/react.js +169 -0
  5. package/dist/cjs/localisedUrls/config.js +49 -0
  6. package/dist/cjs/localisedUrls/index.js +91 -0
  7. package/dist/cjs/localisedUrls/normalise.js +87 -0
  8. package/dist/cjs/localisedUrls/pathname.js +68 -0
  9. package/dist/cjs/localisedUrls/patterns.js +214 -0
  10. package/dist/cjs/localisedUrls/redirect.js +103 -0
  11. package/dist/cjs/localisedUrls/resolve.js +78 -0
  12. package/dist/cjs/localisedUrls/routes.js +202 -0
  13. package/dist/cjs/localisedUrls/types.js +18 -0
  14. package/dist/esm/index.mjs +3 -0
  15. package/dist/esm/language-sync/controller.mjs +203 -0
  16. package/dist/esm/language-sync/react.mjs +118 -0
  17. package/dist/esm/localisedUrls/config.mjs +11 -0
  18. package/dist/esm/localisedUrls/index.mjs +7 -0
  19. package/dist/esm/localisedUrls/normalise.mjs +37 -0
  20. package/dist/esm/localisedUrls/pathname.mjs +24 -0
  21. package/dist/esm/localisedUrls/patterns.mjs +152 -0
  22. package/dist/esm/localisedUrls/redirect.mjs +56 -0
  23. package/dist/esm/localisedUrls/resolve.mjs +37 -0
  24. package/dist/esm/localisedUrls/routes.mjs +161 -0
  25. package/dist/esm/localisedUrls/types.mjs +0 -0
  26. package/dist/esm-node/index.mjs +4 -0
  27. package/dist/esm-node/language-sync/controller.mjs +204 -0
  28. package/dist/esm-node/language-sync/react.mjs +119 -0
  29. package/dist/esm-node/localisedUrls/config.mjs +12 -0
  30. package/dist/esm-node/localisedUrls/index.mjs +8 -0
  31. package/dist/esm-node/localisedUrls/normalise.mjs +38 -0
  32. package/dist/esm-node/localisedUrls/pathname.mjs +25 -0
  33. package/dist/esm-node/localisedUrls/patterns.mjs +153 -0
  34. package/dist/esm-node/localisedUrls/redirect.mjs +57 -0
  35. package/dist/esm-node/localisedUrls/resolve.mjs +38 -0
  36. package/dist/esm-node/localisedUrls/routes.mjs +162 -0
  37. package/dist/esm-node/localisedUrls/types.mjs +1 -0
  38. package/dist/types/index.d.ts +3 -0
  39. package/dist/types/language-sync/controller.d.ts +26 -0
  40. package/dist/types/language-sync/react.d.ts +38 -0
  41. package/dist/types/localisedUrls/config.d.ts +9 -0
  42. package/dist/types/localisedUrls/index.d.ts +9 -0
  43. package/dist/types/localisedUrls/normalise.d.ts +10 -0
  44. package/dist/types/localisedUrls/pathname.d.ts +4 -0
  45. package/dist/types/localisedUrls/patterns.d.ts +11 -0
  46. package/dist/types/localisedUrls/redirect.d.ts +11 -0
  47. package/dist/types/localisedUrls/resolve.d.ts +7 -0
  48. package/dist/types/localisedUrls/routes.d.ts +3 -0
  49. package/dist/types/localisedUrls/types.d.ts +14 -0
  50. package/package.json +71 -0
  51. package/rslib.config.mts +4 -0
  52. package/rstest.config.mts +36 -0
  53. package/src/index.ts +3 -0
  54. package/src/language-sync/controller.ts +386 -0
  55. package/src/language-sync/react.ts +227 -0
  56. package/src/localisedUrls/config.ts +18 -0
  57. package/src/localisedUrls/index.ts +24 -0
  58. package/src/localisedUrls/normalise.ts +62 -0
  59. package/src/localisedUrls/pathname.ts +60 -0
  60. package/src/localisedUrls/patterns.ts +283 -0
  61. package/src/localisedUrls/redirect.ts +93 -0
  62. package/src/localisedUrls/resolve.ts +106 -0
  63. package/src/localisedUrls/routes.ts +422 -0
  64. package/src/localisedUrls/types.ts +18 -0
  65. package/tests/clientRedirectIntegration.test.tsx +74 -0
  66. package/tests/languageSyncController.test.ts +213 -0
  67. package/tests/localisedUrls.test.ts +673 -0
  68. package/tests/reactLanguageSync.test.tsx +117 -0
  69. package/tests/tsconfig.json +11 -0
  70. package/tsconfig.json +11 -0
@@ -0,0 +1,93 @@
1
+ import { normalisePathname } from './normalise';
2
+ import { stripLanguagePrefix } from './pathname';
3
+
4
+ export type LocaleRedirectSkipRule =
5
+ | {
6
+ type: 'exact';
7
+ path: string;
8
+ }
9
+ | {
10
+ type: 'prefix';
11
+ path: string;
12
+ };
13
+
14
+ export const DEFAULT_LOCALE_REDIRECT_SKIP_RULES: readonly LocaleRedirectSkipRule[] =
15
+ [
16
+ { type: 'exact', path: '/backend-mf-manifest.json' },
17
+ { type: 'exact', path: '/backendRemoteEntry.cjs' },
18
+ { type: 'exact', path: '/mf-manifest.json' },
19
+ { type: 'exact', path: '/mf-stats.json' },
20
+ { type: 'exact', path: '/remoteEntry.js' },
21
+ { type: 'prefix', path: '/static/' },
22
+ { type: 'prefix', path: '/upload/' },
23
+ ];
24
+
25
+ const stripTrailingSlash = (pathname: string): string =>
26
+ pathname.length > 1 ? pathname.replace(/\/+$/, '') : pathname;
27
+
28
+ export const matchesPathPrefix = (
29
+ pathname: string,
30
+ prefix: string,
31
+ ): boolean => {
32
+ const normalizedPathname = normalisePathname(pathname);
33
+ const normalizedPrefix = stripTrailingSlash(normalisePathname(prefix));
34
+
35
+ return (
36
+ normalizedPathname === normalizedPrefix ||
37
+ normalizedPathname.startsWith(`${normalizedPrefix}/`)
38
+ );
39
+ };
40
+
41
+ const matchesSkipRule = (
42
+ pathname: string,
43
+ rule: LocaleRedirectSkipRule,
44
+ ): boolean => {
45
+ if (rule.type === 'exact') {
46
+ return normalisePathname(pathname) === normalisePathname(rule.path);
47
+ }
48
+
49
+ return matchesPathPrefix(pathname, rule.path);
50
+ };
51
+
52
+ export const isDefaultLocaleRedirectSkipPath = (
53
+ pathname: string,
54
+ languages: string[] = [],
55
+ ): boolean => {
56
+ const normalizedPathname = normalisePathname(pathname);
57
+ const pathWithoutLanguage = stripLanguagePrefix(
58
+ normalizedPathname,
59
+ languages,
60
+ );
61
+
62
+ return DEFAULT_LOCALE_REDIRECT_SKIP_RULES.some(rule =>
63
+ matchesSkipRule(pathWithoutLanguage, rule),
64
+ );
65
+ };
66
+
67
+ export const shouldSkipLocaleRedirect = (
68
+ pathname: string,
69
+ languages: string[] = [],
70
+ ignoreRedirectRoutes?: string[] | ((pathname: string) => boolean),
71
+ ): boolean => {
72
+ const normalizedPathname = normalisePathname(pathname);
73
+ const pathWithoutLanguage = stripLanguagePrefix(
74
+ normalizedPathname,
75
+ languages,
76
+ );
77
+
78
+ if (isDefaultLocaleRedirectSkipPath(pathWithoutLanguage)) {
79
+ return true;
80
+ }
81
+
82
+ if (!ignoreRedirectRoutes) {
83
+ return false;
84
+ }
85
+
86
+ if (typeof ignoreRedirectRoutes === 'function') {
87
+ return ignoreRedirectRoutes(pathWithoutLanguage);
88
+ }
89
+
90
+ return ignoreRedirectRoutes.some(pattern =>
91
+ matchesPathPrefix(pathWithoutLanguage, pattern),
92
+ );
93
+ };
@@ -0,0 +1,106 @@
1
+ import { normalisePathname } from './normalise';
2
+
3
+ import {
4
+ buildPathFromPattern,
5
+ matchPathPattern,
6
+ sortPatternsBySpecificity,
7
+ } from './patterns';
8
+
9
+ import type { LocalisedUrlsMap } from './types';
10
+
11
+ type CanonicalCandidate = {
12
+ pattern: string;
13
+ canonicalPattern: string;
14
+ localisedUrlEntry: LocalisedUrlsMap[string];
15
+ };
16
+
17
+ type ResolveLocalisedUrlPathOptions =
18
+ | {
19
+ mode: 'localised';
20
+ targetLanguage: string;
21
+ }
22
+ | {
23
+ mode: 'canonical';
24
+ };
25
+
26
+ const getCanonicalCandidates = (
27
+ localisedUrls: LocalisedUrlsMap,
28
+ ): CanonicalCandidate[] =>
29
+ sortPatternsBySpecificity(
30
+ Object.entries(localisedUrls).map(
31
+ ([canonicalPattern, localisedUrlEntry]) => ({
32
+ pattern: canonicalPattern,
33
+ canonicalPattern,
34
+ localisedUrlEntry,
35
+ }),
36
+ ),
37
+ );
38
+
39
+ const resolveLocalisedUrlPath = (
40
+ pathname: string,
41
+ languages: string[],
42
+ localisedUrls: LocalisedUrlsMap,
43
+ options: ResolveLocalisedUrlPathOptions,
44
+ ): string => {
45
+ const normalizedPathname = normalisePathname(pathname);
46
+ const canonicalCandidates = getCanonicalCandidates(localisedUrls);
47
+
48
+ const candidates = sortPatternsBySpecificity(
49
+ canonicalCandidates.flatMap(({ canonicalPattern, localisedUrlEntry }) => {
50
+ const targetPattern =
51
+ options.mode === 'localised'
52
+ ? localisedUrlEntry[options.targetLanguage]
53
+ : canonicalPattern;
54
+ if (!targetPattern) {
55
+ return [];
56
+ }
57
+
58
+ const sourcePatterns = new Set([
59
+ canonicalPattern,
60
+ ...languages
61
+ .map(language => localisedUrlEntry[language])
62
+ .filter((sourcePattern): sourcePattern is string =>
63
+ Boolean(sourcePattern),
64
+ ),
65
+ ]);
66
+ return Array.from(sourcePatterns, sourcePattern => ({
67
+ pattern: sourcePattern,
68
+ sourcePattern,
69
+ targetPattern,
70
+ }));
71
+ }),
72
+ );
73
+
74
+ for (const { sourcePattern, targetPattern } of candidates) {
75
+ const params = matchPathPattern(normalizedPathname, sourcePattern);
76
+ if (params) {
77
+ return buildPathFromPattern(targetPattern, params);
78
+ }
79
+ }
80
+
81
+ return normalizedPathname;
82
+ };
83
+
84
+ export const resolveLocalisedPath = (
85
+ pathname: string,
86
+ targetLanguage: string,
87
+ languages: string[],
88
+ localisedUrls: LocalisedUrlsMap,
89
+ ): string =>
90
+ resolveLocalisedUrlPath(pathname, languages, localisedUrls, {
91
+ mode: 'localised',
92
+ targetLanguage,
93
+ });
94
+
95
+ /**
96
+ * Reverse-map language-specific pathnames back to language-agnostic
97
+ * LocalisedUrlsMap keys.
98
+ */
99
+ export const resolveCanonicalLocalisedPath = (
100
+ pathname: string,
101
+ languages: string[],
102
+ localisedUrls: LocalisedUrlsMap,
103
+ ): string =>
104
+ resolveLocalisedUrlPath(pathname, languages, localisedUrls, {
105
+ mode: 'canonical',
106
+ });
@@ -0,0 +1,422 @@
1
+ import {
2
+ getLeadingLocaleParam,
3
+ normalisePathPattern,
4
+ normaliseRoutePath,
5
+ stripLeadingLocaleParam,
6
+ } from './normalise';
7
+ import {
8
+ doPathPatternsOverlap,
9
+ getOrderedPathParamSignature,
10
+ getPathParamSignature,
11
+ getPathPatternValidationIssue,
12
+ getPhysicalPathPattern,
13
+ haveEqualPatternSpecificity,
14
+ } from './patterns';
15
+ import type {
16
+ LocalisedRoute,
17
+ LocalisedUrlPathMap,
18
+ LocalisedUrlsMap,
19
+ } from './types';
20
+
21
+ const isLocalisableRoutePath = (path?: string): path is string => {
22
+ const pathWithoutLocale = stripLeadingLocaleParam(path);
23
+
24
+ if (
25
+ !pathWithoutLocale ||
26
+ pathWithoutLocale === '/' ||
27
+ pathWithoutLocale === '*'
28
+ ) {
29
+ return false;
30
+ }
31
+
32
+ return true;
33
+ };
34
+
35
+ const joinPath = (parentPath: string, routePath?: string): string => {
36
+ if (!isLocalisableRoutePath(routePath)) {
37
+ return parentPath;
38
+ }
39
+
40
+ const segment = normaliseRoutePath(stripLeadingLocaleParam(routePath) || '');
41
+ return normalisePathPattern(`${parentPath}/${segment}`);
42
+ };
43
+
44
+ const isFrameworkInternalRoutePath = (canonicalPath: string) =>
45
+ canonicalPath === '/_mf' || canonicalPath.startsWith('/_mf/');
46
+
47
+ const legalRouteIdPart = (value: string): string =>
48
+ value.replace(/[^a-zA-Z0-9_$-]+/g, '_').replace(/^_+|_+$/g, '') || 'index';
49
+
50
+ const formatParamSignature = (signature: string[]): string =>
51
+ signature.length > 0 ? signature.join(', ') : '(none)';
52
+
53
+ const validateLocalisedUrlPatterns = (
54
+ languages: string[],
55
+ localisedUrls: LocalisedUrlsMap,
56
+ ) => {
57
+ const physicalPatterns = new Map<
58
+ string,
59
+ { canonicalPath: string; source: string }
60
+ >();
61
+ const claimedPatterns: Array<{
62
+ canonicalPath: string;
63
+ pattern: string;
64
+ source: string;
65
+ }> = [];
66
+
67
+ const claimPhysicalPattern = (
68
+ sourcePattern: string,
69
+ canonicalPath: string,
70
+ source: string,
71
+ ) => {
72
+ const physicalPattern = getPhysicalPathPattern(sourcePattern);
73
+ const existing = physicalPatterns.get(physicalPattern);
74
+ if (existing && existing.canonicalPath !== canonicalPath) {
75
+ throw new Error(
76
+ `localisedUrls["${existing.canonicalPath}"] ${existing.source} and localisedUrls["${canonicalPath}"] ${source} generate the same physical route pattern "${physicalPattern}". Localised route patterns must identify exactly one canonical route.`,
77
+ );
78
+ }
79
+
80
+ const overlapping = claimedPatterns.find(
81
+ claimed =>
82
+ claimed.canonicalPath !== canonicalPath &&
83
+ haveEqualPatternSpecificity(claimed.pattern, sourcePattern) &&
84
+ doPathPatternsOverlap(claimed.pattern, sourcePattern),
85
+ );
86
+ if (overlapping) {
87
+ throw new Error(
88
+ `localisedUrls["${overlapping.canonicalPath}"] ${overlapping.source} pattern "${overlapping.pattern}" and localisedUrls["${canonicalPath}"] ${source} pattern "${sourcePattern}" are equal-specificity overlapping route patterns. Localised route patterns must identify exactly one canonical route.`,
89
+ );
90
+ }
91
+
92
+ physicalPatterns.set(physicalPattern, { canonicalPath, source });
93
+ claimedPatterns.push({ canonicalPath, pattern: sourcePattern, source });
94
+ };
95
+
96
+ for (const [canonicalPath, entry] of Object.entries(localisedUrls).sort(
97
+ ([left], [right]) => (left < right ? -1 : left > right ? 1 : 0),
98
+ )) {
99
+ const canonicalIssue = getPathPatternValidationIssue(canonicalPath);
100
+ if (canonicalIssue) {
101
+ throw new Error(
102
+ `localisedUrls["${canonicalPath}"] canonical pattern has ${canonicalIssue}.`,
103
+ );
104
+ }
105
+ const expectedSignature = getPathParamSignature(canonicalPath);
106
+ const expectedOrderedSignature =
107
+ getOrderedPathParamSignature(canonicalPath);
108
+ claimPhysicalPattern(canonicalPath, canonicalPath, 'canonical pattern');
109
+
110
+ for (const language of languages) {
111
+ const localisedPattern = entry[language];
112
+ if (!localisedPattern) {
113
+ continue;
114
+ }
115
+
116
+ const localisedIssue = getPathPatternValidationIssue(localisedPattern);
117
+ if (localisedIssue) {
118
+ throw new Error(
119
+ `localisedUrls["${canonicalPath}"].${language} has ${localisedIssue}.`,
120
+ );
121
+ }
122
+
123
+ const actualSignature = getPathParamSignature(localisedPattern);
124
+ if (
125
+ actualSignature.length !== expectedSignature.length ||
126
+ actualSignature.some(
127
+ (parameter, index) => parameter !== expectedSignature[index],
128
+ )
129
+ ) {
130
+ throw new Error(
131
+ `localisedUrls["${canonicalPath}"].${language} must use the same parameter signature as "${canonicalPath}": expected ${formatParamSignature(
132
+ expectedSignature,
133
+ )}; received ${formatParamSignature(actualSignature)}.`,
134
+ );
135
+ }
136
+
137
+ const actualOrderedSignature =
138
+ getOrderedPathParamSignature(localisedPattern);
139
+ if (
140
+ expectedOrderedSignature.some(
141
+ parameter => parameter === '*' || parameter.endsWith('?'),
142
+ ) &&
143
+ actualOrderedSignature.some(
144
+ (parameter, index) => parameter !== expectedOrderedSignature[index],
145
+ )
146
+ ) {
147
+ throw new Error(
148
+ `localisedUrls["${canonicalPath}"].${language} must keep optional and splat parameters in canonical order: expected ${formatParamSignature(
149
+ expectedOrderedSignature,
150
+ )}; received ${formatParamSignature(actualOrderedSignature)}.`,
151
+ );
152
+ }
153
+
154
+ claimPhysicalPattern(localisedPattern, canonicalPath, `.${language}`);
155
+ }
156
+ }
157
+ };
158
+
159
+ const ensureLocalisedUrlsForPath = (
160
+ canonicalPath: string,
161
+ languages: string[],
162
+ localisedUrls: LocalisedUrlsMap,
163
+ ): LocalisedUrlPathMap => {
164
+ const entry = localisedUrls[canonicalPath];
165
+ if (!entry) {
166
+ throw new Error(
167
+ `localisedUrls is enabled, but route "${canonicalPath}" does not define localised URLs for languages: ${languages.join(
168
+ ', ',
169
+ )}. Add localisedUrls["${canonicalPath}"] or set localeDetection.localisedUrls to false.`,
170
+ );
171
+ }
172
+
173
+ const missingLanguages = languages.filter(language => !entry[language]);
174
+ if (missingLanguages.length > 0) {
175
+ throw new Error(
176
+ `localisedUrls["${canonicalPath}"] is missing languages: ${missingLanguages.join(
177
+ ', ',
178
+ )}. Every configured language must have a localised URL.`,
179
+ );
180
+ }
181
+
182
+ return entry;
183
+ };
184
+
185
+ export const validateLocalisedUrls = (
186
+ routes: LocalisedRoute[],
187
+ languages: string[],
188
+ localisedUrls: LocalisedUrlsMap,
189
+ ) => {
190
+ validateLocalisedUrlPatterns(languages, localisedUrls);
191
+
192
+ const visit = (route: LocalisedRoute, parentPath: string) => {
193
+ const canonicalPath = joinPath(parentPath, route.path);
194
+ if (
195
+ isLocalisableRoutePath(route.path) &&
196
+ !isFrameworkInternalRoutePath(canonicalPath)
197
+ ) {
198
+ ensureLocalisedUrlsForPath(canonicalPath, languages, localisedUrls);
199
+ }
200
+
201
+ if ('children' in route && route.children) {
202
+ route.children.forEach(child => visit(child, canonicalPath));
203
+ }
204
+ };
205
+
206
+ routes.forEach(route => visit(route, ''));
207
+ };
208
+
209
+ const getLocalisedRouteIdSuffixes = (
210
+ paths: string[],
211
+ ): Array<string | undefined> => {
212
+ const usedSuffixes = new Set<string>();
213
+
214
+ return paths.map((path, index) => {
215
+ if (index === 0) {
216
+ return undefined;
217
+ }
218
+
219
+ const baseSuffix = legalRouteIdPart(path);
220
+ let suffix = baseSuffix;
221
+ let disambiguator = 2;
222
+ while (usedSuffixes.has(suffix)) {
223
+ suffix = `${baseSuffix}_${disambiguator++}`;
224
+ }
225
+ usedSuffixes.add(suffix);
226
+ return suffix;
227
+ });
228
+ };
229
+
230
+ const getLocalisedRoutePaths = (
231
+ canonicalPath: string,
232
+ parentLocalisedPaths: Record<string, string>,
233
+ languages: string[],
234
+ entry: LocalisedUrlPathMap,
235
+ ): string[] => {
236
+ const paths = languages.map(language => {
237
+ const fullPath = normalisePathPattern(entry[language]);
238
+ const parentPath = normalisePathPattern(
239
+ parentLocalisedPaths[language] || '/',
240
+ );
241
+ if (parentPath === '/') {
242
+ return normaliseRoutePath(fullPath) || undefined;
243
+ }
244
+
245
+ const parentPrefix = `${parentPath}/`;
246
+ if (!fullPath.startsWith(parentPrefix)) {
247
+ throw new Error(
248
+ `localisedUrls["${canonicalPath}"].${language} must be nested under "${parentPath}" because its parent route is localised there.`,
249
+ );
250
+ }
251
+
252
+ return normaliseRoutePath(fullPath.slice(parentPath.length));
253
+ });
254
+
255
+ const uniquePaths = Array.from(new Set(paths.filter(Boolean) as string[]));
256
+ return uniquePaths;
257
+ };
258
+
259
+ const transformLocalisedRoute = (
260
+ route: LocalisedRoute,
261
+ parentCanonicalPath: string,
262
+ parentLocalisedPaths: Record<string, string>,
263
+ languages: string[],
264
+ localisedUrls: LocalisedUrlsMap,
265
+ ): LocalisedRoute[] => {
266
+ const canonicalPath = joinPath(parentCanonicalPath, route.path);
267
+ const localisedUrlEntry =
268
+ isLocalisableRoutePath(route.path) &&
269
+ !isFrameworkInternalRoutePath(canonicalPath)
270
+ ? ensureLocalisedUrlsForPath(canonicalPath, languages, localisedUrls)
271
+ : undefined;
272
+ const routeLocalisedPaths = localisedUrlEntry
273
+ ? languages.reduce<Record<string, string>>((acc, language) => {
274
+ acc[language] = normalisePathPattern(localisedUrlEntry[language]);
275
+ return acc;
276
+ }, {})
277
+ : parentLocalisedPaths;
278
+
279
+ const children =
280
+ 'children' in route && route.children
281
+ ? route.children.flatMap(child =>
282
+ transformLocalisedRoute(
283
+ child,
284
+ canonicalPath,
285
+ routeLocalisedPaths,
286
+ languages,
287
+ localisedUrls,
288
+ ),
289
+ )
290
+ : undefined;
291
+
292
+ const baseRoute = {
293
+ ...route,
294
+ ...(children ? { children } : {}),
295
+ } as LocalisedRoute;
296
+
297
+ if (!localisedUrlEntry) {
298
+ return [baseRoute];
299
+ }
300
+
301
+ const localisedPaths = getLocalisedRoutePaths(
302
+ canonicalPath,
303
+ parentLocalisedPaths,
304
+ languages,
305
+ localisedUrlEntry,
306
+ );
307
+ const leadingLocaleParam = getLeadingLocaleParam(route.path);
308
+ const routeIdPaths = leadingLocaleParam
309
+ ? localisedPaths.map(path =>
310
+ normaliseRoutePath(`${leadingLocaleParam}/${path}`),
311
+ )
312
+ : localisedPaths;
313
+ const routeIdSuffixes = getLocalisedRouteIdSuffixes(routeIdPaths);
314
+
315
+ return localisedPaths.map((localisedPath, index) =>
316
+ cloneRouteWithLocalisedPath(
317
+ baseRoute,
318
+ localisedPath,
319
+ routeIdSuffixes[index],
320
+ canonicalPath,
321
+ ),
322
+ );
323
+ };
324
+
325
+ const suffixRouteIds = <T extends LocalisedRoute>(
326
+ route: T,
327
+ suffix: string,
328
+ ): T => {
329
+ const children =
330
+ 'children' in route && route.children
331
+ ? route.children.map(child => suffixRouteIds(child, suffix))
332
+ : undefined;
333
+
334
+ return {
335
+ ...route,
336
+ ...(route.id ? { id: `${route.id}__localised_${suffix}` } : {}),
337
+ ...(children ? { children } : {}),
338
+ };
339
+ };
340
+
341
+ const collectRouteIdCounts = (
342
+ routes: LocalisedRoute[],
343
+ counts = new Map<string, number>(),
344
+ ): Map<string, number> => {
345
+ for (const route of routes) {
346
+ if (route.id) {
347
+ counts.set(route.id, (counts.get(route.id) ?? 0) + 1);
348
+ }
349
+ if ('children' in route && route.children) {
350
+ collectRouteIdCounts(route.children, counts);
351
+ }
352
+ }
353
+ return counts;
354
+ };
355
+
356
+ const validateNoNewRouteIdCollisions = (
357
+ sourceRoutes: LocalisedRoute[],
358
+ localisedRoutes: LocalisedRoute[],
359
+ ) => {
360
+ const sourceCounts = collectRouteIdCounts(sourceRoutes);
361
+ const localisedCounts = collectRouteIdCounts(localisedRoutes);
362
+
363
+ for (const [routeId, count] of localisedCounts) {
364
+ if (count > 1 && count > (sourceCounts.get(routeId) ?? 0)) {
365
+ throw new Error(
366
+ `Localised route expansion generated duplicate route ID "${routeId}". Change the source route ID or localised path so every generated route remains identifiable.`,
367
+ );
368
+ }
369
+ }
370
+ };
371
+
372
+ const cloneRouteWithLocalisedPath = (
373
+ route: LocalisedRoute,
374
+ path: string,
375
+ routeIdSuffix: string | undefined,
376
+ canonicalPath: string,
377
+ ): LocalisedRoute => {
378
+ const leadingLocaleParam = getLeadingLocaleParam(route.path);
379
+ const localisedPath = leadingLocaleParam
380
+ ? normaliseRoutePath(`${leadingLocaleParam}/${path}`)
381
+ : path;
382
+ const routeWithPath = {
383
+ ...route,
384
+ path: localisedPath,
385
+ } as LocalisedRoute;
386
+ // Language-agnostic source pattern; lets downstream codegen collapse the
387
+ // localized physical variants back to one canonical route.
388
+ (routeWithPath as { modernCanonicalPath?: string }).modernCanonicalPath =
389
+ canonicalPath;
390
+
391
+ return routeIdSuffix
392
+ ? suffixRouteIds(routeWithPath, routeIdSuffix)
393
+ : routeWithPath;
394
+ };
395
+
396
+ export const applyLocalisedUrlsToRoutes = (
397
+ routes: LocalisedRoute[],
398
+ languages: string[],
399
+ localisedUrls: LocalisedUrlsMap,
400
+ ): LocalisedRoute[] => {
401
+ const rootLocalisedPaths = languages.reduce<Record<string, string>>(
402
+ (acc, language) => {
403
+ acc[language] = '/';
404
+ return acc;
405
+ },
406
+ {},
407
+ );
408
+
409
+ validateLocalisedUrls(routes, languages, localisedUrls);
410
+
411
+ const localisedRoutes = routes.flatMap(route =>
412
+ transformLocalisedRoute(
413
+ route,
414
+ '',
415
+ rootLocalisedPaths,
416
+ languages,
417
+ localisedUrls,
418
+ ),
419
+ );
420
+ validateNoNewRouteIdCollisions(routes, localisedRoutes);
421
+ return localisedRoutes;
422
+ };
@@ -0,0 +1,18 @@
1
+ export type LocalisedRoute = {
2
+ type: 'nested' | 'page';
3
+ path?: string;
4
+ id?: string;
5
+ children?: LocalisedRoute[];
6
+ [key: string]: any;
7
+ };
8
+
9
+ export type LocalisedUrlPathMap = Record<string, string>;
10
+
11
+ export type LocalisedUrlsMap = Record<string, LocalisedUrlPathMap>;
12
+
13
+ export type LocalisedUrlsOption = boolean | LocalisedUrlsMap;
14
+
15
+ export interface ResolvedLocalisedUrlsConfig {
16
+ enabled: boolean;
17
+ map: LocalisedUrlsMap;
18
+ }
@@ -0,0 +1,74 @@
1
+ import React, { act } from 'react';
2
+ import { createRoot } from 'react-dom/client';
3
+ import { useClientSideRedirect } from '../../plugin-i18n/src/runtime/hooks';
4
+
5
+ const navigate = rstest.fn(async () => undefined);
6
+ let location = {
7
+ pathname: '/cs/about',
8
+ search: '?from=test',
9
+ hash: '#section',
10
+ };
11
+
12
+ rstest.mock('../../plugin-i18n/src/runtime/routerAdapter', () => ({
13
+ useI18nRouterAdapter: () => ({
14
+ hasRouter: true,
15
+ location,
16
+ navigate,
17
+ }),
18
+ }));
19
+
20
+ test('canonicalizes successive prefixed routes in one mounted provider', async () => {
21
+ const previousTarget = process.env.MODERN_TARGET;
22
+ process.env.MODERN_TARGET = 'browser';
23
+ const instance = {
24
+ language: 'cs',
25
+ isInitialized: true,
26
+ } as Parameters<typeof useClientSideRedirect>[0];
27
+ const localisedUrls = {
28
+ '/about': { en: '/about', cs: '/o-nas' },
29
+ '/terms-of-service': {
30
+ en: '/terms-of-service',
31
+ cs: '/podminky-pouzivani',
32
+ },
33
+ };
34
+ const Harness = () => {
35
+ useClientSideRedirect(
36
+ instance,
37
+ true,
38
+ ['en', 'cs'],
39
+ 'en',
40
+ undefined,
41
+ localisedUrls,
42
+ );
43
+ return null;
44
+ };
45
+ const container = document.createElement('div');
46
+ const root = createRoot(container);
47
+
48
+ try {
49
+ window.history.replaceState(null, '', '/cs/about?from=test#section');
50
+ await act(async () => root.render(<Harness />));
51
+ expect(navigate).toHaveBeenLastCalledWith('/cs/o-nas?from=test#section', {
52
+ replace: true,
53
+ });
54
+
55
+ location = {
56
+ pathname: '/cs/terms-of-service',
57
+ search: '',
58
+ hash: '',
59
+ };
60
+ window.history.replaceState(null, '', '/cs/terms-of-service');
61
+ await act(async () => root.render(<Harness />));
62
+ expect(navigate).toHaveBeenLastCalledWith('/cs/podminky-pouzivani', {
63
+ replace: true,
64
+ });
65
+ expect(navigate).toHaveBeenCalledTimes(2);
66
+ } finally {
67
+ await act(async () => root.unmount());
68
+ if (previousTarget === undefined) {
69
+ delete process.env.MODERN_TARGET;
70
+ } else {
71
+ process.env.MODERN_TARGET = previousTarget;
72
+ }
73
+ }
74
+ });