@bleedingdev/modern-js-plugin-i18n 3.5.0-ultramodern.100 → 3.5.0-ultramodern.102

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.
@@ -77,21 +77,20 @@ const createI18nRootWrapper = (options)=>(App)=>(props)=>{
77
77
  forceUpdate,
78
78
  synchronizeLanguage
79
79
  ]);
80
+ const I18nextProvider = getI18nextProvider();
81
+ const i18nextInstanceForProvider = (0, external_react_namespaceObject.useMemo)(()=>i18nInstance ? (0, instance_js_namespaceObject.getI18nextInstanceForProvider)(i18nInstance, lang) : void 0, [
82
+ i18nInstance,
83
+ lang
84
+ ]);
80
85
  const children = props.children;
81
86
  let appContent = App ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(App, {
82
87
  ...props,
83
88
  children: children
84
89
  }) : children;
85
- if (i18nInstance) {
86
- const I18nextProvider = getI18nextProvider();
87
- if (I18nextProvider) {
88
- const i18nextInstanceForProvider = (0, instance_js_namespaceObject.getI18nextInstanceForProvider)(i18nInstance, lang);
89
- appContent = /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(I18nextProvider, {
90
- i18n: i18nextInstanceForProvider,
91
- children: appContent
92
- });
93
- }
94
- }
90
+ if (I18nextProvider && i18nextInstanceForProvider) appContent = /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(I18nextProvider, {
91
+ i18n: i18nextInstanceForProvider,
92
+ children: appContent
93
+ });
95
94
  return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(jsx_runtime_namespaceObject.Fragment, {
96
95
  children: [
97
96
  Boolean(htmlLangAttr) && /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(head_namespaceObject.Helmet, {
@@ -82,6 +82,12 @@ const getRouterParams = (internalContext, contextRouter)=>{
82
82
  return params;
83
83
  }, {});
84
84
  };
85
+ const getRouterSnapshot = (internalContext, contextRouter)=>{
86
+ const location = getRouterStateLocation(internalContext, contextRouter);
87
+ const params = getRouterParams(internalContext, contextRouter);
88
+ const serializedParams = Object.entries(params).sort(([left], [right])=>left.localeCompare(right)).map(([key, value])=>`${key}=${value}`).join('&');
89
+ return `${location?.pathname ?? ''}\u0000${location?.search ?? ''}\u0000${location?.hash ?? ''}\u0000${serializedParams}`;
90
+ };
85
91
  const useI18nRouterAdapter = ()=>{
86
92
  const runtimeContext = (0, external_react_namespaceObject.useContext)(runtime_namespaceObject.RuntimeContext);
87
93
  const internalContext = (0, external_react_namespaceObject.useContext)(context_namespaceObject.InternalRuntimeContext);
@@ -95,11 +101,18 @@ const useI18nRouterAdapter = ()=>{
95
101
  warn: false
96
102
  }) : null;
97
103
  const [, setRouterVersion] = (0, external_react_namespaceObject.useState)(0);
104
+ const routerSnapshotRef = (0, external_react_namespaceObject.useRef)(getRouterSnapshot(internalContext, contextRouter));
105
+ routerSnapshotRef.current = getRouterSnapshot(internalContext, contextRouter);
98
106
  const hasRouter = 'tanstack' === framework || 'react-router' === framework || Boolean(reactRouterNavigate);
99
107
  (0, external_react_namespaceObject.useEffect)(()=>{
100
108
  const router = getRouterInstance(internalContext, contextRouter);
101
109
  if (!router) return;
102
- const update = ()=>setRouterVersion((version)=>version + 1);
110
+ const update = ()=>{
111
+ const nextSnapshot = getRouterSnapshot(internalContext, contextRouter);
112
+ if (nextSnapshot === routerSnapshotRef.current) return;
113
+ routerSnapshotRef.current = nextSnapshot;
114
+ setRouterVersion((version)=>version + 1);
115
+ };
103
116
  const unsubscribers = [];
104
117
  if ('react-router' === framework && !inReactRouter && 'function' == typeof router.subscribe) {
105
118
  const subscribe = router.subscribe;
@@ -45,21 +45,20 @@ const createI18nRootWrapper = (options)=>(App)=>(props)=>{
45
45
  forceUpdate,
46
46
  synchronizeLanguage
47
47
  ]);
48
+ const I18nextProvider = getI18nextProvider();
49
+ const i18nextInstanceForProvider = useMemo(()=>i18nInstance ? getI18nextInstanceForProvider(i18nInstance, lang) : void 0, [
50
+ i18nInstance,
51
+ lang
52
+ ]);
48
53
  const children = props.children;
49
54
  let appContent = App ? /*#__PURE__*/ jsx(App, {
50
55
  ...props,
51
56
  children: children
52
57
  }) : children;
53
- if (i18nInstance) {
54
- const I18nextProvider = getI18nextProvider();
55
- if (I18nextProvider) {
56
- const i18nextInstanceForProvider = getI18nextInstanceForProvider(i18nInstance, lang);
57
- appContent = /*#__PURE__*/ jsx(I18nextProvider, {
58
- i18n: i18nextInstanceForProvider,
59
- children: appContent
60
- });
61
- }
62
- }
58
+ if (I18nextProvider && i18nextInstanceForProvider) appContent = /*#__PURE__*/ jsx(I18nextProvider, {
59
+ i18n: i18nextInstanceForProvider,
60
+ children: appContent
61
+ });
63
62
  return /*#__PURE__*/ jsxs(Fragment, {
64
63
  children: [
65
64
  Boolean(htmlLangAttr) && /*#__PURE__*/ jsx(Helmet, {
@@ -1,7 +1,7 @@
1
1
  import { RuntimeContext, isBrowser } from "@modern-js/runtime";
2
2
  import { InternalRuntimeContext, getRouterRuntimeState } from "@modern-js/runtime/context";
3
3
  import { Link as router_Link, useInRouterContext, useLocation, useNavigate, useParams } from "@modern-js/runtime/router";
4
- import { useCallback, useContext, useEffect, useState } from "react";
4
+ import { useCallback, useContext, useEffect, useRef, useState } from "react";
5
5
  const normalizeUrlPart = (value, prefix)=>{
6
6
  if ('string' != typeof value || !value) return '';
7
7
  return value.startsWith(prefix) ? value : `${prefix}${value}`;
@@ -50,6 +50,12 @@ const getRouterParams = (internalContext, contextRouter)=>{
50
50
  return params;
51
51
  }, {});
52
52
  };
53
+ const getRouterSnapshot = (internalContext, contextRouter)=>{
54
+ const location = getRouterStateLocation(internalContext, contextRouter);
55
+ const params = getRouterParams(internalContext, contextRouter);
56
+ const serializedParams = Object.entries(params).sort(([left], [right])=>left.localeCompare(right)).map(([key, value])=>`${key}=${value}`).join('&');
57
+ return `${location?.pathname ?? ''}\u0000${location?.search ?? ''}\u0000${location?.hash ?? ''}\u0000${serializedParams}`;
58
+ };
53
59
  const useI18nRouterAdapter = ()=>{
54
60
  const runtimeContext = useContext(RuntimeContext);
55
61
  const internalContext = useContext(InternalRuntimeContext);
@@ -63,11 +69,18 @@ const useI18nRouterAdapter = ()=>{
63
69
  warn: false
64
70
  }) : null;
65
71
  const [, setRouterVersion] = useState(0);
72
+ const routerSnapshotRef = useRef(getRouterSnapshot(internalContext, contextRouter));
73
+ routerSnapshotRef.current = getRouterSnapshot(internalContext, contextRouter);
66
74
  const hasRouter = 'tanstack' === framework || 'react-router' === framework || Boolean(reactRouterNavigate);
67
75
  useEffect(()=>{
68
76
  const router = getRouterInstance(internalContext, contextRouter);
69
77
  if (!router) return;
70
- const update = ()=>setRouterVersion((version)=>version + 1);
78
+ const update = ()=>{
79
+ const nextSnapshot = getRouterSnapshot(internalContext, contextRouter);
80
+ if (nextSnapshot === routerSnapshotRef.current) return;
81
+ routerSnapshotRef.current = nextSnapshot;
82
+ setRouterVersion((version)=>version + 1);
83
+ };
71
84
  const unsubscribers = [];
72
85
  if ('react-router' === framework && !inReactRouter && 'function' == typeof router.subscribe) {
73
86
  const subscribe = router.subscribe;
@@ -46,21 +46,20 @@ const createI18nRootWrapper = (options)=>(App)=>(props)=>{
46
46
  forceUpdate,
47
47
  synchronizeLanguage
48
48
  ]);
49
+ const I18nextProvider = getI18nextProvider();
50
+ const i18nextInstanceForProvider = useMemo(()=>i18nInstance ? getI18nextInstanceForProvider(i18nInstance, lang) : void 0, [
51
+ i18nInstance,
52
+ lang
53
+ ]);
49
54
  const children = props.children;
50
55
  let appContent = App ? /*#__PURE__*/ jsx(App, {
51
56
  ...props,
52
57
  children: children
53
58
  }) : children;
54
- if (i18nInstance) {
55
- const I18nextProvider = getI18nextProvider();
56
- if (I18nextProvider) {
57
- const i18nextInstanceForProvider = getI18nextInstanceForProvider(i18nInstance, lang);
58
- appContent = /*#__PURE__*/ jsx(I18nextProvider, {
59
- i18n: i18nextInstanceForProvider,
60
- children: appContent
61
- });
62
- }
63
- }
59
+ if (I18nextProvider && i18nextInstanceForProvider) appContent = /*#__PURE__*/ jsx(I18nextProvider, {
60
+ i18n: i18nextInstanceForProvider,
61
+ children: appContent
62
+ });
64
63
  return /*#__PURE__*/ jsxs(Fragment, {
65
64
  children: [
66
65
  Boolean(htmlLangAttr) && /*#__PURE__*/ jsx(Helmet, {
@@ -2,7 +2,7 @@ import "node:module";
2
2
  import { RuntimeContext, isBrowser } from "@modern-js/runtime";
3
3
  import { InternalRuntimeContext, getRouterRuntimeState } from "@modern-js/runtime/context";
4
4
  import { Link as router_Link, useInRouterContext, useLocation, useNavigate, useParams } from "@modern-js/runtime/router";
5
- import { useCallback, useContext, useEffect, useState } from "react";
5
+ import { useCallback, useContext, useEffect, useRef, useState } from "react";
6
6
  const normalizeUrlPart = (value, prefix)=>{
7
7
  if ('string' != typeof value || !value) return '';
8
8
  return value.startsWith(prefix) ? value : `${prefix}${value}`;
@@ -51,6 +51,12 @@ const getRouterParams = (internalContext, contextRouter)=>{
51
51
  return params;
52
52
  }, {});
53
53
  };
54
+ const getRouterSnapshot = (internalContext, contextRouter)=>{
55
+ const location = getRouterStateLocation(internalContext, contextRouter);
56
+ const params = getRouterParams(internalContext, contextRouter);
57
+ const serializedParams = Object.entries(params).sort(([left], [right])=>left.localeCompare(right)).map(([key, value])=>`${key}=${value}`).join('&');
58
+ return `${location?.pathname ?? ''}\u0000${location?.search ?? ''}\u0000${location?.hash ?? ''}\u0000${serializedParams}`;
59
+ };
54
60
  const useI18nRouterAdapter = ()=>{
55
61
  const runtimeContext = useContext(RuntimeContext);
56
62
  const internalContext = useContext(InternalRuntimeContext);
@@ -64,11 +70,18 @@ const useI18nRouterAdapter = ()=>{
64
70
  warn: false
65
71
  }) : null;
66
72
  const [, setRouterVersion] = useState(0);
73
+ const routerSnapshotRef = useRef(getRouterSnapshot(internalContext, contextRouter));
74
+ routerSnapshotRef.current = getRouterSnapshot(internalContext, contextRouter);
67
75
  const hasRouter = 'tanstack' === framework || 'react-router' === framework || Boolean(reactRouterNavigate);
68
76
  useEffect(()=>{
69
77
  const router = getRouterInstance(internalContext, contextRouter);
70
78
  if (!router) return;
71
- const update = ()=>setRouterVersion((version)=>version + 1);
79
+ const update = ()=>{
80
+ const nextSnapshot = getRouterSnapshot(internalContext, contextRouter);
81
+ if (nextSnapshot === routerSnapshotRef.current) return;
82
+ routerSnapshotRef.current = nextSnapshot;
83
+ setRouterVersion((version)=>version + 1);
84
+ };
72
85
  const unsubscribers = [];
73
86
  if ('react-router' === framework && !inReactRouter && 'function' == typeof router.subscribe) {
74
87
  const subscribe = router.subscribe;
package/package.json CHANGED
@@ -17,7 +17,7 @@
17
17
  "modern",
18
18
  "modern.js"
19
19
  ],
20
- "version": "3.5.0-ultramodern.100",
20
+ "version": "3.5.0-ultramodern.102",
21
21
  "engines": {
22
22
  "node": ">=20"
23
23
  },
@@ -91,12 +91,12 @@
91
91
  }
92
92
  },
93
93
  "dependencies": {
94
- "@modern-js/plugin": "npm:@bleedingdev/modern-js-plugin@3.5.0-ultramodern.100",
95
- "@modern-js/runtime-utils": "npm:@bleedingdev/modern-js-runtime-utils@3.5.0-ultramodern.100",
96
- "@modern-js/server-core": "npm:@bleedingdev/modern-js-server-core@3.5.0-ultramodern.100",
97
- "@modern-js/server-runtime": "npm:@bleedingdev/modern-js-server-runtime@3.5.0-ultramodern.100",
98
- "@modern-js/types": "npm:@bleedingdev/modern-js-types@3.5.0-ultramodern.100",
99
- "@modern-js/utils": "npm:@bleedingdev/modern-js-utils@3.5.0-ultramodern.100",
94
+ "@modern-js/plugin": "npm:@bleedingdev/modern-js-plugin@3.5.0-ultramodern.102",
95
+ "@modern-js/runtime-utils": "npm:@bleedingdev/modern-js-runtime-utils@3.5.0-ultramodern.102",
96
+ "@modern-js/server-core": "npm:@bleedingdev/modern-js-server-core@3.5.0-ultramodern.102",
97
+ "@modern-js/server-runtime": "npm:@bleedingdev/modern-js-server-runtime@3.5.0-ultramodern.102",
98
+ "@modern-js/types": "npm:@bleedingdev/modern-js-types@3.5.0-ultramodern.102",
99
+ "@modern-js/utils": "npm:@bleedingdev/modern-js-utils@3.5.0-ultramodern.102",
100
100
  "@swc/helpers": "^0.5.23",
101
101
  "i18next-browser-languagedetector": "^8.2.1",
102
102
  "i18next-chained-backend": "^5.0.5",
@@ -105,7 +105,7 @@
105
105
  "i18next-http-middleware": "^3.9.7"
106
106
  },
107
107
  "peerDependencies": {
108
- "@modern-js/runtime": "3.5.0-ultramodern.100",
108
+ "@modern-js/runtime": "3.5.0-ultramodern.102",
109
109
  "i18next": ">=26.3.1",
110
110
  "react": "^19.2.7",
111
111
  "react-dom": "^19.2.7",
@@ -120,11 +120,12 @@
120
120
  }
121
121
  },
122
122
  "devDependencies": {
123
- "@modern-js/app-tools": "npm:@bleedingdev/modern-js-app-tools@3.5.0-ultramodern.100",
124
- "@modern-js/runtime": "npm:@bleedingdev/modern-js-runtime@3.5.0-ultramodern.100",
123
+ "@modern-js/app-tools": "npm:@bleedingdev/modern-js-app-tools@3.5.0-ultramodern.102",
124
+ "@modern-js/runtime": "npm:@bleedingdev/modern-js-runtime@3.5.0-ultramodern.102",
125
125
  "@rslib/core": "0.23.2",
126
126
  "@types/node": "^26.1.1",
127
127
  "@typescript/native-preview": "7.0.0-dev.20260707.2",
128
+ "esbuild": "^0.28.1",
128
129
  "i18next": "26.3.6",
129
130
  "react": "^19.2.7",
130
131
  "react-dom": "^19.2.7",
@@ -113,6 +113,14 @@ export const createI18nRootWrapper =
113
113
  synchronizeLanguage,
114
114
  ],
115
115
  );
116
+ const I18nextProvider = getI18nextProvider();
117
+ const i18nextInstanceForProvider = useMemo(
118
+ () =>
119
+ i18nInstance
120
+ ? getI18nextInstanceForProvider(i18nInstance, lang)
121
+ : undefined,
122
+ [i18nInstance, lang],
123
+ );
116
124
 
117
125
  const children = (props as React.PropsWithChildren).children;
118
126
  let appContent: React.ReactNode = App ? (
@@ -121,19 +129,12 @@ export const createI18nRootWrapper =
121
129
  children
122
130
  );
123
131
 
124
- if (i18nInstance) {
125
- const I18nextProvider = getI18nextProvider();
126
- if (I18nextProvider) {
127
- const i18nextInstanceForProvider = getI18nextInstanceForProvider(
128
- i18nInstance,
129
- lang,
130
- );
131
- appContent = (
132
- <I18nextProvider i18n={i18nextInstanceForProvider}>
133
- {appContent}
134
- </I18nextProvider>
135
- );
136
- }
132
+ if (I18nextProvider && i18nextInstanceForProvider) {
133
+ appContent = (
134
+ <I18nextProvider i18n={i18nextInstanceForProvider}>
135
+ {appContent}
136
+ </I18nextProvider>
137
+ );
137
138
  }
138
139
 
139
140
  return (
@@ -13,7 +13,7 @@ import {
13
13
  useParams as useReactRouterParams,
14
14
  } from '@modern-js/runtime/router';
15
15
  import type React from 'react';
16
- import { useCallback, useContext, useEffect, useState } from 'react';
16
+ import { useCallback, useContext, useEffect, useRef, useState } from 'react';
17
17
 
18
18
  type I18nRouterFramework = 'react-router' | 'tanstack' | string;
19
19
 
@@ -205,6 +205,21 @@ const getRouterParams = (
205
205
  }, {});
206
206
  };
207
207
 
208
+ const getRouterSnapshot = (
209
+ internalContext: InternalRuntimeContextWithRouter,
210
+ contextRouter?: RouterInstance | null,
211
+ ) => {
212
+ const location = getRouterStateLocation(internalContext, contextRouter);
213
+ const params = getRouterParams(internalContext, contextRouter);
214
+ const serializedParams = Object.entries(params)
215
+ .sort(([left], [right]) => left.localeCompare(right))
216
+ .map(([key, value]) => `${key}=${value}`)
217
+ .join('&');
218
+ return `${location?.pathname ?? ''}\u0000${location?.search ?? ''}\u0000${
219
+ location?.hash ?? ''
220
+ }\u0000${serializedParams}`;
221
+ };
222
+
208
223
  export const useI18nRouterAdapter = (): I18nRouterAdapter => {
209
224
  const runtimeContext = useContext(RuntimeContext) as RuntimeContextWithRouter;
210
225
  const internalContext = useContext(
@@ -227,6 +242,10 @@ export const useI18nRouterAdapter = (): I18nRouterAdapter => {
227
242
  ? (contextUseRouter({ warn: false }) as RouterInstance | null)
228
243
  : null;
229
244
  const [, setRouterVersion] = useState(0);
245
+ const routerSnapshotRef = useRef(
246
+ getRouterSnapshot(internalContext, contextRouter),
247
+ );
248
+ routerSnapshotRef.current = getRouterSnapshot(internalContext, contextRouter);
230
249
  const hasRouter =
231
250
  framework === 'tanstack' ||
232
251
  framework === 'react-router' ||
@@ -238,7 +257,14 @@ export const useI18nRouterAdapter = (): I18nRouterAdapter => {
238
257
  return;
239
258
  }
240
259
 
241
- const update = () => setRouterVersion(version => version + 1);
260
+ const update = () => {
261
+ const nextSnapshot = getRouterSnapshot(internalContext, contextRouter);
262
+ if (nextSnapshot === routerSnapshotRef.current) {
263
+ return;
264
+ }
265
+ routerSnapshotRef.current = nextSnapshot;
266
+ setRouterVersion(version => version + 1);
267
+ };
242
268
  const unsubscribers: Array<() => void> = [];
243
269
 
244
270
  if (
@@ -1,5 +1,3 @@
1
- import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
- import path from 'node:path';
3
1
  import type { NestedRouteForCli } from '@modern-js/types';
4
2
  import { describe, expect, test } from '@rstest/core';
5
3
  import { i18nPlugin as i18nCliPlugin } from '../src/cli';
@@ -19,12 +17,6 @@ import {
19
17
  validateLocalisedUrls,
20
18
  } from '../src/shared/localisedUrls';
21
19
 
22
- const localisedRoutesGoldenPath = path.join(
23
- __dirname,
24
- 'fixtures',
25
- 'localised-routes.golden.json',
26
- );
27
-
28
20
  const createRoute = (
29
21
  path: string,
30
22
  children?: NestedRouteForCli[],
@@ -45,9 +37,6 @@ const createRequestContext = (pathname: string) =>
45
37
  },
46
38
  }) as any;
47
39
 
48
- const serializeRoutesForGolden = (routes: unknown): string =>
49
- `${JSON.stringify(routes, null, 2)}\n`;
50
-
51
40
  describe('resolveLocalisedUrlsConfig', () => {
52
41
  test('is opt-in: only a non-empty map enables the feature', () => {
53
42
  const map = { '/about': { en: '/about', cs: '/o-nas' } };
@@ -119,7 +108,7 @@ describe('cli modifyFileSystemRoutes', () => {
119
108
  return modifyRoutes!;
120
109
  };
121
110
 
122
- const generateLocalisedRoutesGolden = (): string => {
111
+ const generateLocalisedRoutes = () => {
123
112
  const modifyRoutes = setupModifyRoutes({
124
113
  localePathRedirect: true,
125
114
  languages: ['en', 'cs', 'de'],
@@ -164,23 +153,53 @@ describe('cli modifyFileSystemRoutes', () => {
164
153
  routes,
165
154
  });
166
155
 
167
- return serializeRoutesForGolden(result.routes);
156
+ return result.routes;
168
157
  };
169
158
 
170
- test('matches checked-in localised routes golden output', async () => {
171
- const localisedRoutes = generateLocalisedRoutesGolden();
172
- const repeatedLocalisedRoutes = generateLocalisedRoutesGolden();
159
+ test('creates deterministic localized aliases with canonical route identity', () => {
160
+ const localisedRoutes = generateLocalisedRoutes();
161
+ expect(generateLocalisedRoutes()).toEqual(localisedRoutes);
173
162
 
174
- expect(repeatedLocalisedRoutes).toBe(localisedRoutes);
175
-
176
- if (process.env.UPDATE_I18N_LOCALISED_ROUTES_GOLDEN === '1') {
177
- await mkdir(path.dirname(localisedRoutesGoldenPath), { recursive: true });
178
- await writeFile(localisedRoutesGoldenPath, localisedRoutes);
163
+ const [localeLayout] = localisedRoutes;
164
+ expect(localeLayout.children?.map(route => route.path)).toEqual([
165
+ 'about',
166
+ 'o-nas',
167
+ 'ueber-uns',
168
+ 'products',
169
+ 'produkty',
170
+ 'produkte',
171
+ 'docs',
172
+ 'dokumenty',
173
+ 'dokumente',
174
+ ]);
175
+ expect(localeLayout.children?.slice(0, 3)).toMatchObject([
176
+ {
177
+ _component: 'about.tsx',
178
+ modernCanonicalPath: '/about',
179
+ path: 'about',
180
+ },
181
+ {
182
+ _component: 'about.tsx',
183
+ modernCanonicalPath: '/about',
184
+ path: 'o-nas',
185
+ },
186
+ {
187
+ _component: 'about.tsx',
188
+ modernCanonicalPath: '/about',
189
+ path: 'ueber-uns',
190
+ },
191
+ ]);
192
+ for (const productRoute of localeLayout.children?.slice(3, 6) ?? []) {
193
+ expect(productRoute).toMatchObject({
194
+ _component: 'products.tsx',
195
+ modernCanonicalPath: '/products',
196
+ });
197
+ expect(productRoute.children?.[0]).toMatchObject({
198
+ _component: ':slug.tsx',
199
+ modernCanonicalPath: '/products/:slug',
200
+ path: ':slug',
201
+ });
179
202
  }
180
-
181
- await expect(readFile(localisedRoutesGoldenPath, 'utf8')).resolves.toBe(
182
- localisedRoutes,
183
- );
184
203
  });
185
204
 
186
205
  test('upstream-style configs without a map keep routes untouched', () => {
@@ -1,48 +1,170 @@
1
- import { readFileSync } from 'node:fs';
2
- import { dirname, resolve } from 'node:path';
3
- import { fileURLToPath } from 'node:url';
1
+ import { mkdtemp, rm } from 'node:fs/promises';
2
+ import { tmpdir } from 'node:os';
3
+ import { basename, resolve } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
4
5
  import { describe, expect, test } from '@rstest/core';
6
+ import { build } from 'esbuild';
7
+ import i18next from 'i18next';
8
+ import { createElement } from 'react';
9
+ import { renderToStaticMarkup } from 'react-dom/server';
10
+ import { i18nPlugin as noReactI18nextPlugin } from '../src/runtime/no-react-i18next';
5
11
 
6
- const __dirname = dirname(fileURLToPath(import.meta.url));
7
12
  const runtimeRoot = resolve(__dirname, '../src/runtime');
8
13
 
9
- const readRuntimeSource = (file: string) =>
10
- readFileSync(resolve(runtimeRoot, file), 'utf8').replace(/\r\n/gu, '\n');
11
-
12
14
  describe('react-i18next runtime boundary', () => {
13
- test('keeps the disabled runtime entry free of the optional adapter edge', () => {
14
- const noReactEntry = readRuntimeSource('no-react-i18next.tsx');
15
- const core = readRuntimeSource('core.tsx');
16
-
17
- expect(noReactEntry).not.toContain('./i18n/react-i18next');
18
- expect(core).not.toContain('./i18n/react-i18next');
19
- expect(core).not.toContain("import('react-i18next')");
15
+ test('bundles the disabled runtime entry when react-i18next is unavailable', async () => {
16
+ await expect(
17
+ build({
18
+ bundle: true,
19
+ entryPoints: [resolve(runtimeRoot, 'no-react-i18next.tsx')],
20
+ format: 'esm',
21
+ packages: 'external',
22
+ platform: 'node',
23
+ plugins: [
24
+ {
25
+ name: 'reject-react-i18next',
26
+ setup(buildApi) {
27
+ buildApi.onResolve({ filter: /^react-i18next$/ }, () => {
28
+ throw new Error(
29
+ 'disabled runtime entry reached optional react-i18next',
30
+ );
31
+ });
32
+ },
33
+ },
34
+ ],
35
+ write: false,
36
+ }),
37
+ ).resolves.toBeDefined();
20
38
  });
21
39
 
22
- test('keeps the runtime plugin factory entry synchronous for federation', () => {
23
- const core = readRuntimeSource('core.tsx');
24
- const pluginSetup = readRuntimeSource('pluginSetup.ts');
40
+ test('bundles the default runtime entry with the react-i18next adapter', async () => {
41
+ let adapterResolutions = 0;
42
+ await build({
43
+ bundle: true,
44
+ entryPoints: [resolve(runtimeRoot, 'index.tsx')],
45
+ format: 'esm',
46
+ packages: 'external',
47
+ platform: 'node',
48
+ plugins: [
49
+ {
50
+ name: 'observe-react-i18next',
51
+ setup(buildApi) {
52
+ buildApi.onResolve({ filter: /^react-i18next$/ }, args => {
53
+ adapterResolutions += 1;
54
+ return { external: true, path: args.path };
55
+ });
56
+ },
57
+ },
58
+ ],
59
+ write: false,
60
+ });
25
61
 
26
- expect(core).not.toContain("from './i18n/backend/middleware'");
27
- expect(core).not.toContain("from './i18n/utils'");
28
- expect(pluginSetup).not.toContain("from './i18n/backend/middleware'");
29
- expect(pluginSetup).not.toContain("from './i18n/utils'");
30
- expect(pluginSetup).toContain("import('./i18n/backend/middleware')");
31
- expect(pluginSetup).toContain("import('./i18n/utils')");
62
+ expect(adapterResolutions).toBeGreaterThan(0);
32
63
  });
33
64
 
34
- test('keeps the Modern i18n context stable across federated runtime copies', () => {
35
- const context = readRuntimeSource('context.tsx');
65
+ test('keeps expensive lifecycle helpers behind asynchronous bundle edges', async () => {
66
+ const result = await build({
67
+ bundle: true,
68
+ entryPoints: [resolve(runtimeRoot, 'pluginSetup.ts')],
69
+ format: 'esm',
70
+ metafile: true,
71
+ outdir: 'out',
72
+ packages: 'external',
73
+ platform: 'node',
74
+ splitting: true,
75
+ write: false,
76
+ });
77
+
78
+ const entryOutput = Object.values(result.metafile.outputs).find(output =>
79
+ output.entryPoint?.endsWith('/pluginSetup.ts'),
80
+ );
81
+ if (!entryOutput) {
82
+ throw new Error('pluginSetup entry output was not generated');
83
+ }
84
+ const dynamicOutputNames = entryOutput.imports
85
+ .filter(moduleImport => moduleImport.kind === 'dynamic-import')
86
+ .map(moduleImport => basename(moduleImport.path));
87
+ const dynamicOutputs = Object.entries(result.metafile.outputs)
88
+ .filter(([outputPath]) =>
89
+ dynamicOutputNames.includes(basename(outputPath)),
90
+ )
91
+ .map(([, output]) => output);
92
+ const dynamicEntries = dynamicOutputs.map(output =>
93
+ basename(output.entryPoint ?? ''),
94
+ );
36
95
 
37
- expect(context).toContain(
38
- "Symbol.for(\n '@modern-js/plugin-i18n/runtime/ModernI18nContext'",
96
+ expect(dynamicEntries).toEqual(
97
+ expect.arrayContaining(['middleware.ts', 'utils.ts']),
39
98
  );
40
- expect(context).toContain('globalStore[modernI18nContextKey] ??=');
41
99
  });
42
100
 
43
- test('keeps the default runtime entry wired to react-i18next integration', () => {
44
- const defaultEntry = readRuntimeSource('index.tsx');
101
+ test('registers plugin lifecycle hooks synchronously', () => {
102
+ let beforeRender: unknown;
103
+ let rootWrapper: unknown;
104
+ const plugin = noReactI18nextPlugin({ reactI18next: false });
105
+ const setupResult = plugin.setup?.({
106
+ getRuntimeConfig: () => ({}),
107
+ onBeforeRender: hook => {
108
+ beforeRender = hook;
109
+ },
110
+ wrapRoot: wrapper => {
111
+ rootWrapper = wrapper;
112
+ },
113
+ } as any);
114
+
115
+ expect(setupResult).toBeUndefined();
116
+ expect(typeof beforeRender).toBe('function');
117
+ expect(typeof rootWrapper).toBe('function');
118
+ });
119
+
120
+ test('shares Modern i18n context across independently bundled runtime copies', async () => {
121
+ const tempDir = await mkdtemp(
122
+ resolve(__dirname, '.modern-i18n-runtime-boundary-'),
123
+ );
124
+ try {
125
+ const contextEntry = resolve(runtimeRoot, 'context.tsx');
126
+ const copies = await Promise.all(
127
+ ['copy-a.mjs', 'copy-b.mjs'].map(async filename => {
128
+ const outfile = resolve(tempDir, filename);
129
+ await build({
130
+ bundle: true,
131
+ entryPoints: [contextEntry],
132
+ format: 'esm',
133
+ jsx: 'automatic',
134
+ outfile,
135
+ packages: 'external',
136
+ platform: 'node',
137
+ });
138
+ return import(pathToFileURL(outfile).href);
139
+ }),
140
+ );
141
+ const [copyA, copyB] = copies;
142
+ const instance = i18next.createInstance();
143
+ await instance.init({
144
+ initImmediate: false,
145
+ lng: 'cs',
146
+ resources: { cs: { translation: { language: 'Jazyk' } } },
147
+ });
148
+ const Consumer = () =>
149
+ createElement('span', null, copyB.useModernI18n().language);
150
+
151
+ const html = renderToStaticMarkup(
152
+ createElement(
153
+ copyA.ModernI18nProvider,
154
+ {
155
+ value: {
156
+ i18nInstance: instance,
157
+ language: 'cs',
158
+ languages: ['en', 'cs'],
159
+ },
160
+ },
161
+ createElement(Consumer),
162
+ ),
163
+ );
45
164
 
46
- expect(defaultEntry).toContain('./i18n/react-i18next');
165
+ expect(html).toBe('<span>cs</span>');
166
+ } finally {
167
+ await rm(tempDir, { force: true, recursive: true });
168
+ }
47
169
  });
48
170
  });
@@ -20,6 +20,7 @@ import { I18nLink } from '../src/runtime/I18nLink';
20
20
  import type { I18nInstance } from '../src/runtime/i18n';
21
21
  import { getReactI18nextIntegration } from '../src/runtime/i18n/react-i18next';
22
22
  import { createI18nRootWrapper } from '../src/runtime/providerComposition';
23
+ import { useI18nRouterAdapter } from '../src/runtime/routerAdapter';
23
24
 
24
25
  (
25
26
  globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
@@ -244,6 +245,11 @@ function createMutableTanstackRouter(pathname = '/en') {
244
245
  listener();
245
246
  }
246
247
  },
248
+ publishStateUpdate() {
249
+ for (const listener of listeners) {
250
+ listener();
251
+ }
252
+ },
247
253
  };
248
254
  }
249
255
 
@@ -459,6 +465,53 @@ describe('i18n runtime wrapRoot', () => {
459
465
  expect(rendered.container.textContent).toContain('router content');
460
466
  });
461
467
 
468
+ test('keeps the i18next provider instance stable across unrelated parent renders', async () => {
469
+ const i18nInstance = createI18nInstance('cs');
470
+ const providerInstances: I18nInstance[] = [];
471
+ const I18nextProvider = ({
472
+ children,
473
+ i18n,
474
+ }: PropsWithChildren<{ i18n: I18nInstance }>) => {
475
+ providerInstances.push(i18n);
476
+ return <>{children}</>;
477
+ };
478
+ const App = () => <main>router content</main>;
479
+ const I18nRoot = createI18nRootWrapper({
480
+ htmlLangAttr: false,
481
+ localePathRedirect: false,
482
+ languages: ['en', 'cs'],
483
+ fallbackLanguage: 'en',
484
+ getLatestI18nInstance: () => i18nInstance,
485
+ getI18nextProvider: () => I18nextProvider,
486
+ })(App);
487
+ const Parent = () => {
488
+ const [renderVersion, setRenderVersion] = useState(0);
489
+ return (
490
+ <>
491
+ <button
492
+ type="button"
493
+ onClick={() => setRenderVersion(version => version + 1)}
494
+ >
495
+ Render {renderVersion}
496
+ </button>
497
+ <I18nRoot renderVersion={renderVersion} />
498
+ </>
499
+ );
500
+ };
501
+
502
+ rendered = await renderI18nRoot(<Parent />);
503
+ const initialProviderInstance = providerInstances.at(-1);
504
+
505
+ await act(async () => {
506
+ rendered?.container
507
+ .querySelector('button')
508
+ ?.dispatchEvent(new MouseEvent('click', { bubbles: true }));
509
+ });
510
+
511
+ expect(providerInstances.length).toBeGreaterThan(1);
512
+ expect(providerInstances.at(-1)).toBe(initialProviderInstance);
513
+ });
514
+
462
515
  test('commits route language and translated copy after the instance changes', async () => {
463
516
  window.history.replaceState(null, '', '/en');
464
517
  const router = createMutableTanstackRouter();
@@ -762,6 +815,34 @@ describe('i18n router adapter', () => {
762
815
  expect(link?.getAttribute('data-router-link')).toBe('tanstack');
763
816
  });
764
817
 
818
+ test('ignores router state updates that do not change location or params', async () => {
819
+ const router = createMutableTanstackRouter('/en');
820
+ let renders = 0;
821
+ const LocationProbe = () => {
822
+ renders += 1;
823
+ const { location } = useI18nRouterAdapter();
824
+ return <output>{location?.pathname}</output>;
825
+ };
826
+
827
+ rendered = await renderWithRuntime(
828
+ <LocationProbe />,
829
+ createTanstackRuntimeContext(router),
830
+ );
831
+ const initialRenders = renders;
832
+
833
+ await act(async () => {
834
+ router.publishStateUpdate();
835
+ });
836
+ expect(renders).toBe(initialRenders);
837
+ expect(rendered.container.textContent).toBe('/en');
838
+
839
+ await act(async () => {
840
+ router.publishPathname('/cs');
841
+ });
842
+ expect(renders).toBe(initialRenders + 1);
843
+ expect(rendered.container.textContent).toBe('/cs');
844
+ });
845
+
765
846
  test('forwards warmup props through I18nLink with a localized string target', async () => {
766
847
  const router = createTanstackRouter('/cs/podminky-pouzivani', 'cs');
767
848
  rendered = await renderWithRuntime(
@@ -1,156 +0,0 @@
1
- [
2
- {
3
- "id": ":lang",
4
- "path": ":lang",
5
- "type": "nested",
6
- "origin": "file-system",
7
- "routeType": "layout",
8
- "_component": ":lang.tsx",
9
- "children": [
10
- {
11
- "id": "about",
12
- "path": "about",
13
- "type": "nested",
14
- "origin": "file-system",
15
- "routeType": "page",
16
- "_component": "about.tsx",
17
- "modernCanonicalPath": "/about"
18
- },
19
- {
20
- "id": "about__localised_o-nas",
21
- "path": "o-nas",
22
- "type": "nested",
23
- "origin": "file-system",
24
- "routeType": "page",
25
- "_component": "about.tsx",
26
- "modernCanonicalPath": "/about"
27
- },
28
- {
29
- "id": "about__localised_ueber-uns",
30
- "path": "ueber-uns",
31
- "type": "nested",
32
- "origin": "file-system",
33
- "routeType": "page",
34
- "_component": "about.tsx",
35
- "modernCanonicalPath": "/about"
36
- },
37
- {
38
- "id": "products",
39
- "path": "products",
40
- "type": "nested",
41
- "origin": "file-system",
42
- "routeType": "layout",
43
- "_component": "products.tsx",
44
- "children": [
45
- {
46
- "id": ":slug",
47
- "path": ":slug",
48
- "type": "nested",
49
- "origin": "file-system",
50
- "routeType": "page",
51
- "_component": ":slug.tsx",
52
- "modernCanonicalPath": "/products/:slug"
53
- }
54
- ],
55
- "modernCanonicalPath": "/products"
56
- },
57
- {
58
- "id": "products__localised_produkty",
59
- "path": "produkty",
60
- "type": "nested",
61
- "origin": "file-system",
62
- "routeType": "layout",
63
- "_component": "products.tsx",
64
- "children": [
65
- {
66
- "id": ":slug__localised_produkty",
67
- "path": ":slug",
68
- "type": "nested",
69
- "origin": "file-system",
70
- "routeType": "page",
71
- "_component": ":slug.tsx",
72
- "modernCanonicalPath": "/products/:slug"
73
- }
74
- ],
75
- "modernCanonicalPath": "/products"
76
- },
77
- {
78
- "id": "products__localised_produkte",
79
- "path": "produkte",
80
- "type": "nested",
81
- "origin": "file-system",
82
- "routeType": "layout",
83
- "_component": "products.tsx",
84
- "children": [
85
- {
86
- "id": ":slug__localised_produkte",
87
- "path": ":slug",
88
- "type": "nested",
89
- "origin": "file-system",
90
- "routeType": "page",
91
- "_component": ":slug.tsx",
92
- "modernCanonicalPath": "/products/:slug"
93
- }
94
- ],
95
- "modernCanonicalPath": "/products"
96
- },
97
- {
98
- "id": "docs",
99
- "path": "docs",
100
- "type": "nested",
101
- "origin": "file-system",
102
- "routeType": "layout",
103
- "_component": "docs.tsx",
104
- "children": [
105
- {
106
- "id": "*",
107
- "path": "*",
108
- "type": "nested",
109
- "origin": "file-system",
110
- "routeType": "page",
111
- "_component": "*.tsx"
112
- }
113
- ],
114
- "modernCanonicalPath": "/docs"
115
- },
116
- {
117
- "id": "docs__localised_dokumenty",
118
- "path": "dokumenty",
119
- "type": "nested",
120
- "origin": "file-system",
121
- "routeType": "layout",
122
- "_component": "docs.tsx",
123
- "children": [
124
- {
125
- "id": "*__localised_dokumenty",
126
- "path": "*",
127
- "type": "nested",
128
- "origin": "file-system",
129
- "routeType": "page",
130
- "_component": "*.tsx"
131
- }
132
- ],
133
- "modernCanonicalPath": "/docs"
134
- },
135
- {
136
- "id": "docs__localised_dokumente",
137
- "path": "dokumente",
138
- "type": "nested",
139
- "origin": "file-system",
140
- "routeType": "layout",
141
- "_component": "docs.tsx",
142
- "children": [
143
- {
144
- "id": "*__localised_dokumente",
145
- "path": "*",
146
- "type": "nested",
147
- "origin": "file-system",
148
- "routeType": "page",
149
- "_component": "*.tsx"
150
- }
151
- ],
152
- "modernCanonicalPath": "/docs"
153
- }
154
- ]
155
- }
156
- ]