@bleedingdev/modern-js-runtime-extensions 3.9.0-ultramodern.10 → 3.9.0-ultramodern.12

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 (66) hide show
  1. package/dist/cjs/localisedUrls/config.js +49 -0
  2. package/dist/cjs/localisedUrls/index.js +95 -0
  3. package/dist/cjs/localisedUrls/normalise.js +87 -0
  4. package/dist/cjs/localisedUrls/pathname.js +68 -0
  5. package/dist/cjs/localisedUrls/patterns.js +214 -0
  6. package/dist/cjs/localisedUrls/redirect.js +100 -0
  7. package/dist/cjs/localisedUrls/resolve.js +78 -0
  8. package/dist/cjs/localisedUrls/routeIdentity.js +92 -0
  9. package/dist/cjs/localisedUrls/routes.js +217 -0
  10. package/dist/cjs/localisedUrls/types.js +18 -0
  11. package/dist/cjs/routerState.js +48 -77
  12. package/dist/cjs/routerStatePlugin.js +36 -9
  13. package/dist/esm/localisedUrls/config.mjs +11 -0
  14. package/dist/esm/localisedUrls/index.mjs +8 -0
  15. package/dist/esm/localisedUrls/normalise.mjs +37 -0
  16. package/dist/esm/localisedUrls/pathname.mjs +24 -0
  17. package/dist/esm/localisedUrls/patterns.mjs +152 -0
  18. package/dist/esm/localisedUrls/redirect.mjs +53 -0
  19. package/dist/esm/localisedUrls/resolve.mjs +37 -0
  20. package/dist/esm/localisedUrls/routeIdentity.mjs +54 -0
  21. package/dist/esm/localisedUrls/routes.mjs +176 -0
  22. package/dist/esm/localisedUrls/types.mjs +0 -0
  23. package/dist/esm/routerState.mjs +49 -75
  24. package/dist/esm/routerStatePlugin.mjs +37 -10
  25. package/dist/esm-node/localisedUrls/config.mjs +12 -0
  26. package/dist/esm-node/localisedUrls/index.mjs +9 -0
  27. package/dist/esm-node/localisedUrls/normalise.mjs +38 -0
  28. package/dist/esm-node/localisedUrls/pathname.mjs +25 -0
  29. package/dist/esm-node/localisedUrls/patterns.mjs +153 -0
  30. package/dist/esm-node/localisedUrls/redirect.mjs +54 -0
  31. package/dist/esm-node/localisedUrls/resolve.mjs +38 -0
  32. package/dist/esm-node/localisedUrls/routeIdentity.mjs +55 -0
  33. package/dist/esm-node/localisedUrls/routes.mjs +177 -0
  34. package/dist/esm-node/localisedUrls/types.mjs +1 -0
  35. package/dist/esm-node/routerState.mjs +49 -75
  36. package/dist/esm-node/routerStatePlugin.mjs +37 -10
  37. package/dist/types/localisedUrls/config.d.ts +9 -0
  38. package/dist/types/localisedUrls/index.d.ts +10 -0
  39. package/dist/types/localisedUrls/normalise.d.ts +10 -0
  40. package/dist/types/localisedUrls/pathname.d.ts +4 -0
  41. package/dist/types/localisedUrls/patterns.d.ts +11 -0
  42. package/dist/types/localisedUrls/redirect.d.ts +19 -0
  43. package/dist/types/localisedUrls/resolve.d.ts +7 -0
  44. package/dist/types/localisedUrls/routeIdentity.d.ts +22 -0
  45. package/dist/types/localisedUrls/routes.d.ts +3 -0
  46. package/dist/types/localisedUrls/types.d.ts +14 -0
  47. package/dist/types/routeHydration.d.ts +2 -2
  48. package/dist/types/routerState.d.ts +5 -6
  49. package/dist/types/routerStateTypes.d.ts +47 -17
  50. package/package.json +16 -4
  51. package/src/localisedUrls/config.ts +18 -0
  52. package/src/localisedUrls/index.ts +25 -0
  53. package/src/localisedUrls/normalise.ts +62 -0
  54. package/src/localisedUrls/pathname.ts +60 -0
  55. package/src/localisedUrls/patterns.ts +283 -0
  56. package/src/localisedUrls/redirect.ts +107 -0
  57. package/src/localisedUrls/resolve.ts +106 -0
  58. package/src/localisedUrls/routeIdentity.ts +83 -0
  59. package/src/localisedUrls/routes.ts +451 -0
  60. package/src/localisedUrls/types.ts +18 -0
  61. package/src/routeHydration.ts +2 -2
  62. package/src/routerState.ts +52 -122
  63. package/src/routerStatePlugin.ts +49 -10
  64. package/src/routerStateTypes.ts +47 -17
  65. package/tests/localisedUrls.test.ts +560 -0
  66. package/tests/routerState.test.ts +7 -8
@@ -1,3 +1,4 @@
1
+ import type React from 'react';
1
2
  export type BuiltInRouterFramework = 'react-router' | 'tanstack';
2
3
  export type RouterFramework = BuiltInRouterFramework | (string & {});
3
4
  export interface RouterRouteMatchSnapshot {
@@ -7,34 +8,63 @@ export interface RouterRouteMatchSnapshot {
7
8
  params?: Record<string, string>;
8
9
  }
9
10
  export interface InternalRouterServerSnapshot {
10
- framework?: RouterFramework;
11
- basename?: string;
12
- statusCode?: number;
13
- errors?: Record<string, unknown>;
14
- routerData?: {
15
- loaderData?: Record<string, unknown>;
16
- errors?: Record<string, unknown>;
11
+ readonly framework?: RouterFramework;
12
+ readonly basename?: string;
13
+ readonly statusCode?: number;
14
+ readonly errors?: Record<string, unknown>;
15
+ readonly routerData?: {
16
+ readonly loaderData?: Record<string, unknown>;
17
+ readonly errors?: Record<string, unknown>;
17
18
  };
18
- hydrationScript?: string;
19
- hydrationScripts?: string[];
20
- matchedRouteIds?: string[];
21
- matches?: RouterRouteMatchSnapshot[];
19
+ readonly hydrationScripts?: readonly string[];
20
+ readonly matchedRouteIds?: readonly string[];
21
+ readonly matches?: readonly RouterRouteMatchSnapshot[];
22
22
  }
23
23
  export interface InternalRouterRuntimeState {
24
24
  framework: RouterFramework;
25
25
  basename?: string;
26
26
  instance?: unknown;
27
- hydrationScript?: string;
28
- hydrationScripts?: string[];
29
- matchedRouteIds?: string[];
30
- matches?: RouterRouteMatchSnapshot[];
31
- serverSnapshot?: InternalRouterServerSnapshot;
27
+ navigation?: RouterNavigationCapability;
32
28
  cleanup?: () => void | Promise<void>;
33
29
  }
34
30
  export interface RouterServerPrepareResult {
35
31
  state: InternalRouterRuntimeState;
36
32
  snapshot?: InternalRouterServerSnapshot;
37
- redirect?: Response;
38
33
  cleanup?: () => void | Promise<void>;
39
34
  }
40
35
  export type RouterLifecyclePhase = 'ssr-prepare' | 'client-create' | 'hydrate';
36
+ /** Provider-owned browser navigation. Consumers never inspect router internals. */
37
+ export interface RouterNavigationSnapshot {
38
+ location: {
39
+ pathname: string;
40
+ search: string;
41
+ hash: string;
42
+ };
43
+ params: Record<string, string>;
44
+ }
45
+ export interface RouterLinkTarget {
46
+ pathname: string;
47
+ href: string;
48
+ search?: Record<string, unknown>;
49
+ hash?: string;
50
+ hashScrollIntoView?: boolean | ScrollIntoViewOptions;
51
+ prefetch?: 'intent' | 'render' | 'viewport' | 'none';
52
+ preload?: unknown;
53
+ }
54
+ export interface RouterNavigationCapability {
55
+ getSnapshot: () => RouterNavigationSnapshot;
56
+ subscribe: (listener: () => void) => () => void;
57
+ navigate: (href: string, options?: {
58
+ replace?: boolean;
59
+ state?: unknown;
60
+ }) => void | Promise<void>;
61
+ Link: React.ComponentType<{
62
+ to: string;
63
+ children?: React.ReactNode;
64
+ [key: string]: unknown;
65
+ }>;
66
+ createLinkProps?: (target: RouterLinkTarget) => {
67
+ to: string;
68
+ [key: string]: unknown;
69
+ };
70
+ }
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "directory": "packages/runtime/runtime-extensions"
12
12
  },
13
13
  "license": "MIT",
14
- "version": "3.9.0-ultramodern.10",
14
+ "version": "3.9.0-ultramodern.12",
15
15
  "engines": {
16
16
  "node": ">=26.7.0"
17
17
  },
@@ -186,6 +186,14 @@
186
186
  "require": "./dist/cjs/routerPrefetchPolicy.js"
187
187
  },
188
188
  "default": "./dist/esm/routerPrefetchPolicy.mjs"
189
+ },
190
+ "./localised-urls": {
191
+ "types": "./dist/types/localisedUrls/index.d.ts",
192
+ "node": {
193
+ "import": "./dist/esm-node/localisedUrls/index.mjs",
194
+ "require": "./dist/cjs/localisedUrls/index.js"
195
+ },
196
+ "default": "./dist/esm/localisedUrls/index.mjs"
189
197
  }
190
198
  },
191
199
  "typesVersions": {
@@ -269,12 +277,16 @@
269
277
  "router-prefetch-policy": [
270
278
  "./dist/types/routerPrefetchPolicy.d.ts",
271
279
  "./src/routerPrefetchPolicy.ts"
280
+ ],
281
+ "localised-urls": [
282
+ "./dist/types/localisedUrls/index.d.ts",
283
+ "./src/localisedUrls/index.ts"
272
284
  ]
273
285
  }
274
286
  },
275
287
  "devDependencies": {
276
288
  "@loadable/component": "5.16.7",
277
- "@modern-js/utils": "npm:@bleedingdev/modern-js-utils@3.9.0-ultramodern.10",
289
+ "@modern-js/utils": "npm:@bleedingdev/modern-js-utils@3.9.0-ultramodern.12",
278
290
  "@rsbuild/core": "2.2.3",
279
291
  "@rslib/core": "1.0.0",
280
292
  "@scripts/rstest-config": "2.66.0",
@@ -303,8 +315,8 @@
303
315
  }
304
316
  },
305
317
  "dependencies": {
306
- "@modern-js/create-request": "npm:@bleedingdev/modern-js-create-request@3.9.0-ultramodern.10",
307
- "@modern-js/runtime-utils": "npm:@bleedingdev/modern-js-runtime-utils@3.9.0-ultramodern.10",
318
+ "@modern-js/create-request": "npm:@bleedingdev/modern-js-create-request@3.9.0-ultramodern.12",
319
+ "@modern-js/runtime-utils": "npm:@bleedingdev/modern-js-runtime-utils@3.9.0-ultramodern.12",
308
320
  "react-helmet-async": "3.0.0"
309
321
  },
310
322
  "scripts": {
@@ -0,0 +1,18 @@
1
+ import type { LocalisedUrlsOption, ResolvedLocalisedUrlsConfig } from './types';
2
+
3
+ /**
4
+ * Localised URLs are strictly opt-in: only an explicit, non-empty map enables
5
+ * route expansion and validation. `true`, `false`, an empty map and absence
6
+ * all resolve to disabled, so upstream-style configs (`localePathRedirect` +
7
+ * `languages` without a map) keep plain locale-prefix behavior instead of
8
+ * failing the build for every route missing from a map they never wrote.
9
+ */
10
+ export const resolveLocalisedUrlsConfig = (
11
+ option: LocalisedUrlsOption | undefined,
12
+ ): ResolvedLocalisedUrlsConfig => {
13
+ if (option && typeof option === 'object' && Object.keys(option).length > 0) {
14
+ return { enabled: true, map: option };
15
+ }
16
+
17
+ return { enabled: false, map: {} };
18
+ };
@@ -0,0 +1,25 @@
1
+ export { resolveLocalisedUrlsConfig } from './config';
2
+ export { normalisePathname, normalisePathPattern } from './normalise';
3
+ export {
4
+ canonicalTargetPathname,
5
+ localiseTargetPathname,
6
+ stripLanguagePrefix,
7
+ } from './pathname';
8
+ export { buildPathFromPattern, matchPathPattern } from './patterns';
9
+ export type { LocaleRedirectSkipRule } from './redirect';
10
+ export {
11
+ DEFAULT_LOCALE_REDIRECT_SKIP_RULES,
12
+ isDefaultLocaleRedirectSkipPath,
13
+ matchesPathPrefix,
14
+ shouldSkipLocaleRedirect,
15
+ } from './redirect';
16
+ export { resolveCanonicalLocalisedPath, resolveLocalisedPath } from './resolve';
17
+ export { createLocalisedRouteRewrite } from './routeIdentity';
18
+ export { applyLocalisedUrlsToRoutes, validateLocalisedUrls } from './routes';
19
+ export type {
20
+ LocalisedRoute,
21
+ LocalisedUrlPathMap,
22
+ LocalisedUrlsMap,
23
+ LocalisedUrlsOption,
24
+ ResolvedLocalisedUrlsConfig,
25
+ } from './types';
@@ -0,0 +1,62 @@
1
+ const LOCALE_PARAM_NAMES = new Set(['lang', 'locale', 'language']);
2
+
3
+ const normaliseSlashes = (path: string): string => {
4
+ const withoutDuplicateSlashes = path.replace(/\/+/g, '/');
5
+ const withLeadingSlash = withoutDuplicateSlashes.startsWith('/')
6
+ ? withoutDuplicateSlashes
7
+ : `/${withoutDuplicateSlashes}`;
8
+
9
+ return withLeadingSlash.length > 1
10
+ ? withLeadingSlash.replace(/\/+$/, '')
11
+ : withLeadingSlash;
12
+ };
13
+
14
+ export const normalisePathPattern = (path: string): string =>
15
+ normaliseSlashes(path).replace(/\[(.+?)\]/g, ':$1');
16
+
17
+ /**
18
+ * Normalise a concrete request pathname: slash cleanup only. Unlike
19
+ * {@link normalisePathPattern} it must not rewrite literal `[x]` segments to
20
+ * `:x` params — pathnames are values, not patterns.
21
+ */
22
+ export const normalisePathname = (pathname: string): string =>
23
+ normaliseSlashes(pathname);
24
+
25
+ export const normaliseRoutePath = (path: string): string => {
26
+ const normalized = normalisePathPattern(path);
27
+ return normalized === '/' ? '' : normalized.slice(1);
28
+ };
29
+
30
+ const getLocaleParamSegment = (segment: string): string | null => {
31
+ if (!segment.startsWith(':')) {
32
+ return null;
33
+ }
34
+
35
+ const paramName = segment.slice(1).replace(/\?$/, '');
36
+ return LOCALE_PARAM_NAMES.has(paramName) ? segment : null;
37
+ };
38
+
39
+ const splitPathSegments = (path?: string): string[] => {
40
+ if (!path) {
41
+ return [];
42
+ }
43
+
44
+ return normalisePathPattern(path).split('/').filter(Boolean);
45
+ };
46
+
47
+ export const stripLeadingLocaleParam = (path?: string): string | undefined => {
48
+ const segments = splitPathSegments(path);
49
+ const leadingLocaleParam = getLocaleParamSegment(segments[0] || '');
50
+
51
+ if (!leadingLocaleParam) {
52
+ return path;
53
+ }
54
+
55
+ const remainingPath = segments.slice(1).join('/');
56
+ return remainingPath ? `/${remainingPath}` : undefined;
57
+ };
58
+
59
+ export const getLeadingLocaleParam = (path?: string): string | null => {
60
+ const segments = splitPathSegments(path);
61
+ return getLocaleParamSegment(segments[0] || '');
62
+ };
@@ -0,0 +1,60 @@
1
+ import { resolveLocalisedUrlsConfig } from './config';
2
+
3
+ import { resolveCanonicalLocalisedPath, resolveLocalisedPath } from './resolve';
4
+
5
+ import type { LocalisedUrlsOption } from './types';
6
+
7
+ export const stripLanguagePrefix = (
8
+ pathname: string,
9
+ languages: string[],
10
+ ): string => {
11
+ const segments = pathname.split('/').filter(Boolean);
12
+ const firstSegment = segments[0]?.toLowerCase();
13
+
14
+ if (
15
+ firstSegment &&
16
+ languages.some(language => language.toLowerCase() === firstSegment)
17
+ ) {
18
+ return `/${segments.slice(1).join('/')}`;
19
+ }
20
+
21
+ return pathname || '/';
22
+ };
23
+
24
+ export const localiseTargetPathname = (
25
+ pathname: string,
26
+ language: string,
27
+ languages: string[],
28
+ localisedUrls?: LocalisedUrlsOption,
29
+ ): string => {
30
+ const pathWithoutLanguage = stripLanguagePrefix(pathname, languages);
31
+ const localisedUrlsConfig = resolveLocalisedUrlsConfig(localisedUrls);
32
+ const resolvedPath = localisedUrlsConfig.enabled
33
+ ? resolveLocalisedPath(
34
+ pathWithoutLanguage,
35
+ language,
36
+ languages,
37
+ localisedUrlsConfig.map,
38
+ )
39
+ : pathWithoutLanguage;
40
+ const resolvedSegments = resolvedPath.split('/').filter(Boolean);
41
+
42
+ return `/${[language, ...resolvedSegments].join('/')}`;
43
+ };
44
+
45
+ export const canonicalTargetPathname = (
46
+ pathname: string,
47
+ languages: string[],
48
+ localisedUrls?: LocalisedUrlsOption,
49
+ ): string => {
50
+ const pathWithoutLanguage = stripLanguagePrefix(pathname, languages);
51
+ const localisedUrlsConfig = resolveLocalisedUrlsConfig(localisedUrls);
52
+
53
+ return localisedUrlsConfig.enabled
54
+ ? resolveCanonicalLocalisedPath(
55
+ pathWithoutLanguage,
56
+ languages,
57
+ localisedUrlsConfig.map,
58
+ )
59
+ : pathWithoutLanguage;
60
+ };
@@ -0,0 +1,283 @@
1
+ import { normalisePathname, normalisePathPattern } from './normalise';
2
+
3
+ const escapeRegExp = (value: string): string =>
4
+ value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
5
+
6
+ const getParamName = (segment: string): string =>
7
+ segment.slice(1).replace(/\?$/, '');
8
+
9
+ export const getOrderedPathParamSignature = (pattern: string): string[] =>
10
+ normalisePathPattern(pattern)
11
+ .split('/')
12
+ .filter(Boolean)
13
+ .flatMap(segment => {
14
+ if (segment === '*') {
15
+ return ['*'];
16
+ }
17
+ if (!segment.startsWith(':')) {
18
+ return [];
19
+ }
20
+
21
+ return [`:${getParamName(segment)}${segment.endsWith('?') ? '?' : ''}`];
22
+ });
23
+
24
+ export const getPathParamSignature = (pattern: string): string[] =>
25
+ getOrderedPathParamSignature(pattern).sort((left, right) =>
26
+ left < right ? -1 : left > right ? 1 : 0,
27
+ );
28
+
29
+ export const getPathPatternValidationIssue = (
30
+ pattern: string,
31
+ ): string | undefined => {
32
+ const segments = normalisePathPattern(pattern).split('/').filter(Boolean);
33
+ const seenParams = new Set<string>();
34
+
35
+ for (const [index, segment] of segments.entries()) {
36
+ if (segment === '*') {
37
+ if (index !== segments.length - 1) {
38
+ return 'splat parameter "*" must be the final segment';
39
+ }
40
+ if (seenParams.has('*')) {
41
+ return 'duplicate splat parameter "*"';
42
+ }
43
+ seenParams.add('*');
44
+ continue;
45
+ }
46
+ if (!segment.startsWith(':')) {
47
+ continue;
48
+ }
49
+
50
+ const paramName = getParamName(segment);
51
+ if (seenParams.has(paramName)) {
52
+ return `duplicate path parameter ":${paramName}"`;
53
+ }
54
+ seenParams.add(paramName);
55
+ }
56
+
57
+ return undefined;
58
+ };
59
+
60
+ export const getPhysicalPathPattern = (pattern: string): string => {
61
+ const segments = normalisePathPattern(pattern).split('/').filter(Boolean);
62
+ const physicalSegments = segments.map(segment => {
63
+ if (segment === '*') {
64
+ return '*';
65
+ }
66
+ if (segment.startsWith(':')) {
67
+ return segment.endsWith('?') ? ':param?' : ':param';
68
+ }
69
+ return segment;
70
+ });
71
+
72
+ return `/${physicalSegments.join('/')}`;
73
+ };
74
+
75
+ interface CompiledPathPattern {
76
+ names: string[];
77
+ regexp: RegExp;
78
+ }
79
+
80
+ const compiledPathPatternCache = new Map<string, CompiledPathPattern>();
81
+
82
+ const compilePathPattern = (pattern: string): CompiledPathPattern => {
83
+ const normalizedPattern = normalisePathPattern(pattern);
84
+ const cached = compiledPathPatternCache.get(normalizedPattern);
85
+ if (cached) {
86
+ return cached;
87
+ }
88
+
89
+ const names: string[] = [];
90
+ const segments = normalizedPattern.split('/').filter(Boolean);
91
+ const source = segments
92
+ .map(segment => {
93
+ if (segment.startsWith(':')) {
94
+ names.push(getParamName(segment));
95
+ const paramPattern = '([^/]+)';
96
+ return segment.endsWith('?')
97
+ ? `(?:/${paramPattern})?`
98
+ : `/${paramPattern}`;
99
+ }
100
+ if (segment === '*') {
101
+ names.push('*');
102
+ return '(?:/(.*))?';
103
+ }
104
+ return `/${escapeRegExp(segment)}`;
105
+ })
106
+ .join('');
107
+
108
+ const compiled = {
109
+ names,
110
+ regexp: new RegExp(`^${source || '/'}$`),
111
+ };
112
+ compiledPathPatternCache.set(normalizedPattern, compiled);
113
+
114
+ return compiled;
115
+ };
116
+
117
+ const getPatternSpecificity = (pattern: string) => {
118
+ const segments = normalisePathPattern(pattern).split('/').filter(Boolean);
119
+ let staticSegments = 0;
120
+ let dynamicSegments = 0;
121
+ let optionalSegments = 0;
122
+ let splatSegments = 0;
123
+
124
+ for (const segment of segments) {
125
+ if (segment === '*') {
126
+ splatSegments++;
127
+ } else if (segment.startsWith(':')) {
128
+ dynamicSegments++;
129
+ if (segment.endsWith('?')) {
130
+ optionalSegments++;
131
+ }
132
+ } else {
133
+ staticSegments++;
134
+ }
135
+ }
136
+
137
+ return {
138
+ staticSegments,
139
+ dynamicSegments,
140
+ optionalSegments,
141
+ splatSegments,
142
+ totalSegments: segments.length,
143
+ };
144
+ };
145
+
146
+ const comparePatternSpecificity = (left: string, right: string): number => {
147
+ const a = getPatternSpecificity(left);
148
+ const b = getPatternSpecificity(right);
149
+
150
+ return (
151
+ b.staticSegments - a.staticSegments ||
152
+ a.splatSegments - b.splatSegments ||
153
+ a.optionalSegments - b.optionalSegments ||
154
+ b.totalSegments - a.totalSegments ||
155
+ a.dynamicSegments - b.dynamicSegments
156
+ );
157
+ };
158
+
159
+ export const haveEqualPatternSpecificity = (
160
+ left: string,
161
+ right: string,
162
+ ): boolean => comparePatternSpecificity(left, right) === 0;
163
+
164
+ export const doPathPatternsOverlap = (left: string, right: string): boolean => {
165
+ const leftSegments = normalisePathPattern(left).split('/').filter(Boolean);
166
+ const rightSegments = normalisePathPattern(right).split('/').filter(Boolean);
167
+ if (leftSegments.length !== rightSegments.length) {
168
+ return false;
169
+ }
170
+
171
+ return leftSegments.every((leftSegment, index) => {
172
+ const rightSegment = rightSegments[index];
173
+ const leftIsDynamic = leftSegment === '*' || leftSegment.startsWith(':');
174
+ const rightIsDynamic = rightSegment === '*' || rightSegment.startsWith(':');
175
+ return leftIsDynamic || rightIsDynamic || leftSegment === rightSegment;
176
+ });
177
+ };
178
+
179
+ const comparePatternNames = (left: string, right: string): number => {
180
+ const normalizedLeft = normalisePathPattern(left);
181
+ const normalizedRight = normalisePathPattern(right);
182
+
183
+ return normalizedLeft < normalizedRight
184
+ ? -1
185
+ : normalizedLeft > normalizedRight
186
+ ? 1
187
+ : 0;
188
+ };
189
+
190
+ export const sortPatternsBySpecificity = <T extends { pattern: string }>(
191
+ patterns: T[],
192
+ ): T[] =>
193
+ patterns
194
+ .map((pattern, index) => ({ pattern, index }))
195
+ .sort(
196
+ (left, right) =>
197
+ comparePatternSpecificity(
198
+ left.pattern.pattern,
199
+ right.pattern.pattern,
200
+ ) ||
201
+ comparePatternNames(left.pattern.pattern, right.pattern.pattern) ||
202
+ left.index - right.index,
203
+ )
204
+ .map(({ pattern }) => pattern);
205
+
206
+ /**
207
+ * `decodeURIComponent` throws `URIError` on malformed percent-encoding
208
+ * (e.g. `%E0%A4%A`), which attacker-controlled request URLs can carry.
209
+ * Treat such segments as undecodable instead of throwing.
210
+ */
211
+ const decodePathParam = (value: string): string | null => {
212
+ try {
213
+ return decodeURIComponent(value);
214
+ } catch {
215
+ return null;
216
+ }
217
+ };
218
+
219
+ const encodeSplatParam = (value: string): string =>
220
+ value.split('/').map(encodeURIComponent).join('/');
221
+
222
+ export const matchPathPattern = (
223
+ pathname: string,
224
+ pattern: string,
225
+ ): Record<string, string> | null => {
226
+ const { names, regexp } = compilePathPattern(pattern);
227
+ const match = regexp.exec(normalisePathname(pathname));
228
+ if (!match) {
229
+ return null;
230
+ }
231
+
232
+ const params: Record<string, string> = {};
233
+ for (let index = 0; index < names.length; index++) {
234
+ const decoded = decodePathParam(match[index + 1] || '');
235
+ if (decoded === null) {
236
+ // Malformed encoding cannot identify a localised route: no match.
237
+ return null;
238
+ }
239
+ Object.defineProperty(params, names[index], {
240
+ configurable: true,
241
+ enumerable: true,
242
+ value: decoded,
243
+ writable: true,
244
+ });
245
+ }
246
+
247
+ return params;
248
+ };
249
+
250
+ export const buildPathFromPattern = (
251
+ pattern: string,
252
+ params: Record<string, string>,
253
+ ): string => {
254
+ const segments = normalisePathPattern(pattern).split('/').filter(Boolean);
255
+ const path = segments
256
+ .map(segment => {
257
+ if (segment.startsWith(':')) {
258
+ const paramName = getParamName(segment);
259
+ const param = Object.hasOwn(params, paramName)
260
+ ? params[paramName]
261
+ : undefined;
262
+ if (param === undefined || param === '') {
263
+ if (segment.endsWith('?')) {
264
+ return '';
265
+ }
266
+ throw new Error(
267
+ `Missing required path parameter "${paramName}" for pattern "${normalisePathPattern(
268
+ pattern,
269
+ )}".`,
270
+ );
271
+ }
272
+ return encodeURIComponent(param);
273
+ }
274
+ if (segment === '*') {
275
+ return encodeSplatParam(params['*'] || '');
276
+ }
277
+ return segment;
278
+ })
279
+ .filter(Boolean)
280
+ .join('/');
281
+
282
+ return `/${path}`;
283
+ };
@@ -0,0 +1,107 @@
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
+ type: 'pattern';
15
+ path: RegExp;
16
+ };
17
+
18
+ /**
19
+ * Federation artifacts are never pages. The remote entries match the same
20
+ * shapes the federation layer itself recognises and serves (`mfCache.ts`):
21
+ * a manifest may name a root entry such as `remoteEntry.catalog.js`.
22
+ */
23
+ export const DEFAULT_LOCALE_REDIRECT_SKIP_RULES: readonly LocaleRedirectSkipRule[] =
24
+ [
25
+ { type: 'exact', path: '/backend-mf-manifest.json' },
26
+ { type: 'exact', path: '/mf-manifest.json' },
27
+ { type: 'exact', path: '/mf-stats.json' },
28
+ {
29
+ type: 'pattern',
30
+ path: /^\/(?:backendRemoteEntry(?:\.[a-zA-Z0-9_-]+)?\.cjs|remoteEntry(?:\.[a-zA-Z0-9_-]+)?\.js)$/,
31
+ },
32
+ { type: 'prefix', path: '/static/' },
33
+ { type: 'prefix', path: '/upload/' },
34
+ ];
35
+
36
+ const stripTrailingSlash = (pathname: string): string =>
37
+ pathname.length > 1 ? pathname.replace(/\/+$/, '') : pathname;
38
+
39
+ export const matchesPathPrefix = (
40
+ pathname: string,
41
+ prefix: string,
42
+ ): boolean => {
43
+ const normalizedPathname = normalisePathname(pathname);
44
+ const normalizedPrefix = stripTrailingSlash(normalisePathname(prefix));
45
+
46
+ return (
47
+ normalizedPathname === normalizedPrefix ||
48
+ normalizedPathname.startsWith(`${normalizedPrefix}/`)
49
+ );
50
+ };
51
+
52
+ const matchesSkipRule = (
53
+ pathname: string,
54
+ rule: LocaleRedirectSkipRule,
55
+ ): boolean => {
56
+ if (rule.type === 'exact') {
57
+ return normalisePathname(pathname) === normalisePathname(rule.path);
58
+ }
59
+ if (rule.type === 'pattern') {
60
+ return rule.path.test(normalisePathname(pathname));
61
+ }
62
+
63
+ return matchesPathPrefix(pathname, rule.path);
64
+ };
65
+
66
+ export const isDefaultLocaleRedirectSkipPath = (
67
+ pathname: string,
68
+ languages: string[] = [],
69
+ ): boolean => {
70
+ const normalizedPathname = normalisePathname(pathname);
71
+ const pathWithoutLanguage = stripLanguagePrefix(
72
+ normalizedPathname,
73
+ languages,
74
+ );
75
+
76
+ return DEFAULT_LOCALE_REDIRECT_SKIP_RULES.some(rule =>
77
+ matchesSkipRule(pathWithoutLanguage, rule),
78
+ );
79
+ };
80
+
81
+ export const shouldSkipLocaleRedirect = (
82
+ pathname: string,
83
+ languages: string[] = [],
84
+ ignoreRedirectRoutes?: string[] | ((pathname: string) => boolean),
85
+ ): boolean => {
86
+ const normalizedPathname = normalisePathname(pathname);
87
+ const pathWithoutLanguage = stripLanguagePrefix(
88
+ normalizedPathname,
89
+ languages,
90
+ );
91
+
92
+ if (isDefaultLocaleRedirectSkipPath(pathWithoutLanguage)) {
93
+ return true;
94
+ }
95
+
96
+ if (!ignoreRedirectRoutes) {
97
+ return false;
98
+ }
99
+
100
+ if (typeof ignoreRedirectRoutes === 'function') {
101
+ return ignoreRedirectRoutes(pathWithoutLanguage);
102
+ }
103
+
104
+ return ignoreRedirectRoutes.some(pattern =>
105
+ matchesPathPrefix(pathWithoutLanguage, pattern),
106
+ );
107
+ };