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

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 (51) hide show
  1. package/dist/cjs/index.js +9 -2
  2. package/dist/cjs/localeRedirectPolicy.js +96 -0
  3. package/dist/cjs/localisedUrls/index.js +7 -0
  4. package/dist/cjs/localisedUrls/redirect.js +3 -6
  5. package/dist/cjs/localisedUrls/routeIdentity.js +118 -0
  6. package/dist/cjs/localisedUrls/routes.js +8 -0
  7. package/dist/cjs/paths.js +56 -0
  8. package/dist/cjs/router-navigation/adapter.js +235 -0
  9. package/dist/cjs/router-navigation/index.js +40 -0
  10. package/dist/esm/index.mjs +1 -0
  11. package/dist/esm/localeRedirectPolicy.mjs +46 -0
  12. package/dist/esm/localisedUrls/index.mjs +1 -0
  13. package/dist/esm/localisedUrls/redirect.mjs +3 -6
  14. package/dist/esm/localisedUrls/routeIdentity.mjs +77 -0
  15. package/dist/esm/localisedUrls/routes.mjs +8 -0
  16. package/dist/esm/paths.mjs +12 -0
  17. package/dist/esm/router-navigation/adapter.mjs +197 -0
  18. package/dist/esm/router-navigation/index.mjs +1 -0
  19. package/dist/esm-node/index.mjs +1 -0
  20. package/dist/esm-node/localeRedirectPolicy.mjs +47 -0
  21. package/dist/esm-node/localisedUrls/index.mjs +1 -0
  22. package/dist/esm-node/localisedUrls/redirect.mjs +3 -6
  23. package/dist/esm-node/localisedUrls/routeIdentity.mjs +78 -0
  24. package/dist/esm-node/localisedUrls/routes.mjs +8 -0
  25. package/dist/esm-node/paths.mjs +13 -0
  26. package/dist/esm-node/router-navigation/adapter.mjs +198 -0
  27. package/dist/esm-node/router-navigation/index.mjs +2 -0
  28. package/dist/types/index.d.ts +1 -0
  29. package/dist/types/localeRedirectPolicy.d.ts +22 -0
  30. package/dist/types/localisedUrls/index.d.ts +1 -0
  31. package/dist/types/localisedUrls/redirect.d.ts +8 -0
  32. package/dist/types/localisedUrls/routeIdentity.d.ts +24 -0
  33. package/dist/types/paths.d.ts +9 -0
  34. package/dist/types/router-navigation/adapter.d.ts +71 -0
  35. package/dist/types/router-navigation/index.d.ts +1 -0
  36. package/package.json +29 -5
  37. package/src/index.ts +1 -0
  38. package/src/localeRedirectPolicy.ts +127 -0
  39. package/src/localisedUrls/index.ts +4 -0
  40. package/src/localisedUrls/redirect.ts +16 -2
  41. package/src/localisedUrls/routeIdentity.ts +107 -0
  42. package/src/localisedUrls/routes.ts +10 -0
  43. package/src/paths.ts +37 -0
  44. package/src/router-navigation/adapter.tsx +536 -0
  45. package/src/router-navigation/index.ts +6 -0
  46. package/tests/languageSyncController.test.ts +0 -77
  47. package/tests/localeRedirectPolicy.test.ts +173 -0
  48. package/tests/localisedUrls.test.ts +0 -141
  49. package/tests/paths.test.ts +24 -0
  50. package/tests/reactLanguageSync.test.tsx +20 -1
  51. package/tests/clientRedirectIntegration.test.tsx +0 -74
@@ -0,0 +1,46 @@
1
+ import { isDefaultLocaleRedirectSkipPath, localiseTargetPathname, matchesPathPrefix, shouldSkipLocaleRedirect, stripLanguagePrefix } from "./localisedUrls/index.mjs";
2
+ const stripUrlPathPrefix = (pathname, urlPath)=>{
3
+ const basePath = urlPath.replace('/*', '');
4
+ if (!basePath || '/' === basePath) return pathname;
5
+ const remainingPath = pathname.startsWith(basePath) ? pathname.slice(basePath.length) : pathname;
6
+ return remainingPath || '/';
7
+ };
8
+ const shouldIgnoreRedirect = (pathname, urlPath, ignoreRedirectRoutes)=>{
9
+ const remainingPath = stripUrlPathPrefix(pathname, urlPath);
10
+ return shouldSkipLocaleRedirect(remainingPath, [], ignoreRedirectRoutes);
11
+ };
12
+ const isStaticResourceRequest = (pathname, staticRoutePrefixes, languages = [])=>{
13
+ if (isDefaultLocaleRedirectSkipPath(pathname, languages)) return true;
14
+ const matchesStaticRoutePrefix = (targetPathname)=>staticRoutePrefixes.some((prefix)=>matchesPathPrefix(targetPathname, prefix));
15
+ if (matchesStaticRoutePrefix(pathname)) return true;
16
+ const pathWithoutLanguage = stripLanguagePrefix(pathname, languages);
17
+ return pathWithoutLanguage !== pathname && matchesStaticRoutePrefix(pathWithoutLanguage);
18
+ };
19
+ const getLanguageFromPath = (req, urlPath, languages)=>{
20
+ const url = new URL(req.url, `http://${req.header().host}`);
21
+ const pathname = url.pathname;
22
+ const remainingPath = stripUrlPathPrefix(pathname, urlPath);
23
+ const segments = remainingPath.split('/').filter(Boolean);
24
+ const firstSegment = segments[0];
25
+ if (languages.includes(firstSegment)) return firstSegment;
26
+ return null;
27
+ };
28
+ const buildLocalizedUrl = (req, urlPath, language, languages, localisedUrls)=>{
29
+ const url = new URL(req.url);
30
+ const pathname = url.pathname;
31
+ const basePath = urlPath.replace('/*', '');
32
+ const remainingPath = stripUrlPathPrefix(pathname, urlPath);
33
+ const newPathname = localiseTargetPathname(remainingPath, language, languages, localisedUrls);
34
+ const suffix = `${url.search}${url.hash}`;
35
+ const localizedUrl = '/' === basePath ? newPathname + suffix : basePath + newPathname + suffix;
36
+ return localizedUrl;
37
+ };
38
+ const createLocaleRedirectResponse = (location)=>new Response(null, {
39
+ status: 302,
40
+ headers: {
41
+ 'Cache-Control': 'private, no-store',
42
+ Location: location,
43
+ Vary: 'Accept-Language, Cookie'
44
+ }
45
+ });
46
+ export { buildLocalizedUrl, createLocaleRedirectResponse, getLanguageFromPath, isStaticResourceRequest, shouldIgnoreRedirect };
@@ -4,4 +4,5 @@ export { canonicalTargetPathname, localiseTargetPathname, stripLanguagePrefix }
4
4
  export { buildPathFromPattern, matchPathPattern } from "./patterns.mjs";
5
5
  export { DEFAULT_LOCALE_REDIRECT_SKIP_RULES, isDefaultLocaleRedirectSkipPath, matchesPathPrefix, shouldSkipLocaleRedirect } from "./redirect.mjs";
6
6
  export { resolveCanonicalLocalisedPath, resolveLocalisedPath } from "./resolve.mjs";
7
+ export { canonicaliseLocalisedRoutes, createLocalisedRouteRewrite } from "./routeIdentity.mjs";
7
8
  export { applyLocalisedUrlsToRoutes, validateLocalisedUrls } from "./routes.mjs";
@@ -5,10 +5,6 @@ const DEFAULT_LOCALE_REDIRECT_SKIP_RULES = [
5
5
  type: 'exact',
6
6
  path: '/backend-mf-manifest.json'
7
7
  },
8
- {
9
- type: 'exact',
10
- path: '/backendRemoteEntry.cjs'
11
- },
12
8
  {
13
9
  type: 'exact',
14
10
  path: '/mf-manifest.json'
@@ -18,8 +14,8 @@ const DEFAULT_LOCALE_REDIRECT_SKIP_RULES = [
18
14
  path: '/mf-stats.json'
19
15
  },
20
16
  {
21
- type: 'exact',
22
- path: '/remoteEntry.js'
17
+ type: 'pattern',
18
+ path: /^\/(?:backendRemoteEntry(?:\.[a-zA-Z0-9_-]+)?\.cjs|remoteEntry(?:\.[a-zA-Z0-9_-]+)?\.js)$/
23
19
  },
24
20
  {
25
21
  type: 'prefix',
@@ -38,6 +34,7 @@ const matchesPathPrefix = (pathname, prefix)=>{
38
34
  };
39
35
  const matchesSkipRule = (pathname, rule)=>{
40
36
  if ('exact' === rule.type) return normalisePathname(pathname) === normalisePathname(rule.path);
37
+ if ('pattern' === rule.type) return rule.path.test(normalisePathname(pathname));
41
38
  return matchesPathPrefix(pathname, rule.path);
42
39
  };
43
40
  const isDefaultLocaleRedirectSkipPath = (pathname, languages = [])=>{
@@ -0,0 +1,77 @@
1
+ import { normalisePathPattern } from "./normalise.mjs";
2
+ import { buildPathFromPattern, matchPathPattern } from "./patterns.mjs";
3
+ function canonicaliseLocalisedRoutes(routes) {
4
+ const seen = new Set();
5
+ return routes.flatMap((route)=>{
6
+ const identity = route.modernLocalisedRoute;
7
+ const key = identity?.id ?? identity?.path;
8
+ if (void 0 !== key) {
9
+ if (seen.has(key)) return [];
10
+ seen.add(key);
11
+ }
12
+ return [
13
+ {
14
+ ...route,
15
+ ...identity ? {
16
+ id: identity.id,
17
+ path: identity.path
18
+ } : {},
19
+ ...route.children ? {
20
+ children: canonicaliseLocalisedRoutes(route.children)
21
+ } : {}
22
+ }
23
+ ];
24
+ });
25
+ }
26
+ function rewritePath(url, mappings) {
27
+ for (const { from, to } of mappings){
28
+ const params = matchPathPattern(url.pathname, from);
29
+ if (params) {
30
+ url.pathname = buildPathFromPattern(to, params);
31
+ break;
32
+ }
33
+ }
34
+ return url;
35
+ }
36
+ function createLocalisedRouteRewrite(routes) {
37
+ const input = [];
38
+ const output = [];
39
+ const visit = (nodes, parent)=>{
40
+ for (const route of nodes){
41
+ const fullPath = normalisePathPattern(`${parent}/${route.path ?? ''}`);
42
+ const identity = route.modernLocalisedRoute;
43
+ if (identity?.paths && fullPath.endsWith(identity.canonicalPath)) {
44
+ const prefix = fullPath.slice(0, -identity.canonicalPath.length);
45
+ const hasLocale = prefix.split('/').some((segment)=>/^:(?:lang|locale|language)\??$/.test(segment));
46
+ for (const [language, localisedPath] of Object.entries(identity.paths)){
47
+ const localePrefix = prefix.split('/').map((segment)=>/^:(?:lang|locale|language)\??$/.test(segment) ? language : segment).join('/');
48
+ const canonical = normalisePathPattern(`${localePrefix}/${identity.canonicalPath}`);
49
+ const localised = normalisePathPattern(`${localePrefix}/${localisedPath}`);
50
+ if (canonical !== localised) {
51
+ input.push({
52
+ from: localised,
53
+ to: canonical
54
+ });
55
+ if (hasLocale) output.push({
56
+ from: canonical,
57
+ to: localised
58
+ });
59
+ }
60
+ }
61
+ }
62
+ if (route.children) visit(route.children, fullPath);
63
+ }
64
+ };
65
+ visit(canonicaliseLocalisedRoutes(routes), '');
66
+ if (0 === input.length) return;
67
+ const specificity = (pattern)=>pattern.split('/').filter((segment)=>segment && !segment.startsWith(':') && '*' !== segment).length;
68
+ for (const mappings of [
69
+ input,
70
+ output
71
+ ])mappings.sort((a, b)=>specificity(b.from) - specificity(a.from));
72
+ return {
73
+ input: ({ url })=>rewritePath(url, input),
74
+ output: ({ url })=>rewritePath(url, output)
75
+ };
76
+ }
77
+ export { canonicaliseLocalisedRoutes, createLocalisedRouteRewrite };
@@ -101,6 +101,14 @@ const transformLocalisedRoute = (route, parentCanonicalPath, parentLocalisedPath
101
101
  const children = 'children' in route && route.children ? route.children.flatMap((child)=>transformLocalisedRoute(child, canonicalPath, routeLocalisedPaths, languages, localisedUrls)) : void 0;
102
102
  const baseRoute = {
103
103
  ...route,
104
+ ...!isFrameworkInternalRoutePath(canonicalPath) ? {
105
+ modernLocalisedRoute: {
106
+ id: route.id,
107
+ path: route.path,
108
+ canonicalPath,
109
+ paths: localisedUrlEntry
110
+ }
111
+ } : {},
104
112
  ...children ? {
105
113
  children
106
114
  } : {}
@@ -0,0 +1,12 @@
1
+ import { splitUrlTarget } from "@modern-js/runtime-utils/url";
2
+ import { canonicalTargetPathname, localiseTargetPathname } from "./localisedUrls/index.mjs";
3
+ const buildLocalizedUrl = (target, language, languages, localisedUrls)=>{
4
+ const { pathname, search, hash } = splitUrlTarget(target);
5
+ return `${localiseTargetPathname(pathname, language, languages, localisedUrls)}${search}${hash}`;
6
+ };
7
+ const localizePath = (target, language, config)=>buildLocalizedUrl(target, language, config.languages, config.localisedUrls);
8
+ const canonicalPath = (target, config)=>{
9
+ const { pathname, search, hash } = splitUrlTarget(target);
10
+ return `${canonicalTargetPathname(pathname, config.languages, config.localisedUrls)}${search}${hash}`;
11
+ };
12
+ export { buildLocalizedUrl, canonicalPath, localizePath };
@@ -0,0 +1,197 @@
1
+ import { Fragment, jsx } from "react/jsx-runtime";
2
+ import { RuntimeContext, isBrowser } from "@modern-js/runtime";
3
+ import { InternalRuntimeContext } from "@modern-js/runtime/context";
4
+ import { getRouterRuntimeState, subscribeRouterRuntimeState } from "@modern-js/runtime-extensions/router-state";
5
+ import { useCallback, useContext, useSyncExternalStore } from "react";
6
+ const normalizeUrlPart = (value, prefix)=>{
7
+ if ('string' != typeof value || !value) return '';
8
+ return value.startsWith(prefix) ? value : `${prefix}${value}`;
9
+ };
10
+ const normalizeLocation = (location)=>{
11
+ if (!location || 'object' != typeof location) return null;
12
+ const locationValue = location;
13
+ if ('string' != typeof locationValue.pathname) return null;
14
+ return {
15
+ pathname: locationValue.pathname,
16
+ search: normalizeUrlPart('string' == typeof locationValue.search ? locationValue.search : locationValue.searchStr, '?'),
17
+ hash: normalizeUrlPart(locationValue.hash, '#')
18
+ };
19
+ };
20
+ const getWindowLocation = ()=>{
21
+ if (!isBrowser()) return null;
22
+ return {
23
+ pathname: window.location.pathname,
24
+ search: window.location.search,
25
+ hash: window.location.hash
26
+ };
27
+ };
28
+ const getRouterFramework = (runtimeContext, internalContext, inReactRouter)=>{
29
+ const framework = getRouterRuntimeState(internalContext)?.framework || getRouterRuntimeState(runtimeContext)?.framework;
30
+ if (framework) return framework;
31
+ if (internalContext.router?.useRouter || runtimeContext.router?.useRouter) return 'tanstack';
32
+ if (internalContext.router?.useLocation || internalContext.router?.useHref || runtimeContext.router?.useLocation || runtimeContext.router?.useHref) return 'react-router';
33
+ if (inReactRouter) return 'react-router';
34
+ };
35
+ const getRouterInstance = (internalContext, contextRouter)=>{
36
+ if (contextRouter) return contextRouter;
37
+ const router = getRouterRuntimeState(internalContext)?.instance;
38
+ if (!router || 'object' != typeof router) return null;
39
+ return router;
40
+ };
41
+ const getRouterStateLocation = (internalContext, contextRouter)=>{
42
+ const router = getRouterInstance(internalContext, contextRouter);
43
+ return normalizeLocation(router?.stores?.location?.get?.()) || normalizeLocation(router?.state?.location);
44
+ };
45
+ const getRouterParams = (internalContext, contextRouter)=>{
46
+ const router = getRouterInstance(internalContext, contextRouter);
47
+ const matches = router?.stores?.matches?.get?.() || router?.state?.matches;
48
+ if (!Array.isArray(matches)) return {};
49
+ return matches.reduce((params, match)=>{
50
+ if (match?.params) Object.assign(params, match.params);
51
+ return params;
52
+ }, {});
53
+ };
54
+ const getRouterSnapshot = (internalContext, contextRouter)=>{
55
+ const location = getRouterStateLocation(internalContext, contextRouter);
56
+ const params = getRouterParams(internalContext, contextRouter);
57
+ return JSON.stringify([
58
+ location?.pathname ?? '',
59
+ location?.search ?? '',
60
+ location?.hash ?? '',
61
+ Object.entries(params).sort(([left], [right])=>left.localeCompare(right))
62
+ ]);
63
+ };
64
+ const createI18nRouterNavigation = ({ I18nNavigationProvider, useNativeI18nRouterAdapter })=>{
65
+ const useIntegratedRouterAdapter = ()=>{
66
+ const runtimeContext = useContext(RuntimeContext);
67
+ const internalContext = useContext(InternalRuntimeContext);
68
+ const routerApi = internalContext.router || runtimeContext.router;
69
+ const native = useNativeI18nRouterAdapter();
70
+ const inReactRouter = native.hasRouter;
71
+ const reactRouterNavigate = native.navigate;
72
+ const reactRouterLocation = inReactRouter ? native.location : null;
73
+ const reactRouterParams = native.params;
74
+ const framework = getRouterFramework(runtimeContext, internalContext, inReactRouter);
75
+ const contextUseRouter = inReactRouter || 'tanstack' !== framework ? void 0 : internalContext.router?.useRouter || runtimeContext.router?.useRouter;
76
+ const contextRouter = contextUseRouter ? contextUseRouter({
77
+ warn: false
78
+ }) : null;
79
+ const slotRouter = getRouterInstance(internalContext, contextRouter);
80
+ const drivableSlotRouter = ('tanstack' === framework || 'react-router' === framework) && 'function' == typeof slotRouter?.navigate;
81
+ const hasRouter = Boolean(reactRouterNavigate) || drivableSlotRouter;
82
+ const subscribeToRouter = useCallback((update)=>{
83
+ const unsubscribers = [];
84
+ const unsubscribeFromSlot = subscribeRouterRuntimeState(internalContext, update);
85
+ if ('function' == typeof unsubscribeFromSlot) unsubscribers.push(unsubscribeFromSlot);
86
+ const router = getRouterInstance(internalContext, contextRouter);
87
+ if (!router) return ()=>{
88
+ for (const unsubscribe of unsubscribers)unsubscribe();
89
+ };
90
+ if ('react-router' === framework && !inReactRouter && 'function' == typeof router.subscribe) {
91
+ const subscribe = router.subscribe;
92
+ const unsubscribe = subscribe.call(router, update);
93
+ if ('function' == typeof unsubscribe) unsubscribers.push(unsubscribe);
94
+ }
95
+ if ('tanstack' === framework && 'function' == typeof router.stores?.location?.subscribe) {
96
+ const unsubscribe = router.stores.location.subscribe(update);
97
+ if ('function' == typeof unsubscribe) unsubscribers.push(unsubscribe);
98
+ }
99
+ if ('tanstack' === framework && 'function' == typeof router.subscribe) {
100
+ const subscribe = router.subscribe;
101
+ for (const eventType of [
102
+ 'onBeforeNavigate',
103
+ 'onBeforeLoad'
104
+ ]){
105
+ const unsubscribe = subscribe.call(router, eventType, update);
106
+ if ('function' == typeof unsubscribe) unsubscribers.push(unsubscribe);
107
+ }
108
+ }
109
+ return ()=>{
110
+ for (const unsubscribe of unsubscribers)unsubscribe();
111
+ };
112
+ }, [
113
+ contextRouter,
114
+ framework,
115
+ inReactRouter,
116
+ internalContext
117
+ ]);
118
+ const getSnapshot = useCallback(()=>getRouterSnapshot(internalContext, contextRouter), [
119
+ contextRouter,
120
+ internalContext
121
+ ]);
122
+ useSyncExternalStore(subscribeToRouter, getSnapshot, getSnapshot);
123
+ const navigate = useCallback((href, options)=>{
124
+ const router = getRouterInstance(internalContext, contextRouter);
125
+ const activeFramework = getRouterFramework(runtimeContext, internalContext, inReactRouter);
126
+ if ('tanstack' === activeFramework) {
127
+ if ('function' == typeof router?.navigate) return router.navigate({
128
+ to: href,
129
+ replace: options?.replace,
130
+ ...options?.state === void 0 ? {} : {
131
+ state: options.state
132
+ }
133
+ });
134
+ throw new Error('TanStack router instance is not available.');
135
+ }
136
+ if (reactRouterNavigate) return reactRouterNavigate(href, options);
137
+ if ('react-router' === activeFramework) {
138
+ if ('function' == typeof router?.navigate) return router.navigate(href, options);
139
+ throw new Error('React Router instance is not available.');
140
+ }
141
+ }, [
142
+ contextRouter,
143
+ internalContext,
144
+ inReactRouter,
145
+ reactRouterNavigate,
146
+ runtimeContext
147
+ ]);
148
+ const location = (reactRouterLocation ? normalizeLocation(reactRouterLocation) : getRouterStateLocation(internalContext, contextRouter)) || getWindowLocation();
149
+ const params = inReactRouter ? reactRouterParams : getRouterParams(internalContext, contextRouter);
150
+ const Link = 'tanstack' === framework ? internalContext.router?.Link || runtimeContext.router?.Link || null : 'react-router' === framework || inReactRouter ? routerApi?.Link ?? null : null;
151
+ return {
152
+ framework,
153
+ hasRouter,
154
+ location,
155
+ navigate: hasRouter ? navigate : null,
156
+ Link,
157
+ params,
158
+ ...'tanstack' === framework ? {
159
+ createLinkProps: createTanstackLinkProps
160
+ } : {}
161
+ };
162
+ };
163
+ const createTanstackLinkProps = (target)=>{
164
+ const preload = void 0 !== target.preload ? target.preload : 'none' === target.prefetch ? false : target.prefetch;
165
+ return {
166
+ to: target.pathname,
167
+ ...target.search ? {
168
+ search: target.search
169
+ } : {},
170
+ ...target.hash ? {
171
+ hash: target.hash
172
+ } : {},
173
+ ...void 0 === target.hashScrollIntoView ? {} : {
174
+ hashScrollIntoView: target.hashScrollIntoView
175
+ },
176
+ ...void 0 === preload ? {} : {
177
+ preload
178
+ }
179
+ };
180
+ };
181
+ const I18nRouterNavigationProvider = ({ children })=>{
182
+ const value = useIntegratedRouterAdapter();
183
+ const native = useNativeI18nRouterAdapter();
184
+ if (!value.hasRouter || native.hasRouter) return /*#__PURE__*/ jsx(Fragment, {
185
+ children: children
186
+ });
187
+ return /*#__PURE__*/ jsx(I18nNavigationProvider, {
188
+ value: value,
189
+ children: children
190
+ });
191
+ };
192
+ return {
193
+ useIntegratedRouterAdapter,
194
+ I18nRouterNavigationProvider
195
+ };
196
+ };
197
+ export { createI18nRouterNavigation };
@@ -0,0 +1 @@
1
+ export { createI18nRouterNavigation } from "./adapter.mjs";
@@ -1,4 +1,5 @@
1
1
  import "node:module";
2
2
  export * from "./language-sync/controller.mjs";
3
3
  export * from "./language-sync/react.mjs";
4
+ export * from "./localeRedirectPolicy.mjs";
4
5
  export * from "./localisedUrls/index.mjs";
@@ -0,0 +1,47 @@
1
+ import "node:module";
2
+ import { isDefaultLocaleRedirectSkipPath, localiseTargetPathname, matchesPathPrefix, shouldSkipLocaleRedirect, stripLanguagePrefix } from "./localisedUrls/index.mjs";
3
+ const stripUrlPathPrefix = (pathname, urlPath)=>{
4
+ const basePath = urlPath.replace('/*', '');
5
+ if (!basePath || '/' === basePath) return pathname;
6
+ const remainingPath = pathname.startsWith(basePath) ? pathname.slice(basePath.length) : pathname;
7
+ return remainingPath || '/';
8
+ };
9
+ const shouldIgnoreRedirect = (pathname, urlPath, ignoreRedirectRoutes)=>{
10
+ const remainingPath = stripUrlPathPrefix(pathname, urlPath);
11
+ return shouldSkipLocaleRedirect(remainingPath, [], ignoreRedirectRoutes);
12
+ };
13
+ const isStaticResourceRequest = (pathname, staticRoutePrefixes, languages = [])=>{
14
+ if (isDefaultLocaleRedirectSkipPath(pathname, languages)) return true;
15
+ const matchesStaticRoutePrefix = (targetPathname)=>staticRoutePrefixes.some((prefix)=>matchesPathPrefix(targetPathname, prefix));
16
+ if (matchesStaticRoutePrefix(pathname)) return true;
17
+ const pathWithoutLanguage = stripLanguagePrefix(pathname, languages);
18
+ return pathWithoutLanguage !== pathname && matchesStaticRoutePrefix(pathWithoutLanguage);
19
+ };
20
+ const getLanguageFromPath = (req, urlPath, languages)=>{
21
+ const url = new URL(req.url, `http://${req.header().host}`);
22
+ const pathname = url.pathname;
23
+ const remainingPath = stripUrlPathPrefix(pathname, urlPath);
24
+ const segments = remainingPath.split('/').filter(Boolean);
25
+ const firstSegment = segments[0];
26
+ if (languages.includes(firstSegment)) return firstSegment;
27
+ return null;
28
+ };
29
+ const buildLocalizedUrl = (req, urlPath, language, languages, localisedUrls)=>{
30
+ const url = new URL(req.url);
31
+ const pathname = url.pathname;
32
+ const basePath = urlPath.replace('/*', '');
33
+ const remainingPath = stripUrlPathPrefix(pathname, urlPath);
34
+ const newPathname = localiseTargetPathname(remainingPath, language, languages, localisedUrls);
35
+ const suffix = `${url.search}${url.hash}`;
36
+ const localizedUrl = '/' === basePath ? newPathname + suffix : basePath + newPathname + suffix;
37
+ return localizedUrl;
38
+ };
39
+ const createLocaleRedirectResponse = (location)=>new Response(null, {
40
+ status: 302,
41
+ headers: {
42
+ 'Cache-Control': 'private, no-store',
43
+ Location: location,
44
+ Vary: 'Accept-Language, Cookie'
45
+ }
46
+ });
47
+ export { buildLocalizedUrl, createLocaleRedirectResponse, getLanguageFromPath, isStaticResourceRequest, shouldIgnoreRedirect };
@@ -5,4 +5,5 @@ export { canonicalTargetPathname, localiseTargetPathname, stripLanguagePrefix }
5
5
  export { buildPathFromPattern, matchPathPattern } from "./patterns.mjs";
6
6
  export { DEFAULT_LOCALE_REDIRECT_SKIP_RULES, isDefaultLocaleRedirectSkipPath, matchesPathPrefix, shouldSkipLocaleRedirect } from "./redirect.mjs";
7
7
  export { resolveCanonicalLocalisedPath, resolveLocalisedPath } from "./resolve.mjs";
8
+ export { canonicaliseLocalisedRoutes, createLocalisedRouteRewrite } from "./routeIdentity.mjs";
8
9
  export { applyLocalisedUrlsToRoutes, validateLocalisedUrls } from "./routes.mjs";
@@ -6,10 +6,6 @@ const DEFAULT_LOCALE_REDIRECT_SKIP_RULES = [
6
6
  type: 'exact',
7
7
  path: '/backend-mf-manifest.json'
8
8
  },
9
- {
10
- type: 'exact',
11
- path: '/backendRemoteEntry.cjs'
12
- },
13
9
  {
14
10
  type: 'exact',
15
11
  path: '/mf-manifest.json'
@@ -19,8 +15,8 @@ const DEFAULT_LOCALE_REDIRECT_SKIP_RULES = [
19
15
  path: '/mf-stats.json'
20
16
  },
21
17
  {
22
- type: 'exact',
23
- path: '/remoteEntry.js'
18
+ type: 'pattern',
19
+ path: /^\/(?:backendRemoteEntry(?:\.[a-zA-Z0-9_-]+)?\.cjs|remoteEntry(?:\.[a-zA-Z0-9_-]+)?\.js)$/
24
20
  },
25
21
  {
26
22
  type: 'prefix',
@@ -39,6 +35,7 @@ const matchesPathPrefix = (pathname, prefix)=>{
39
35
  };
40
36
  const matchesSkipRule = (pathname, rule)=>{
41
37
  if ('exact' === rule.type) return normalisePathname(pathname) === normalisePathname(rule.path);
38
+ if ('pattern' === rule.type) return rule.path.test(normalisePathname(pathname));
42
39
  return matchesPathPrefix(pathname, rule.path);
43
40
  };
44
41
  const isDefaultLocaleRedirectSkipPath = (pathname, languages = [])=>{
@@ -0,0 +1,78 @@
1
+ import "node:module";
2
+ import { normalisePathPattern } from "./normalise.mjs";
3
+ import { buildPathFromPattern, matchPathPattern } from "./patterns.mjs";
4
+ function canonicaliseLocalisedRoutes(routes) {
5
+ const seen = new Set();
6
+ return routes.flatMap((route)=>{
7
+ const identity = route.modernLocalisedRoute;
8
+ const key = identity?.id ?? identity?.path;
9
+ if (void 0 !== key) {
10
+ if (seen.has(key)) return [];
11
+ seen.add(key);
12
+ }
13
+ return [
14
+ {
15
+ ...route,
16
+ ...identity ? {
17
+ id: identity.id,
18
+ path: identity.path
19
+ } : {},
20
+ ...route.children ? {
21
+ children: canonicaliseLocalisedRoutes(route.children)
22
+ } : {}
23
+ }
24
+ ];
25
+ });
26
+ }
27
+ function rewritePath(url, mappings) {
28
+ for (const { from, to } of mappings){
29
+ const params = matchPathPattern(url.pathname, from);
30
+ if (params) {
31
+ url.pathname = buildPathFromPattern(to, params);
32
+ break;
33
+ }
34
+ }
35
+ return url;
36
+ }
37
+ function createLocalisedRouteRewrite(routes) {
38
+ const input = [];
39
+ const output = [];
40
+ const visit = (nodes, parent)=>{
41
+ for (const route of nodes){
42
+ const fullPath = normalisePathPattern(`${parent}/${route.path ?? ''}`);
43
+ const identity = route.modernLocalisedRoute;
44
+ if (identity?.paths && fullPath.endsWith(identity.canonicalPath)) {
45
+ const prefix = fullPath.slice(0, -identity.canonicalPath.length);
46
+ const hasLocale = prefix.split('/').some((segment)=>/^:(?:lang|locale|language)\??$/.test(segment));
47
+ for (const [language, localisedPath] of Object.entries(identity.paths)){
48
+ const localePrefix = prefix.split('/').map((segment)=>/^:(?:lang|locale|language)\??$/.test(segment) ? language : segment).join('/');
49
+ const canonical = normalisePathPattern(`${localePrefix}/${identity.canonicalPath}`);
50
+ const localised = normalisePathPattern(`${localePrefix}/${localisedPath}`);
51
+ if (canonical !== localised) {
52
+ input.push({
53
+ from: localised,
54
+ to: canonical
55
+ });
56
+ if (hasLocale) output.push({
57
+ from: canonical,
58
+ to: localised
59
+ });
60
+ }
61
+ }
62
+ }
63
+ if (route.children) visit(route.children, fullPath);
64
+ }
65
+ };
66
+ visit(canonicaliseLocalisedRoutes(routes), '');
67
+ if (0 === input.length) return;
68
+ const specificity = (pattern)=>pattern.split('/').filter((segment)=>segment && !segment.startsWith(':') && '*' !== segment).length;
69
+ for (const mappings of [
70
+ input,
71
+ output
72
+ ])mappings.sort((a, b)=>specificity(b.from) - specificity(a.from));
73
+ return {
74
+ input: ({ url })=>rewritePath(url, input),
75
+ output: ({ url })=>rewritePath(url, output)
76
+ };
77
+ }
78
+ export { canonicaliseLocalisedRoutes, createLocalisedRouteRewrite };
@@ -102,6 +102,14 @@ const transformLocalisedRoute = (route, parentCanonicalPath, parentLocalisedPath
102
102
  const children = 'children' in route && route.children ? route.children.flatMap((child)=>transformLocalisedRoute(child, canonicalPath, routeLocalisedPaths, languages, localisedUrls)) : void 0;
103
103
  const baseRoute = {
104
104
  ...route,
105
+ ...!isFrameworkInternalRoutePath(canonicalPath) ? {
106
+ modernLocalisedRoute: {
107
+ id: route.id,
108
+ path: route.path,
109
+ canonicalPath,
110
+ paths: localisedUrlEntry
111
+ }
112
+ } : {},
105
113
  ...children ? {
106
114
  children
107
115
  } : {}
@@ -0,0 +1,13 @@
1
+ import "node:module";
2
+ import { splitUrlTarget } from "@modern-js/runtime-utils/url";
3
+ import { canonicalTargetPathname, localiseTargetPathname } from "./localisedUrls/index.mjs";
4
+ const buildLocalizedUrl = (target, language, languages, localisedUrls)=>{
5
+ const { pathname, search, hash } = splitUrlTarget(target);
6
+ return `${localiseTargetPathname(pathname, language, languages, localisedUrls)}${search}${hash}`;
7
+ };
8
+ const localizePath = (target, language, config)=>buildLocalizedUrl(target, language, config.languages, config.localisedUrls);
9
+ const canonicalPath = (target, config)=>{
10
+ const { pathname, search, hash } = splitUrlTarget(target);
11
+ return `${canonicalTargetPathname(pathname, config.languages, config.localisedUrls)}${search}${hash}`;
12
+ };
13
+ export { buildLocalizedUrl, canonicalPath, localizePath };