@bleedingdev/modern-js-plugin-i18n 3.2.0-ultramodern.119 → 3.2.0-ultramodern.120

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 (42) hide show
  1. package/README.md +221 -11
  2. package/dist/cjs/runtime/I18nLink.js +7 -17
  3. package/dist/cjs/runtime/Link.js +252 -0
  4. package/dist/cjs/runtime/canonicalRoutes.js +18 -0
  5. package/dist/cjs/runtime/index.js +23 -0
  6. package/dist/cjs/runtime/localizedPaths.js +105 -0
  7. package/dist/cjs/runtime/utils.js +22 -5
  8. package/dist/cjs/shared/localisedUrls.js +32 -2
  9. package/dist/esm/runtime/I18nLink.mjs +6 -16
  10. package/dist/esm/runtime/Link.mjs +209 -0
  11. package/dist/esm/runtime/canonicalRoutes.mjs +0 -0
  12. package/dist/esm/runtime/index.mjs +4 -2
  13. package/dist/esm/runtime/localizedPaths.mjs +58 -0
  14. package/dist/esm/runtime/utils.mjs +18 -4
  15. package/dist/esm/shared/localisedUrls.mjs +24 -3
  16. package/dist/esm-node/runtime/I18nLink.mjs +6 -16
  17. package/dist/esm-node/runtime/Link.mjs +210 -0
  18. package/dist/esm-node/runtime/canonicalRoutes.mjs +1 -0
  19. package/dist/esm-node/runtime/index.mjs +4 -2
  20. package/dist/esm-node/runtime/localizedPaths.mjs +59 -0
  21. package/dist/esm-node/runtime/utils.mjs +18 -4
  22. package/dist/esm-node/shared/localisedUrls.mjs +24 -3
  23. package/dist/types/runtime/I18nLink.d.ts +4 -13
  24. package/dist/types/runtime/Link.d.ts +56 -0
  25. package/dist/types/runtime/canonicalRoutes.d.ts +60 -0
  26. package/dist/types/runtime/index.d.ts +5 -1
  27. package/dist/types/runtime/localizedPaths.d.ts +39 -0
  28. package/dist/types/runtime/utils.d.ts +12 -3
  29. package/dist/types/shared/localisedUrls.d.ts +8 -0
  30. package/package.json +13 -13
  31. package/rstest.config.mts +2 -2
  32. package/src/runtime/I18nLink.tsx +13 -46
  33. package/src/runtime/Link.tsx +414 -0
  34. package/src/runtime/canonicalRoutes.ts +93 -0
  35. package/src/runtime/index.tsx +24 -2
  36. package/src/runtime/localizedPaths.ts +118 -0
  37. package/src/runtime/utils.ts +24 -5
  38. package/src/shared/localisedUrls.ts +63 -3
  39. package/tests/link.test.tsx +475 -0
  40. package/tests/linkTypes.test.ts +28 -0
  41. package/tests/type-fixture/linkTypes.fixture.tsx +51 -0
  42. package/tests/type-fixture/tsconfig.json +15 -0
package/package.json CHANGED
@@ -17,7 +17,7 @@
17
17
  "modern",
18
18
  "modern.js"
19
19
  ],
20
- "version": "3.2.0-ultramodern.119",
20
+ "version": "3.2.0-ultramodern.120",
21
21
  "engines": {
22
22
  "node": ">=20"
23
23
  },
@@ -88,15 +88,15 @@
88
88
  "i18next-http-backend": "^4.0.0",
89
89
  "i18next-http-middleware": "^3.9.7",
90
90
  "react-i18next": "17.0.8",
91
- "@modern-js/plugin": "npm:@bleedingdev/modern-js-plugin@3.2.0-ultramodern.119",
92
- "@modern-js/server-core": "npm:@bleedingdev/modern-js-server-core@3.2.0-ultramodern.119",
93
- "@modern-js/runtime-utils": "npm:@bleedingdev/modern-js-runtime-utils@3.2.0-ultramodern.119",
94
- "@modern-js/server-runtime": "npm:@bleedingdev/modern-js-server-runtime@3.2.0-ultramodern.119",
95
- "@modern-js/types": "npm:@bleedingdev/modern-js-types@3.2.0-ultramodern.119",
96
- "@modern-js/utils": "npm:@bleedingdev/modern-js-utils@3.2.0-ultramodern.119"
91
+ "@modern-js/plugin": "npm:@bleedingdev/modern-js-plugin@3.2.0-ultramodern.120",
92
+ "@modern-js/server-runtime": "npm:@bleedingdev/modern-js-server-runtime@3.2.0-ultramodern.120",
93
+ "@modern-js/types": "npm:@bleedingdev/modern-js-types@3.2.0-ultramodern.120",
94
+ "@modern-js/server-core": "npm:@bleedingdev/modern-js-server-core@3.2.0-ultramodern.120",
95
+ "@modern-js/utils": "npm:@bleedingdev/modern-js-utils@3.2.0-ultramodern.120",
96
+ "@modern-js/runtime-utils": "npm:@bleedingdev/modern-js-runtime-utils@3.2.0-ultramodern.120"
97
97
  },
98
98
  "peerDependencies": {
99
- "@modern-js/runtime": "3.2.0-ultramodern.119",
99
+ "@modern-js/runtime": "3.2.0-ultramodern.120",
100
100
  "i18next": ">=25.7.4",
101
101
  "react": "^19.2.7",
102
102
  "react-dom": "^19.2.7"
@@ -107,17 +107,17 @@
107
107
  }
108
108
  },
109
109
  "devDependencies": {
110
- "@rslib/core": "0.21.5",
110
+ "@rslib/core": "0.22.0",
111
111
  "@types/jest": "^30.0.0",
112
- "@types/node": "^25.9.1",
113
- "@typescript/native-preview": "7.0.0-dev.20260606.1",
112
+ "@types/node": "^25.9.3",
113
+ "@typescript/native-preview": "7.0.0-dev.20260610.1",
114
114
  "i18next": "26.3.1",
115
115
  "jest": "^30.4.2",
116
116
  "react": "^19.2.7",
117
117
  "react-dom": "^19.2.7",
118
118
  "ts-jest": "^29.4.11",
119
- "@modern-js/app-tools": "npm:@bleedingdev/modern-js-app-tools@3.2.0-ultramodern.119",
120
- "@modern-js/runtime": "npm:@bleedingdev/modern-js-runtime@3.2.0-ultramodern.119"
119
+ "@modern-js/app-tools": "npm:@bleedingdev/modern-js-app-tools@3.2.0-ultramodern.120",
120
+ "@modern-js/runtime": "npm:@bleedingdev/modern-js-runtime@3.2.0-ultramodern.120"
121
121
  },
122
122
  "sideEffects": false,
123
123
  "publishConfig": {
package/rstest.config.mts CHANGED
@@ -26,13 +26,13 @@ export default {
26
26
  withTestPreset({
27
27
  name: 'plugin-i18n-node',
28
28
  testEnvironment: 'node',
29
- include: ['tests/localisedUrls.test.ts'],
29
+ include: ['tests/localisedUrls.test.ts', 'tests/linkTypes.test.ts'],
30
30
  extends: commonConfig,
31
31
  }),
32
32
  withTestPreset({
33
33
  name: 'plugin-i18n-client',
34
34
  testEnvironment: 'happy-dom',
35
- include: ['tests/routerAdapter.test.tsx'],
35
+ include: ['tests/routerAdapter.test.tsx', 'tests/link.test.tsx'],
36
36
  extends: commonConfig,
37
37
  }),
38
38
  ],
@@ -1,7 +1,5 @@
1
1
  import type React from 'react';
2
- import { useModernI18n } from './context';
3
- import { useI18nRouterAdapter } from './routerAdapter';
4
- import { buildLocalizedUrl } from './utils';
2
+ import { Link } from './Link';
5
3
 
6
4
  export interface I18nLinkProps {
7
5
  to: string;
@@ -9,61 +7,30 @@ export interface I18nLinkProps {
9
7
  [key: string]: any;
10
8
  }
11
9
 
10
+ let warnedDeprecation = false;
11
+
12
12
  /**
13
- * I18nLink component that automatically adds language prefix to navigation links.
14
- * This component should be used within a :lang dynamic route context.
15
- *
16
- * @example
17
- * ```tsx
18
- * // When current language is 'en' and to="/about"
19
- * // The actual link will be "/en/about"
20
- * <I18nLink to="/about">About</I18nLink>
21
- *
22
- * // When current language is 'zh' and to="/"
23
- * // The actual link will be "/zh"
24
- * <I18nLink to="/">Home</I18nLink>
25
- * ```
13
+ * @deprecated Use {@link Link} from `@modern-js/plugin-i18n/runtime` instead.
14
+ * `Link` accepts the same language-agnostic `to` values and additionally
15
+ * supports `#hash`/`?query` targets, typed canonical routes, `params`
16
+ * interpolation and language-invariant active state.
26
17
  */
27
18
  export const I18nLink: React.FC<I18nLinkProps> = ({
28
19
  to,
29
20
  children,
30
21
  ...props
31
22
  }) => {
32
- const { Link, params, hasRouter } = useI18nRouterAdapter();
33
- const { language, supportedLanguages, localisedUrls } = useModernI18n();
34
-
35
- // Get the current language from context (which reflects the actual current language)
36
- // URL params might be stale after language changes, so we prioritize the context language
37
- const currentLang = language;
38
-
39
- // Build the localized URL by adding language prefix
40
- const localizedTo = buildLocalizedUrl(
41
- to,
42
- currentLang,
43
- supportedLanguages,
44
- localisedUrls,
45
- );
46
-
47
- // In development mode, warn if used outside of :lang route context
48
- if (process.env.NODE_ENV === 'development' && hasRouter && !params.lang) {
23
+ if (process.env.NODE_ENV === 'development' && !warnedDeprecation) {
24
+ warnedDeprecation = true;
49
25
  console.warn(
50
- 'I18nLink is being used outside of a :lang dynamic route context. ' +
51
- 'This may cause unexpected behavior. Please ensure I18nLink is used within a route that has a :lang parameter.',
52
- );
53
- }
54
-
55
- if (!hasRouter || !Link) {
56
- const { prefetch: _prefetch, preload: _preload, ...anchorProps } = props;
57
-
58
- return (
59
- <a href={localizedTo} {...anchorProps}>
60
- {children}
61
- </a>
26
+ '[plugin-i18n] I18nLink is deprecated. Import { Link } from ' +
27
+ "'@modern-js/plugin-i18n/runtime' instead it accepts the same " +
28
+ 'language-agnostic `to` values.',
62
29
  );
63
30
  }
64
31
 
65
32
  return (
66
- <Link to={localizedTo} {...props}>
33
+ <Link to={to} {...props}>
67
34
  {children}
68
35
  </Link>
69
36
  );
@@ -0,0 +1,414 @@
1
+ import type React from 'react';
2
+ import { useMemo } from 'react';
3
+ import type {
4
+ LinkParamsProp,
5
+ LinkTargetPathname,
6
+ ValidateLinkTo,
7
+ } from './canonicalRoutes';
8
+ import { useModernI18n } from './context';
9
+ import { canonicalPath, type LocalizedPathsConfig } from './localizedPaths';
10
+ import { useI18nRouterAdapter } from './routerAdapter';
11
+ import { buildLocalizedUrl, splitUrlTarget } from './utils';
12
+
13
+ const EXTERNAL_TARGET_RE = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;
14
+
15
+ const warnedTargets = new Set<string>();
16
+
17
+ const warnOnce = (key: string, message: string) => {
18
+ if (process.env.NODE_ENV !== 'development' || warnedTargets.has(key)) {
19
+ return;
20
+ }
21
+ warnedTargets.add(key);
22
+ console.warn(message);
23
+ };
24
+
25
+ export type LinkParams = Record<string, string | number | undefined>;
26
+
27
+ /**
28
+ * Interpolate `$param`, `:param`, optional (`{-$param}` / `:param?`) and splat
29
+ * (`$` / `*`) segments with concrete values before localization, so
30
+ * pattern-mapped slugs localize correctly.
31
+ */
32
+ export const interpolateRouteParams = (
33
+ pathname: string,
34
+ params?: LinkParams,
35
+ ): string => {
36
+ if (!/[$:*{]/.test(pathname)) {
37
+ return pathname;
38
+ }
39
+
40
+ const resolveParam = (name: string): string | undefined => {
41
+ const value = params?.[name];
42
+ return value === undefined ? undefined : String(value);
43
+ };
44
+
45
+ const segments = pathname
46
+ .split('/')
47
+ .map(segment => {
48
+ if (!segment) {
49
+ return segment;
50
+ }
51
+
52
+ if (segment.startsWith('{-$') && segment.endsWith('}')) {
53
+ const value = resolveParam(segment.slice(3, -1));
54
+ return value === undefined ? null : encodeURIComponent(value);
55
+ }
56
+
57
+ if (segment === '$' || segment === '*') {
58
+ const value = resolveParam('_splat') ?? resolveParam('*');
59
+ return value === undefined
60
+ ? null
61
+ : value.split('/').map(encodeURIComponent).join('/');
62
+ }
63
+
64
+ if (segment.startsWith('$')) {
65
+ const value = resolveParam(segment.slice(1));
66
+ if (value === undefined) {
67
+ warnOnce(
68
+ `missing-param:${pathname}:${segment}`,
69
+ `[plugin-i18n] <Link to="${pathname}"> is missing required param "${segment.slice(1)}".`,
70
+ );
71
+ return segment;
72
+ }
73
+ return encodeURIComponent(value);
74
+ }
75
+
76
+ if (segment.startsWith(':')) {
77
+ const optional = segment.endsWith('?');
78
+ const name = segment.slice(1, optional ? -1 : undefined);
79
+ const value = resolveParam(name);
80
+ if (value === undefined) {
81
+ if (optional) {
82
+ return null;
83
+ }
84
+ warnOnce(
85
+ `missing-param:${pathname}:${segment}`,
86
+ `[plugin-i18n] <Link to="${pathname}"> is missing required param "${name}".`,
87
+ );
88
+ return segment;
89
+ }
90
+ return encodeURIComponent(value);
91
+ }
92
+
93
+ return segment;
94
+ })
95
+ .filter(segment => segment !== null);
96
+
97
+ return segments.join('/') || '/';
98
+ };
99
+
100
+ export interface LinkActiveOptions {
101
+ /**
102
+ * `true`: active only when the location matches the target exactly.
103
+ * `false`: also active when the location is nested under the target.
104
+ * Defaults to prefix matching, except for `/` which defaults to exact.
105
+ */
106
+ exact?: boolean;
107
+ }
108
+
109
+ type AnchorRest = Omit<
110
+ React.AnchorHTMLAttributes<HTMLAnchorElement>,
111
+ 'href' | 'children'
112
+ >;
113
+
114
+ export interface LinkBaseProps extends AnchorRest {
115
+ children?: React.ReactNode;
116
+ /** Hash fragment without the leading `#`. Overrides a `#hash` inside `to`. */
117
+ hash?: string;
118
+ /** Search params. Object form is passed natively to TanStack Link. */
119
+ search?: string | Record<string, unknown>;
120
+ hashScrollIntoView?: boolean | ScrollIntoViewOptions;
121
+ replace?: boolean;
122
+ prefetch?: 'intent' | 'render' | 'viewport' | 'none';
123
+ preload?: unknown;
124
+ activeOptions?: LinkActiveOptions;
125
+ /** Extra anchor props applied when the link is active. */
126
+ activeProps?: AnchorRest & Record<string, unknown>;
127
+ [key: string]: unknown;
128
+ }
129
+
130
+ export type LinkProps<TTo extends string = string> = LinkBaseProps & {
131
+ to: TTo;
132
+ } & ValidateLinkTo<TTo> &
133
+ LinkParamsProp<LinkTargetPathname<TTo>>;
134
+
135
+ const normalizeSearch = (
136
+ search: string | Record<string, unknown> | undefined,
137
+ searchFromTo: string,
138
+ ): {
139
+ searchString: string;
140
+ searchObject: Record<string, string> | undefined;
141
+ } => {
142
+ if (search && typeof search === 'object') {
143
+ const entries = Object.entries(search).filter(
144
+ ([, value]) => value !== undefined && value !== null,
145
+ );
146
+ const searchObject = Object.fromEntries(
147
+ entries.map(([key, value]) => [key, String(value)]),
148
+ );
149
+ const params = new URLSearchParams(searchObject);
150
+ const serialized = params.toString();
151
+ return {
152
+ searchString: serialized ? `?${serialized}` : '',
153
+ searchObject,
154
+ };
155
+ }
156
+
157
+ const raw = typeof search === 'string' && search ? search : searchFromTo;
158
+ if (!raw) {
159
+ return { searchString: '', searchObject: undefined };
160
+ }
161
+
162
+ const searchString = raw.startsWith('?') ? raw : `?${raw}`;
163
+ const searchObject: Record<string, string> = {};
164
+ new URLSearchParams(searchString).forEach((value, key) => {
165
+ searchObject[key] = value;
166
+ });
167
+
168
+ return { searchString, searchObject };
169
+ };
170
+
171
+ const splitActiveProps = (
172
+ active: boolean,
173
+ activeProps?: LinkBaseProps['activeProps'],
174
+ ) => {
175
+ if (!active || !activeProps) {
176
+ return {};
177
+ }
178
+ return activeProps;
179
+ };
180
+
181
+ const mergeClassNames = (...values: Array<unknown>): string | undefined => {
182
+ const classNames = values.filter(
183
+ (value): value is string => typeof value === 'string' && value.length > 0,
184
+ );
185
+ return classNames.length > 0 ? classNames.join(' ') : undefined;
186
+ };
187
+
188
+ /**
189
+ * The standard UltraModern link: a vanilla link in every respect except that
190
+ * it localizes canonical, language-agnostic paths automatically.
191
+ *
192
+ * - `to` accepts canonical routes (`/talks/$slug`), optionally with `#hash`
193
+ * and `?query` suffixes; both survive localization.
194
+ * - External URLs and bare `#hash` targets render a plain `<a>`.
195
+ * - Active state is language-invariant: a canonical `to` is active when the
196
+ * current location matches any localized variant of that route.
197
+ *
198
+ * @example
199
+ * ```tsx
200
+ * <Link to="/talks/$slug" params={{ slug: talk.slug }} hash="abstract" />
201
+ * <Link to="/platform" /> // -> /cs/platforma under cs
202
+ * <Link to="/#work-with-me" /> // cross-page hash, SPA navigation
203
+ * <Link to="https://ai.bleeding.dev" /> // external -> plain <a>
204
+ * ```
205
+ */
206
+ export const Link = <TTo extends string = string>(
207
+ props: LinkProps<TTo>,
208
+ ): React.ReactElement => {
209
+ const {
210
+ to,
211
+ params,
212
+ children,
213
+ hash: hashProp,
214
+ search: searchProp,
215
+ hashScrollIntoView,
216
+ activeOptions,
217
+ activeProps,
218
+ ...rest
219
+ } = props as LinkBaseProps & { to: string; params?: LinkParams };
220
+
221
+ const adapter = useI18nRouterAdapter();
222
+ const { language, supportedLanguages, localisedUrls } = useModernI18n();
223
+
224
+ const config: LocalizedPathsConfig = {
225
+ languages: supportedLanguages,
226
+ localisedUrls,
227
+ };
228
+
229
+ const isExternal = EXTERNAL_TARGET_RE.test(to);
230
+ const isBareHash = to.startsWith('#');
231
+
232
+ const target = useMemo(() => {
233
+ if (isExternal || isBareHash) {
234
+ return null;
235
+ }
236
+
237
+ const {
238
+ pathname,
239
+ search: searchFromTo,
240
+ hash: hashFromTo,
241
+ } = splitUrlTarget(to);
242
+ const interpolated = interpolateRouteParams(pathname || '/', params);
243
+
244
+ const firstSegment = interpolated.split('/').filter(Boolean)[0];
245
+ if (firstSegment && supportedLanguages.includes(firstSegment)) {
246
+ warnOnce(
247
+ `lang-prefix:${to}`,
248
+ `[plugin-i18n] <Link to="${to}"> starts with a language prefix. ` +
249
+ 'Write language-agnostic canonical paths; the Link localizes them automatically.',
250
+ );
251
+ }
252
+
253
+ const localizedPathname = buildLocalizedUrl(
254
+ interpolated,
255
+ language,
256
+ supportedLanguages,
257
+ localisedUrls,
258
+ );
259
+ const hash = hashProp ?? (hashFromTo ? hashFromTo.slice(1) : '');
260
+ const { searchString, searchObject } = normalizeSearch(
261
+ searchProp,
262
+ searchFromTo,
263
+ );
264
+
265
+ return {
266
+ canonicalPathname: interpolated,
267
+ localizedPathname,
268
+ hash,
269
+ searchString,
270
+ searchObject,
271
+ href: `${localizedPathname}${searchString}${hash ? `#${hash}` : ''}`,
272
+ };
273
+ }, [
274
+ to,
275
+ params,
276
+ hashProp,
277
+ searchProp,
278
+ isExternal,
279
+ isBareHash,
280
+ language,
281
+ supportedLanguages,
282
+ localisedUrls,
283
+ ]);
284
+
285
+ const isActive = useMemo(() => {
286
+ if (!target || !adapter.location) {
287
+ return false;
288
+ }
289
+
290
+ const current = canonicalPath(adapter.location.pathname, config);
291
+ const targetCanonical = canonicalPath(target.canonicalPathname, config);
292
+ const exact = activeOptions?.exact ?? targetCanonical === '/';
293
+
294
+ if (current === targetCanonical) {
295
+ return true;
296
+ }
297
+ if (exact) {
298
+ return false;
299
+ }
300
+ return current.startsWith(
301
+ targetCanonical === '/' ? '/' : `${targetCanonical}/`,
302
+ );
303
+ }, [
304
+ target,
305
+ adapter.location,
306
+ activeOptions?.exact,
307
+ supportedLanguages,
308
+ localisedUrls,
309
+ ]);
310
+
311
+ const resolvedActiveProps = splitActiveProps(isActive, activeProps);
312
+ const activeAttributes = isActive
313
+ ? {
314
+ 'data-status': 'active',
315
+ 'aria-current': (rest['aria-current'] ??
316
+ resolvedActiveProps['aria-current'] ??
317
+ 'page') as React.AriaAttributes['aria-current'],
318
+ }
319
+ : {};
320
+
321
+ // External targets and same-page anchors are vanilla links.
322
+ if (!target) {
323
+ const {
324
+ prefetch: _prefetch,
325
+ preload: _preload,
326
+ replace: _replace,
327
+ ...anchorProps
328
+ } = rest;
329
+
330
+ return (
331
+ <a href={to} {...anchorProps}>
332
+ {children}
333
+ </a>
334
+ );
335
+ }
336
+
337
+ const { Link: RouterLink, hasRouter, framework } = adapter;
338
+
339
+ if (!hasRouter || !RouterLink) {
340
+ const {
341
+ prefetch: _prefetch,
342
+ preload: _preload,
343
+ replace: _replace,
344
+ ...anchorProps
345
+ } = rest;
346
+ const {
347
+ className: activeClassName,
348
+ style: activeStyle,
349
+ ...activeRest
350
+ } = resolvedActiveProps;
351
+
352
+ return (
353
+ <a
354
+ href={target.href}
355
+ {...anchorProps}
356
+ {...activeRest}
357
+ {...activeAttributes}
358
+ className={mergeClassNames(rest.className, activeClassName)}
359
+ style={{
360
+ ...(rest.style as React.CSSProperties | undefined),
361
+ ...(activeStyle as React.CSSProperties | undefined),
362
+ }}
363
+ >
364
+ {children}
365
+ </a>
366
+ );
367
+ }
368
+
369
+ const {
370
+ className: activeClassName,
371
+ style: activeStyle,
372
+ ...activeRest
373
+ } = resolvedActiveProps;
374
+ const mergedClassName = mergeClassNames(rest.className, activeClassName);
375
+ const mergedStyle = {
376
+ ...(rest.style as React.CSSProperties | undefined),
377
+ ...(activeStyle as React.CSSProperties | undefined),
378
+ };
379
+
380
+ if (framework === 'tanstack') {
381
+ // Pass hash/search natively: string-concatenated targets silently break
382
+ // TanStack navigation.
383
+ return (
384
+ <RouterLink
385
+ to={target.localizedPathname}
386
+ {...(target.searchObject ? { search: target.searchObject } : {})}
387
+ {...(target.hash ? { hash: target.hash } : {})}
388
+ {...(hashScrollIntoView === undefined ? {} : { hashScrollIntoView })}
389
+ {...rest}
390
+ {...activeRest}
391
+ {...activeAttributes}
392
+ className={mergedClassName}
393
+ style={mergedStyle}
394
+ >
395
+ {children}
396
+ </RouterLink>
397
+ );
398
+ }
399
+
400
+ return (
401
+ <RouterLink
402
+ to={target.href}
403
+ {...rest}
404
+ {...activeRest}
405
+ {...activeAttributes}
406
+ className={mergedClassName}
407
+ style={mergedStyle}
408
+ >
409
+ {children}
410
+ </RouterLink>
411
+ );
412
+ };
413
+
414
+ export default Link;
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Canonical (language-agnostic) route map.
3
+ *
4
+ * Empty by default; populated via declaration merging by the generated
5
+ * `register.gen.d.ts` that `@modern-js/plugin-tanstack` emits:
6
+ *
7
+ * ```ts
8
+ * declare module '@modern-js/plugin-i18n/runtime' {
9
+ * interface UltramodernCanonicalRoutes {
10
+ * '/': Record<string, never>;
11
+ * '/talks': Record<string, never>;
12
+ * '/talks/$slug': { slug: string };
13
+ * }
14
+ * }
15
+ * ```
16
+ *
17
+ * Keys are canonical route patterns in TanStack notation (`$param`,
18
+ * `{-$param}`); values describe the route's path params.
19
+ */
20
+ // biome-ignore lint/suspicious/noEmptyInterface: augmented by generated code
21
+ export interface UltramodernCanonicalRoutes {}
22
+
23
+ export type CanonicalRoutePath = keyof UltramodernCanonicalRoutes & string;
24
+
25
+ type HasCanonicalRoutes = [keyof UltramodernCanonicalRoutes] extends [never]
26
+ ? false
27
+ : true;
28
+
29
+ /**
30
+ * Targets that bypass canonical-route validation: external URLs, same-page
31
+ * hash anchors, and canonical paths with a `?search` and/or `#hash` suffix
32
+ * (the pathname part of suffixed targets is still validated).
33
+ */
34
+ type ExternalLinkTarget =
35
+ | `http://${string}`
36
+ | `https://${string}`
37
+ | `mailto:${string}`
38
+ | `tel:${string}`
39
+ | `//${string}`;
40
+
41
+ type SuffixedCanonicalTarget =
42
+ | `${CanonicalRoutePath}?${string}`
43
+ | `${CanonicalRoutePath}#${string}`;
44
+
45
+ export type AllowedLinkTarget =
46
+ | CanonicalRoutePath
47
+ | SuffixedCanonicalTarget
48
+ | ExternalLinkTarget
49
+ | `#${string}`;
50
+
51
+ /**
52
+ * Validates a literal `to` against the canonical route map. Computed strings
53
+ * (type `string`) always pass — the escape hatch for dynamic values. When no
54
+ * canonical map has been generated, everything passes.
55
+ */
56
+ export type ValidateLinkTo<TTo extends string> =
57
+ HasCanonicalRoutes extends false
58
+ ? unknown
59
+ : string extends TTo
60
+ ? unknown
61
+ : TTo extends AllowedLinkTarget
62
+ ? unknown
63
+ : {
64
+ to: {
65
+ error: 'Not a canonical route. Authors must write language-agnostic paths; see UltramodernCanonicalRoutes.';
66
+ received: TTo;
67
+ };
68
+ };
69
+
70
+ /** Strip `?search`/`#hash` suffixes from a link target type. */
71
+ export type LinkTargetPathname<TTo extends string> =
72
+ TTo extends `${infer TPath}#${string}`
73
+ ? TPath extends `${infer TPure}?${string}`
74
+ ? TPure
75
+ : TPath
76
+ : TTo extends `${infer TPath}?${string}`
77
+ ? TPath
78
+ : TTo;
79
+
80
+ /**
81
+ * `params` prop contract for a canonical target: required when the route has
82
+ * required params, optional when all params are optional, forbidden when the
83
+ * route has none. Non-canonical (computed/external) targets accept a loose
84
+ * record.
85
+ */
86
+ export type LinkParamsProp<TPath extends string> =
87
+ TPath extends CanonicalRoutePath
88
+ ? UltramodernCanonicalRoutes[TPath] extends Record<string, never>
89
+ ? { params?: undefined }
90
+ : Record<string, never> extends UltramodernCanonicalRoutes[TPath]
91
+ ? { params?: UltramodernCanonicalRoutes[TPath] }
92
+ : { params: UltramodernCanonicalRoutes[TPath] }
93
+ : { params?: Record<string, string | number | undefined> };
@@ -82,7 +82,7 @@ export const i18nPlugin = (options: I18nPluginOptions): RuntimePlugin => ({
82
82
  } = localeDetection || {};
83
83
  const { enabled: backendEnabled = false } = backend || {};
84
84
  let latestI18nInstance: I18nInstance | undefined;
85
- let I18nextProvider: React.FunctionComponent<any> | null;
85
+ let I18nextProvider: React.ComponentType<any> | null;
86
86
 
87
87
  const loadReactI18nextIntegration = async () => {
88
88
  if (!reactI18next) {
@@ -293,6 +293,28 @@ export const i18nPlugin = (options: I18nPluginOptions): RuntimePlugin => ({
293
293
  },
294
294
  });
295
295
 
296
+ export type {
297
+ AllowedLinkTarget,
298
+ CanonicalRoutePath,
299
+ UltramodernCanonicalRoutes,
300
+ } from './canonicalRoutes';
296
301
  export { useModernI18n } from './context';
297
- export { I18nLink } from './I18nLink';
302
+ export { I18nLink, type I18nLinkProps } from './I18nLink';
303
+ export {
304
+ Link,
305
+ type LinkActiveOptions,
306
+ type LinkBaseProps,
307
+ type LinkParams,
308
+ type LinkProps,
309
+ } from './Link';
310
+ export {
311
+ canonicalPath,
312
+ type LocalizedPathsConfig,
313
+ localizePath,
314
+ type UseLocalizedLocationReturn,
315
+ type UseLocalizedPathsReturn,
316
+ useLocalizedLocation,
317
+ useLocalizedPaths,
318
+ } from './localizedPaths';
319
+ export { buildLocalizedUrl, splitUrlTarget } from './utils';
298
320
  export default i18nPlugin;