@bleedingdev/modern-js-plugin-tanstack 3.9.0-ultramodern.2 → 3.9.0-ultramodern.21

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 (137) hide show
  1. package/dist/cjs/cli/artifacts.js +15 -1
  2. package/dist/cjs/cli/index.js +12 -0
  3. package/dist/cjs/cli/routeMetadata.js +131 -0
  4. package/dist/cjs/cli/tanstackTypes/canonicalRoutes.js +7 -7
  5. package/dist/cjs/cli/tanstackTypes/shared.js +0 -14
  6. package/dist/cjs/cli/tanstackTypes/source.js +27 -60
  7. package/dist/cjs/runtime/basepathRewrite.js +13 -6
  8. package/dist/cjs/runtime/lifecycle.js +6 -9
  9. package/dist/cjs/runtime/loaderBridge.js +10 -4
  10. package/dist/cjs/runtime/navigation.js +102 -0
  11. package/dist/cjs/runtime/plugin.js +7 -2
  12. package/dist/cjs/runtime/plugin.node.js +86 -64
  13. package/dist/cjs/runtime/prefetchLink.js +2 -7
  14. package/dist/cjs/runtime/register.js +0 -2
  15. package/dist/cjs/runtime/routeTree/construction.js +19 -59
  16. package/dist/cjs/runtime/routeTree/loaders.js +1 -1
  17. package/dist/cjs/runtime/routeTree/paths.js +0 -6
  18. package/dist/cjs/runtime/router.js +25 -9
  19. package/dist/cjs/runtime/ssrManagedTags.js +2 -12
  20. package/dist/cjs/runtime/state.js +2 -2
  21. package/dist/cjs/runtime/utils.js +3 -0
  22. package/dist/cjs/shared/routeDescriptor.js +60 -0
  23. package/dist/esm/cli/artifacts.mjs +13 -2
  24. package/dist/esm/cli/index.mjs +12 -9
  25. package/dist/esm/cli/routeMetadata.mjs +71 -0
  26. package/dist/esm/cli/tanstackTypes/canonicalRoutes.mjs +7 -7
  27. package/dist/esm/cli/tanstackTypes/shared.mjs +1 -9
  28. package/dist/esm/cli/tanstackTypes/source.mjs +28 -61
  29. package/dist/esm/runtime/basepathRewrite.mjs +10 -3
  30. package/dist/esm/runtime/lifecycle.mjs +1 -1
  31. package/dist/esm/runtime/loaderBridge.mjs +8 -5
  32. package/dist/esm/runtime/navigation.mjs +64 -0
  33. package/dist/esm/runtime/plugin.mjs +7 -2
  34. package/dist/esm/runtime/plugin.node.mjs +88 -66
  35. package/dist/esm/runtime/prefetchLink.mjs +1 -6
  36. package/dist/esm/runtime/register.mjs +0 -2
  37. package/dist/esm/runtime/routeTree/construction.mjs +19 -59
  38. package/dist/esm/runtime/routeTree/loaders.mjs +2 -2
  39. package/dist/esm/runtime/routeTree/paths.mjs +1 -4
  40. package/dist/esm/runtime/router.mjs +27 -11
  41. package/dist/esm/runtime/ssrManagedTags.mjs +1 -8
  42. package/dist/esm/runtime/state.mjs +1 -1
  43. package/dist/esm/runtime/utils.mjs +3 -0
  44. package/dist/esm/shared/routeDescriptor.mjs +22 -0
  45. package/dist/esm-node/cli/artifacts.mjs +13 -2
  46. package/dist/esm-node/cli/index.mjs +12 -9
  47. package/dist/esm-node/cli/routeMetadata.mjs +72 -0
  48. package/dist/esm-node/cli/tanstackTypes/canonicalRoutes.mjs +7 -7
  49. package/dist/esm-node/cli/tanstackTypes/shared.mjs +1 -9
  50. package/dist/esm-node/cli/tanstackTypes/source.mjs +28 -61
  51. package/dist/esm-node/runtime/basepathRewrite.mjs +10 -3
  52. package/dist/esm-node/runtime/lifecycle.mjs +1 -1
  53. package/dist/esm-node/runtime/loaderBridge.mjs +8 -5
  54. package/dist/esm-node/runtime/navigation.mjs +65 -0
  55. package/dist/esm-node/runtime/plugin.mjs +7 -2
  56. package/dist/esm-node/runtime/plugin.node.mjs +88 -66
  57. package/dist/esm-node/runtime/prefetchLink.mjs +1 -6
  58. package/dist/esm-node/runtime/register.mjs +0 -2
  59. package/dist/esm-node/runtime/routeTree/construction.mjs +19 -59
  60. package/dist/esm-node/runtime/routeTree/loaders.mjs +2 -2
  61. package/dist/esm-node/runtime/routeTree/paths.mjs +1 -4
  62. package/dist/esm-node/runtime/router.mjs +27 -11
  63. package/dist/esm-node/runtime/ssrManagedTags.mjs +1 -8
  64. package/dist/esm-node/runtime/state.mjs +1 -1
  65. package/dist/esm-node/runtime/utils.mjs +3 -0
  66. package/dist/esm-node/shared/routeDescriptor.mjs +23 -0
  67. package/dist/types/cli/artifacts.d.ts +13 -5
  68. package/dist/types/cli/index.d.ts +1 -1
  69. package/dist/types/cli/routeMetadata.d.ts +18 -0
  70. package/dist/types/cli/tanstackTypes/shared.d.ts +0 -2
  71. package/dist/types/runtime/basepathRewrite.d.ts +2 -1
  72. package/dist/types/runtime/lifecycle.d.ts +9 -2
  73. package/dist/types/runtime/loaderBridge.d.ts +1 -0
  74. package/dist/types/runtime/navigation.d.ts +4 -0
  75. package/dist/types/runtime/register.d.ts +1 -9
  76. package/dist/types/runtime/routeTree/paths.d.ts +0 -2
  77. package/dist/types/runtime/router.d.ts +2 -13
  78. package/dist/types/runtime/ssrManagedTags.d.ts +0 -1
  79. package/dist/types/runtime/ssrTypes.d.ts +0 -7
  80. package/dist/types/runtime/state.d.ts +1 -1
  81. package/dist/types/runtime/types.d.ts +2 -1
  82. package/dist/types/shared/routeDescriptor.d.ts +26 -0
  83. package/package.json +22 -19
  84. package/rstest.config.mts +2 -24
  85. package/src/cli/artifacts.ts +53 -6
  86. package/src/cli/index.ts +11 -2
  87. package/src/cli/routeMetadata.ts +121 -0
  88. package/src/cli/tanstackTypes/canonicalRoutes.ts +17 -12
  89. package/src/cli/tanstackTypes/shared.ts +0 -14
  90. package/src/cli/tanstackTypes/source.ts +42 -116
  91. package/src/runtime/basepathRewrite.ts +11 -2
  92. package/src/runtime/lifecycle.ts +14 -4
  93. package/src/runtime/loaderBridge.ts +9 -9
  94. package/src/runtime/navigation.ts +78 -0
  95. package/src/runtime/plugin.node.tsx +120 -93
  96. package/src/runtime/plugin.tsx +11 -1
  97. package/src/runtime/prefetchLink.tsx +1 -23
  98. package/src/runtime/register.ts +1 -12
  99. package/src/runtime/routeTree/construction.ts +32 -110
  100. package/src/runtime/routeTree/loaders.ts +2 -4
  101. package/src/runtime/routeTree/paths.ts +0 -6
  102. package/src/runtime/router.ts +25 -40
  103. package/src/runtime/ssrManagedTags.ts +0 -17
  104. package/src/runtime/ssrTypes.ts +0 -7
  105. package/src/runtime/state.ts +1 -1
  106. package/src/runtime/types.ts +2 -2
  107. package/src/runtime/utils.tsx +4 -1
  108. package/src/shared/routeDescriptor.ts +46 -0
  109. package/tests/router/cli.test.ts +148 -824
  110. package/tests/router/clientNavigation.ts +13 -0
  111. package/tests/router/dataMutation.test.tsx +17 -85
  112. package/tests/router/flightSerialization.roundtrip.test.tsx +9 -6
  113. package/tests/router/generateRouteArtifacts.test.ts +139 -27
  114. package/tests/router/loaderBridge.test.ts +0 -25
  115. package/tests/router/localisedIdentity.test.tsx +100 -0
  116. package/tests/router/prefetchLink.test.tsx +46 -21
  117. package/tests/router/prefetchLinkPreload.test.tsx +11 -32
  118. package/tests/router/routeHooks.test.ts +42 -105
  119. package/tests/router/routeMetadata.test.ts +233 -0
  120. package/tests/router/routeTree.test.ts +144 -836
  121. package/tests/router/rsc.test.tsx +131 -166
  122. package/tests/router/serverPlugin.test.ts +193 -1
  123. package/tests/router/tanstackTypes.test.ts +218 -963
  124. package/dist/esm/rslib-runtime~1.mjs +0 -18
  125. package/dist/esm-node/rslib-runtime~0.mjs +0 -19
  126. package/tests/realm-isolation.test.ts +0 -114
  127. package/tests/router/fastDefaults.test.ts +0 -32
  128. package/tests/router/fixtures/legacyRuntimeRouter.ts +0 -10
  129. package/tests/router/fixtures/rscDecoderSecurityChild.cjs +0 -162
  130. package/tests/router/hooks.test.ts +0 -40
  131. package/tests/router/hydrationBoundary.test.tsx +0 -23
  132. package/tests/router/packageSurface.test.ts +0 -24
  133. package/tests/router/preloadRedirect.test.ts +0 -64
  134. package/tests/router/register.test.ts +0 -8
  135. package/tests/router/routerCompatibility.test.ts +0 -239
  136. package/tests/router/rscDecoderSecurity.test.ts +0 -113
  137. package/tests/router/rscPayloadRouterMatrix.test.ts +0 -197
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, getters, values)=>{
5
+ var define = (defs, kind)=>{
6
+ for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
7
+ enumerable: true,
8
+ [kind]: defs[key]
9
+ });
10
+ };
11
+ define(getters, "get");
12
+ define(values, "value");
13
+ };
14
+ })();
15
+ (()=>{
16
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
17
+ })();
18
+ (()=>{
19
+ __webpack_require__.r = (exports1)=>{
20
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
21
+ value: 'Module'
22
+ });
23
+ Object.defineProperty(exports1, '__esModule', {
24
+ value: true
25
+ });
26
+ };
27
+ })();
28
+ var __webpack_exports__ = {};
29
+ __webpack_require__.r(__webpack_exports__);
30
+ __webpack_require__.d(__webpack_exports__, {
31
+ describeRouteTree: ()=>describeRouteTree
32
+ });
33
+ const paths_js_namespaceObject = require("../runtime/routeTree/paths.js");
34
+ function describeRouteTree(routes) {
35
+ const root = routes.find((route)=>true === route.isRoot || '/' === route.path && true !== route.index);
36
+ const describe = (route, index)=>({
37
+ source: route,
38
+ location: 0 === (route.path ?? '').length && true !== route.index ? {
39
+ id: route.id || route.file || `pathless-${index}`
40
+ } : {
41
+ path: true === route.index ? '/' : (0, paths_js_namespaceObject.toTanstackPath)(route.path || '')
42
+ },
43
+ hasSplat: Boolean(route.path?.includes('*')),
44
+ children: (route.children ?? []).map(describe)
45
+ });
46
+ return {
47
+ root,
48
+ children: (void 0 !== root ? [
49
+ ...root.children ?? [],
50
+ ...routes.filter((route)=>route !== root)
51
+ ] : routes).map(describe)
52
+ };
53
+ }
54
+ exports.describeRouteTree = __webpack_exports__.describeRouteTree;
55
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
56
+ "describeRouteTree"
57
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
58
+ Object.defineProperty(exports, '__esModule', {
59
+ value: true
60
+ });
@@ -1,5 +1,6 @@
1
1
  import node_path from "node:path";
2
2
  import { fs } from "@modern-js/utils";
3
+ import { ROUTE_METADATA_MANIFEST_FILE_NAME, ROUTE_METADATA_MANIFEST_HEADER, findRouteMetaFiles, renderRouteMetadataManifest } from "./routeMetadata.mjs";
3
4
  import { collectCanonicalRoutesForEntry, generateTanstackRouterTypesSourceForEntry } from "./tanstackTypes.mjs";
4
5
  const DEFAULT_GENERATED_DIR_NAME = 'modern-tanstack';
5
6
  async function writeFileIfChanged(filePath, content) {
@@ -77,7 +78,16 @@ async function writeTanstackRouterTypesForEntries(opts) {
77
78
  canonicalRoutes
78
79
  });
79
80
  }
81
+ async function writeRouteMetadataManifest(opts) {
82
+ const routesDirectory = node_path.join(opts.appDirectory, 'src', 'routes');
83
+ const manifestPath = node_path.join(routesDirectory, ROUTE_METADATA_MANIFEST_FILE_NAME);
84
+ const manifest = renderRouteMetadataManifest(await findRouteMetaFiles(routesDirectory));
85
+ if (null !== manifest) return void await writeFileIfChanged(manifestPath, manifest);
86
+ const previous = await fs.pathExists(manifestPath) ? await fs.readFile(manifestPath, 'utf-8') : null;
87
+ if (previous?.startsWith(`${ROUTE_METADATA_MANIFEST_HEADER}\n`)) throw new Error(`[plugin-tanstack] ${manifestPath} is generated from route.meta.ts files, but none remain below ${routesDirectory}. Restore at least one route.meta.ts that exports routeMeta, or delete the manifest together with its imports.`);
88
+ }
80
89
  async function generateTanstackRouteArtifacts(opts) {
90
+ await writeRouteMetadataManifest(opts);
81
91
  const [{ createRunOptions }, { cli }, utils] = await Promise.all([
82
92
  import("@modern-js/app-tools/cli/run"),
83
93
  import("@modern-js/plugin/cli"),
@@ -95,9 +105,10 @@ async function generateTanstackRouteArtifacts(opts) {
95
105
  version: opts.version || process.env.MODERN_JS_VERSION || '0.0.0-routes-generate',
96
106
  internalPlugins: utils.INTERNAL_RUNTIME_PLUGINS
97
107
  });
98
- await cli.init({
108
+ const { appContext } = await cli.init({
99
109
  ...runOptions,
100
110
  command: 'build'
101
111
  });
112
+ await appContext.hooks.onBeforeExit.call();
102
113
  }
103
- export { generateTanstackRouteArtifacts, writeTanstackRegisterFile, writeTanstackRouterTypesForEntries };
114
+ export { generateTanstackRouteArtifacts, writeRouteMetadataManifest, writeTanstackRegisterFile, writeTanstackRouterTypesForEntries };
@@ -1,20 +1,14 @@
1
1
  import node_path from "node:path";
2
2
  import { NESTED_ROUTE_SPEC_FILE, filterRoutesForServer } from "@modern-js/utils";
3
- import { generateTanstackRouteArtifacts, writeTanstackRegisterFile, writeTanstackRouterTypesForEntries } from "./artifacts.mjs";
3
+ import { generateTanstackRouteArtifacts, writeRouteMetadataManifest, writeTanstackRegisterFile, writeTanstackRouterTypesForEntries } from "./artifacts.mjs";
4
4
  import { createTanstackRsbuildRouteSplittingProfile, resolveTanstackRouteCodeSplittingEnabled } from "./routeSplitting.mjs";
5
- import { __webpack_require__ } from "../rslib-runtime~1.mjs";
6
- __webpack_require__.add({
7
- 267 (module) {
8
- module.exports = require("@modern-js/runtime/cli");
9
- }
10
- });
11
5
  const DEFAULT_ROUTES_DIR = 'routes';
12
6
  const DEFAULT_GENERATED_DIR_NAME = 'modern-tanstack';
13
7
  const ENTRYPOINTS_KEY = '@modern-js/plugin-tanstack';
14
8
  let runtimeRouterCli;
15
9
  function getRuntimeRouterCli() {
16
10
  if (runtimeRouterCli) return runtimeRouterCli;
17
- const cli = __webpack_require__(267);
11
+ const cli = require("@modern-js/runtime/cli");
18
12
  if (cli.handleGeneratorEntryCode && cli.getEntrypointRoutesDir && cli.getEntrypointRoutesOwner && cli.updateNestedRoutesSpec) {
19
13
  runtimeRouterCli = cli;
20
14
  return runtimeRouterCli;
@@ -31,6 +25,15 @@ function tanstackRouterPlugin(options = {}) {
31
25
  '@modern-js/runtime'
32
26
  ],
33
27
  setup: (api)=>{
28
+ const { srcDirectory, serverCompileExcludedFiles = [] } = api.getAppContext();
29
+ api.updateAppContext({
30
+ serverCompileExcludedFiles: [
31
+ ...new Set([
32
+ ...serverCompileExcludedFiles,
33
+ node_path.join(srcDirectory, generatedDirName, 'register.gen.d.ts')
34
+ ])
35
+ ]
36
+ });
34
37
  const nestedRoutesForServer = {};
35
38
  const isTanstackEntrypoint = (entrypoint)=>{
36
39
  const { getEntrypointRoutesDir } = getRuntimeRouterCli();
@@ -173,4 +176,4 @@ function tanstackRouterPlugin(options = {}) {
173
176
  const src_cli = tanstackRouterPlugin;
174
177
  export { collectCanonicalRoutesForEntry, generateTanstackRouterTypesSourceForEntry } from "./tanstackTypes.mjs";
175
178
  export default src_cli;
176
- export { createTanstackRsbuildRouteSplittingProfile, generateTanstackRouteArtifacts, resolveTanstackRouteCodeSplittingEnabled, tanstackRouterPlugin, writeTanstackRegisterFile, writeTanstackRouterTypesForEntries };
179
+ export { createTanstackRsbuildRouteSplittingProfile, generateTanstackRouteArtifacts, resolveTanstackRouteCodeSplittingEnabled, tanstackRouterPlugin, writeRouteMetadataManifest, writeTanstackRegisterFile, writeTanstackRouterTypesForEntries };
@@ -0,0 +1,71 @@
1
+ import { readdir } from "node:fs/promises";
2
+ import node_path from "node:path";
3
+ const ROUTE_META_FILE_NAME = 'route.meta.ts';
4
+ const ROUTE_METADATA_MANIFEST_FILE_NAME = 'ultramodern-route-metadata.ts';
5
+ const ROUTE_METADATA_MANIFEST_HEADER = `// @generated by @modern-js/plugin-tanstack from ${ROUTE_META_FILE_NAME} files. Run routes-generate; do not edit.`;
6
+ const PRINT_WIDTH = 120;
7
+ const MANIFEST_BODY = `export const ultramodernLocalisedUrls = Object.fromEntries(
8
+ ultramodernRouteMetadata
9
+ .filter((route: { canonicalPath: string }) => route.canonicalPath !== '/')
10
+ .map((route) => [route.canonicalPath, route.localisedPaths]),
11
+ );
12
+ export const ultramodernPublicRoutes = ultramodernRouteMetadata
13
+ .filter((route) => route.public && route.indexable)
14
+ .map((route) => ({
15
+ canonicalPath: route.canonicalPath,
16
+ descriptionKey: route.descriptionKey,
17
+ id: route.id,
18
+ localisedPaths: route.localisedPaths,
19
+ namespace: route.namespace,
20
+ ownerAppId: route.ownerAppId,
21
+ titleKey: route.titleKey,
22
+ ...('jsonLd' in route ? { jsonLd: route.jsonLd } : {}),
23
+ }));
24
+ export const ultramodernRouteConfig = {
25
+ authoring: 'colocated-route-meta',
26
+ generatedManifest: true,
27
+ localisedUrls: ultramodernLocalisedUrls,
28
+ namespace: ultramodernRouteNamespace,
29
+ publicRoutes: ultramodernPublicRoutes,
30
+ routes: ultramodernRouteMetadata,
31
+ source: 'route-owned',
32
+ } as const;
33
+ `;
34
+ const compareCodeUnits = (left, right)=>left < right ? -1 : left > right ? 1 : 0;
35
+ const quoteSpecifier = (specifier)=>specifier.includes("'") ? JSON.stringify(specifier) : `'${specifier}'`;
36
+ function renderRouteMetadataManifest(routeMetaFiles) {
37
+ const specifiers = routeMetaFiles.map((file)=>`./${file.replaceAll('\\', '/').replace(/\.ts$/u, '')}`).sort(compareCodeUnits);
38
+ if (0 === specifiers.length) return null;
39
+ const bindings = specifiers.map((_, index)=>`route${index}`);
40
+ const imports = specifiers.map((specifier, index)=>`import { routeMeta as ${bindings[index]} } from ${quoteSpecifier(specifier)};`);
41
+ const inlineRoutes = `export const ultramodernRouteMetadata = [${bindings.join(', ')}] as const;`;
42
+ const routes = inlineRoutes.length <= PRINT_WIDTH ? inlineRoutes : `export const ultramodernRouteMetadata = [\n${bindings.map((binding)=>` ${binding},\n`).join('')}] as const;`;
43
+ return `${ROUTE_METADATA_MANIFEST_HEADER}
44
+ ${imports.join('\n')}
45
+
46
+ export const ultramodernRouteNamespace = route0.namespace;
47
+ ${routes}
48
+ ${MANIFEST_BODY}`;
49
+ }
50
+ async function findRouteMetaFiles(routesDirectory) {
51
+ const files = [];
52
+ const visit = async (relativeDirectory)=>{
53
+ const entries = await readdir(node_path.join(routesDirectory, relativeDirectory), {
54
+ withFileTypes: true
55
+ });
56
+ for (const entry of entries){
57
+ const relativePath = node_path.join(relativeDirectory, entry.name);
58
+ if (entry.isDirectory()) await visit(relativePath);
59
+ else if (entry.isFile() && entry.name === ROUTE_META_FILE_NAME) files.push(relativePath);
60
+ }
61
+ };
62
+ try {
63
+ await visit('');
64
+ } catch (error) {
65
+ const { code, path: missingPath } = error;
66
+ if ('ENOENT' === code && missingPath === routesDirectory) return [];
67
+ throw error;
68
+ }
69
+ return files;
70
+ }
71
+ export { ROUTE_METADATA_MANIFEST_FILE_NAME, ROUTE_METADATA_MANIFEST_HEADER, ROUTE_META_FILE_NAME, findRouteMetaFiles, renderRouteMetadataManifest };
@@ -1,3 +1,4 @@
1
+ import { describeRouteTree } from "../../shared/routeDescriptor.mjs";
1
2
  import { toTanstackPath } from "./shared.mjs";
2
3
  const LOCALE_PARAM_SEGMENTS = new Set([
3
4
  ':lang',
@@ -44,11 +45,13 @@ function collectCanonicalRoutesForEntry(routes, options = {}) {
44
45
  const key = toTanstackPath(normalized);
45
46
  if (!canonicalParams.has(key)) canonicalParams.set(key, paramsTypeForCanonicalPath(normalized));
46
47
  };
47
- const visit = (route, parentPath)=>{
48
+ const visit = (descriptor, parentPath)=>{
49
+ const { source: route, children } = descriptor;
48
50
  let currentPath = parentPath;
49
- if ('string' == typeof route.modernCanonicalPath) {
51
+ const canonicalPath = route.modernLocalisedRoute?.canonicalPath ?? route.modernCanonicalPath;
52
+ if ('string' == typeof canonicalPath) {
50
53
  hasI18nSurface = true;
51
- currentPath = normalizeJoined(route.modernCanonicalPath);
54
+ currentPath = canonicalPath ? normalizeJoined(canonicalPath) : '';
52
55
  } else if ('string' == typeof route.path && route.path.length > 0) {
53
56
  const segments = route.path.replace(/\[(.+?)\]/g, ':$1').split('/').filter(Boolean);
54
57
  if (localeParamHeuristic && '' === parentPath && LOCALE_PARAM_SEGMENTS.has(segments[0])) {
@@ -57,16 +60,13 @@ function collectCanonicalRoutesForEntry(routes, options = {}) {
57
60
  }
58
61
  currentPath = segments.length ? normalizeJoined(`${parentPath}/${segments.join('/')}`) : parentPath;
59
62
  }
60
- const children = route.children;
61
63
  if (children && children.length > 0) {
62
64
  for (const child of children)visit(child, currentPath);
63
65
  return;
64
66
  }
65
67
  record(currentPath || '/');
66
68
  };
67
- const rootModern = routes.find((route)=>route.isRoot);
68
- const topLevel = rootModern ? rootModern.children ?? [] : routes;
69
- for (const route of topLevel)visit(route, '');
69
+ for (const route of describeRouteTree(routes).children)visit(route, '');
70
70
  if (!hasI18nSurface || 0 === canonicalParams.size) return null;
71
71
  return Object.fromEntries([
72
72
  ...canonicalParams.entries()
@@ -42,14 +42,6 @@ function pickRouteSearchContractModules(route) {
42
42
  loaderDepsPath: 'string' == typeof loaderDepsPath ? loaderDepsPath : null
43
43
  };
44
44
  }
45
- function isPathlessLayout(route) {
46
- const extras = route;
47
- return 'nested' === extras.type && 'boolean' != typeof extras.index && void 0 === extras.path;
48
- }
49
- function isIndexRoute(route) {
50
- const extras = route;
51
- return 'nested' === extras.type && Boolean(extras.index);
52
- }
53
45
  function createRouteStaticDataSnippet(opts) {
54
46
  const staticData = createRouteStaticData({
55
47
  modernRouteId: opts.modernRouteId && quote(opts.modernRouteId),
@@ -60,4 +52,4 @@ function createRouteStaticDataSnippet(opts) {
60
52
  return entries.length > 0 ? `staticData: createRouteStaticData({\n ${entries.map(([key, value])=>`${key}: ${value},`).join('\n ')}\n }),` : null;
61
53
  }
62
54
  export { toTanstackPath } from "../../runtime/routeTree/paths.mjs";
63
- export { createRouteStaticDataSnippet, isIndexRoute, isPathlessLayout, normalizeRelativeImport, pickModernLoaderModule, pickRouteSearchContractModules, quote, resolveFileNoExt };
55
+ export { createRouteStaticDataSnippet, normalizeRelativeImport, pickModernLoaderModule, pickRouteSearchContractModules, quote, resolveFileNoExt };
@@ -1,15 +1,11 @@
1
1
  import { makeLegalIdentifier } from "@modern-js/runtime/cli";
2
2
  import { upath } from "@modern-js/utils";
3
- import { createRouteStaticDataSnippet, isIndexRoute, isPathlessLayout, normalizeRelativeImport, pickModernLoaderModule, pickRouteSearchContractModules, quote, resolveFileNoExt, toTanstackPath } from "./shared.mjs";
3
+ import { describeRouteTree } from "../../shared/routeDescriptor.mjs";
4
+ import { createRouteStaticDataSnippet, normalizeRelativeImport, pickModernLoaderModule, pickRouteSearchContractModules, quote, resolveFileNoExt } from "./shared.mjs";
4
5
  async function generateTanstackRouterTypesSourceForEntry(opts) {
5
6
  const { appContext, entryName, generatedDirName = 'modern-tanstack', routes } = opts;
6
7
  const outDir = upath.join(appContext.srcDirectory, generatedDirName, entryName);
7
- const rootModern = routes.find((r)=>{
8
- const extras = r;
9
- return r && 'nested' === extras.type && extras.isRoot;
10
- });
11
- const rootExtras = rootModern;
12
- const topLevel = rootModern ? rootExtras?.children || [] : routes;
8
+ const { root: rootModern, children: topLevel } = describeRouteTree(routes);
13
9
  const imports = [];
14
10
  const statements = [];
15
11
  const loaderImportMap = new Map();
@@ -26,9 +22,8 @@ async function generateTanstackRouterTypesSourceForEntry(opts) {
26
22
  let pendingImportName = componentImportMap.get(componentPath);
27
23
  if (!pendingImportName) {
28
24
  pendingImportName = (async ()=>{
29
- const resolvedNoExt = await resolveRouteModuleNoExt(componentPath);
30
- if (!resolvedNoExt) return null;
31
- const relImport = normalizeRelativeImport(upath.relative(outDir, resolvedNoExt));
25
+ const relImport = await resolveRouteImport(componentPath);
26
+ if (!relImport) return null;
32
27
  const componentName = `component_${componentIndex++}`;
33
28
  imports.push(`import ${componentName} from ${quote(relImport)};`);
34
29
  return componentName;
@@ -37,14 +32,15 @@ async function generateTanstackRouterTypesSourceForEntry(opts) {
37
32
  }
38
33
  return pendingImportName;
39
34
  };
40
- const resolveRouteModuleNoExt = async (aliasedNoExtPath)=>{
35
+ const resolveRouteImport = async (aliasedNoExtPath)=>{
41
36
  const prefix = `${appContext.internalSrcAlias}/`;
42
37
  let absNoExt;
43
38
  if (aliasedNoExtPath.startsWith(prefix)) {
44
39
  const rel = aliasedNoExtPath.slice(prefix.length);
45
40
  absNoExt = upath.join(appContext.srcDirectory, rel);
46
41
  } else absNoExt = upath.isAbsolute(aliasedNoExtPath) ? aliasedNoExtPath : upath.join(appContext.srcDirectory, aliasedNoExtPath);
47
- return resolveFileNoExt(absNoExt);
42
+ const resolvedNoExt = await resolveFileNoExt(absNoExt);
43
+ return resolvedNoExt ? normalizeRelativeImport(upath.relative(outDir, resolvedNoExt)) : null;
48
44
  };
49
45
  const getImportNamesForLoader = async (aliasedNoExtPath, inline, hasAction)=>{
50
46
  const key = `${inline ? 'inline' : 'default'}:${hasAction ? 'action' : 'loader'}:${aliasedNoExtPath}`;
@@ -53,9 +49,8 @@ async function generateTanstackRouterTypesSourceForEntry(opts) {
53
49
  loaderName: existing,
54
50
  actionName: hasAction ? existing.replace(/^loader_/, 'action_') : null
55
51
  };
56
- const resolvedNoExt = await resolveRouteModuleNoExt(aliasedNoExtPath);
57
- if (!resolvedNoExt) return null;
58
- const relImport = normalizeRelativeImport(upath.relative(outDir, resolvedNoExt));
52
+ const relImport = await resolveRouteImport(aliasedNoExtPath);
53
+ if (!relImport) return null;
59
54
  const importName = `loader_${loaderIndex++}`;
60
55
  const actionName = hasAction ? importName.replace(/^loader_/, 'action_') : null;
61
56
  if (inline) {
@@ -75,9 +70,8 @@ async function generateTanstackRouterTypesSourceForEntry(opts) {
75
70
  const key = `${exportName}:${aliasedNoExtPath}`;
76
71
  const existing = searchContractImportMap.get(key);
77
72
  if (existing) return existing;
78
- const resolvedNoExt = await resolveRouteModuleNoExt(aliasedNoExtPath);
79
- if (!resolvedNoExt) return null;
80
- const relImport = normalizeRelativeImport(upath.relative(outDir, resolvedNoExt));
73
+ const relImport = await resolveRouteImport(aliasedNoExtPath);
74
+ if (!relImport) return null;
81
75
  const importName = 'validateSearch' === exportName ? `validateSearch_${validateSearchIndex++}` : `loaderDeps_${loaderDepsIndex++}`;
82
76
  imports.push(`import { ${exportName} as ${importName} } from ${quote(relImport)};`);
83
77
  searchContractImportMap.set(key, importName);
@@ -95,9 +89,7 @@ async function generateTanstackRouterTypesSourceForEntry(opts) {
95
89
  const base = id ? makeLegalIdentifier(id) : `r_${routeIndex++}`;
96
90
  return reserveRouteVarName(`route_${base}`);
97
91
  };
98
- const buildRoute = async (opts)=>{
99
- const { parentVar, route } = opts;
100
- const varName = createRouteVarName(route);
92
+ const createRouteOptions = async (route, hasSplat)=>{
101
93
  const routeExtras = route;
102
94
  const loaderInfo = pickModernLoaderModule(route);
103
95
  const routeAction = routeExtras.action;
@@ -107,20 +99,9 @@ async function generateTanstackRouterTypesSourceForEntry(opts) {
107
99
  const searchContractInfo = pickRouteSearchContractModules(route);
108
100
  const validateSearchName = searchContractInfo.validateSearchPath ? await getImportNameForSearchContract(searchContractInfo.validateSearchPath, 'validateSearch') : null;
109
101
  const loaderDepsName = searchContractInfo.loaderDepsPath ? await getImportNameForSearchContract(searchContractInfo.loaderDepsPath, 'loaderDeps') : null;
110
- const rawPath = routeExtras.path;
111
- const hasSplat = 'string' == typeof rawPath && rawPath.includes('*');
112
- const routeOpts = [
113
- `getParentRoute: () => ${parentVar},`
114
- ];
102
+ const routeOpts = [];
115
103
  const componentName = await getImportNameForComponent(routeExtras._component);
116
104
  if (componentName) routeOpts.push(`component: ${componentName},`);
117
- if (isPathlessLayout(route)) {
118
- const id = routeExtras.id;
119
- routeOpts.push(`id: ${quote(id || 'pathless')},`);
120
- } else {
121
- const p = isIndexRoute(route) ? '/' : toTanstackPath(rawPath || '');
122
- routeOpts.push(`path: ${quote(p)},`);
123
- }
124
105
  if (loaderName) routeOpts.push(`loader: modernLoaderToTanstack({ hasSplat: ${hasSplat} }, ${loaderName}),`);
125
106
  if (validateSearchName) routeOpts.push(`validateSearch: ${validateSearchName},`);
126
107
  if (loaderDepsName) routeOpts.push(`loaderDeps: ${loaderDepsName},`);
@@ -130,39 +111,29 @@ async function generateTanstackRouterTypesSourceForEntry(opts) {
130
111
  actionName
131
112
  });
132
113
  if (staticDataSnippet) routeOpts.push(staticDataSnippet);
133
- const children = routeExtras.children;
114
+ return routeOpts;
115
+ };
116
+ const buildRoute = async (descriptor, parentVar)=>{
117
+ const { source: route, location, hasSplat, children } = descriptor;
118
+ const varName = createRouteVarName(route);
119
+ const routeOpts = [
120
+ `getParentRoute: () => ${parentVar},`,
121
+ ...Object.entries(location).map(([key, value])=>`${key}: ${quote(value)},`),
122
+ ...await createRouteOptions(route, hasSplat)
123
+ ];
134
124
  const hasChildren = Boolean(children && children.length > 0);
135
125
  const routeCtorVarName = hasChildren ? reserveRouteVarName(`${varName}__base`) : varName;
136
126
  statements.push(`const ${routeCtorVarName} = createRoute({\n ${routeOpts.join('\n ')}\n});`);
137
127
  if (children && children.length > 0) {
138
128
  const childVars = [];
139
- for (const child of children)childVars.push(await buildRoute({
140
- parentVar: routeCtorVarName,
141
- route: child
142
- }));
129
+ for (const child of children)childVars.push(await buildRoute(child, routeCtorVarName));
143
130
  statements.push(`const ${varName} = ${routeCtorVarName}.addChildren([${childVars.join(', ')}]);`);
144
131
  }
145
132
  return varName;
146
133
  };
147
- const rootLoaderInfo = rootModern ? pickModernLoaderModule(rootModern) : null;
148
- const rootAction = rootExtras?.action;
149
- const rootLoaderImports = rootLoaderInfo?.loaderPath ? await getImportNamesForLoader(rootLoaderInfo.loaderPath, rootLoaderInfo.inline, Boolean(rootLoaderInfo.inline && rootAction === rootLoaderInfo.loaderPath)) : null;
150
- const rootLoaderName = rootLoaderImports?.loaderName || null;
151
- const rootActionName = rootLoaderImports?.actionName || null;
152
- const rootSearchContractInfo = rootModern ? pickRouteSearchContractModules(rootModern) : null;
153
- const rootValidateSearchName = rootSearchContractInfo?.validateSearchPath ? await getImportNameForSearchContract(rootSearchContractInfo.validateSearchPath, 'validateSearch') : null;
154
- const rootLoaderDepsName = rootSearchContractInfo?.loaderDepsPath ? await getImportNameForSearchContract(rootSearchContractInfo.loaderDepsPath, 'loaderDeps') : null;
155
134
  const topLevelVars = [];
156
- for (const route of topLevel)topLevelVars.push(await buildRoute({
157
- parentVar: 'rootRoute',
158
- route
159
- }));
160
- const rootOpts = [];
161
- const rootComponentName = await getImportNameForComponent(rootExtras?._component);
162
- if (rootComponentName) rootOpts.push(`component: ${rootComponentName},`);
163
- if (rootLoaderName) rootOpts.push(`loader: modernLoaderToTanstack({ hasSplat: false }, ${rootLoaderName}),`);
164
- if (rootValidateSearchName) rootOpts.push(`validateSearch: ${rootValidateSearchName},`);
165
- if (rootLoaderDepsName) rootOpts.push(`loaderDeps: ${rootLoaderDepsName},`);
135
+ for (const route of topLevel)topLevelVars.push(await buildRoute(route, 'rootRoute'));
136
+ const rootOpts = rootModern ? await createRouteOptions(rootModern, false) : [];
166
137
  const routerGenTs = `// This file is auto-generated by Modern.js. Do not edit manually.
167
138
 
168
139
  import {
@@ -179,11 +150,7 @@ ${imports.join('\n')}
179
150
 
180
151
  export const rootRoute = createRootRouteWithContext<ModernRouterContext>()({
181
152
  ${rootOpts.join('\n ')}
182
- ${createRouteStaticDataSnippet({
183
- modernRouteId: rootExtras?.id,
184
- loaderName: rootLoaderName,
185
- actionName: rootActionName
186
- }) || ''}
153
+
187
154
  });
188
155
 
189
156
  ${statements.join('\n\n')}
@@ -1,16 +1,19 @@
1
+ import { createLocalisedRouteRewrite } from "@modern-js/i18n-runtime-extensions";
2
+ import { composeRewrites } from "@tanstack/react-router";
1
3
  function normalizeBasepath(basepath) {
2
4
  if (!basepath) return '/';
3
5
  let normalized = basepath.startsWith('/') ? basepath : `/${basepath}`;
4
6
  if (normalized.length > 1 && normalized.endsWith('/')) normalized = normalized.slice(0, -1);
5
7
  return normalized || '/';
6
8
  }
7
- function createModernBasepathRewrite(basepath, caseSensitive = false) {
9
+ function createModernBasepathRewrite(basepath, caseSensitive = false, routes = []) {
10
+ const localisedRewrite = createLocalisedRouteRewrite(routes);
8
11
  const normalizedBasepath = normalizeBasepath(basepath);
9
- if ('/' === normalizedBasepath) return;
12
+ if ('/' === normalizedBasepath) return localisedRewrite;
10
13
  const normalizedBasepathWithSlash = `${normalizedBasepath}/`;
11
14
  const checkBasepath = caseSensitive ? normalizedBasepath : normalizedBasepath.toLowerCase();
12
15
  const checkBasepathWithSlash = caseSensitive ? normalizedBasepathWithSlash : normalizedBasepathWithSlash.toLowerCase();
13
- return {
16
+ const basepathRewrite = {
14
17
  input: ({ url })=>{
15
18
  const pathname = caseSensitive ? url.pathname : url.pathname.toLowerCase();
16
19
  if (pathname === checkBasepath) url.pathname = '/';
@@ -24,5 +27,9 @@ function createModernBasepathRewrite(basepath, caseSensitive = false) {
24
27
  return url;
25
28
  }
26
29
  };
30
+ return localisedRewrite ? composeRewrites([
31
+ basepathRewrite,
32
+ localisedRewrite
33
+ ]) : basepathRewrite;
27
34
  }
28
35
  export { createModernBasepathRewrite };
@@ -1 +1 @@
1
- export { applyRouterRuntimeState, applyRouterServerPrepareResult, createRouterRuntimeState, createRouterServerSnapshot, getRouterRuntimeState, getRouterServerSnapshot } from "@modern-js/runtime/context";
1
+ export { applyRouterRuntimeState, applyRouterServerPrepareResult, createRouterServerSnapshot, getRouterRuntimeState, getRouterServerSnapshot } from "@modern-js/runtime-extensions/router-state";
@@ -36,10 +36,13 @@ function mapSplatParamsForModernLoader(params, hasSplat) {
36
36
  return rest;
37
37
  }
38
38
  function getLoaderSignal(ctx) {
39
- const abortSignal = ctx?.abortController?.signal;
40
- if (abortSignal instanceof AbortSignal) return abortSignal;
41
- if (ctx?.signal instanceof AbortSignal) return ctx.signal;
42
- return new AbortController().signal;
39
+ const matchSignal = ctx?.abortController?.signal ?? ctx?.signal;
40
+ const requestSignal = ctx?.context?.request?.signal;
41
+ const signals = [
42
+ matchSignal,
43
+ requestSignal
44
+ ].filter((signal)=>signal instanceof AbortSignal);
45
+ return AbortSignal.any(signals);
43
46
  }
44
47
  function getLoaderHref(ctx) {
45
48
  if ('string' == typeof ctx?.location) return ctx.location;
@@ -101,4 +104,4 @@ function modernLoaderToTanstack(opts, modernLoader) {
101
104
  };
102
105
  }
103
106
  export { createRouteStaticData } from "../shared/routeStaticData.mjs";
104
- export { getLoaderHref, handleModernLoaderError, handleModernLoaderResult, isAbsoluteUrl, isRedirectResponse, isResponse, isTanstackRedirect, mapSplatParamsForModernLoader, modernLoaderToTanstack, throwTanstackRedirect };
107
+ export { getLoaderHref, getLoaderSignal, handleModernLoaderError, handleModernLoaderResult, isAbsoluteUrl, isRedirectResponse, isResponse, isTanstackRedirect, mapSplatParamsForModernLoader, modernLoaderToTanstack, throwTanstackRedirect };
@@ -0,0 +1,64 @@
1
+ import { Link } from "./prefetchLink.mjs";
2
+ function createTanstackNavigation(router) {
3
+ let location;
4
+ let matches;
5
+ let snapshot;
6
+ return {
7
+ Link: Link,
8
+ getSnapshot () {
9
+ const state = router.state;
10
+ if (location !== state.location || void 0 === matches || matches.length !== state.matches.length || matches.some((match, index)=>match.params !== state.matches[index]?.params)) {
11
+ location = state.location;
12
+ matches = state.matches;
13
+ snapshot = {
14
+ location: {
15
+ pathname: location.pathname,
16
+ search: location.searchStr,
17
+ hash: '' !== location.hash ? `#${location.hash.replace(/^#/, '')}` : ''
18
+ },
19
+ params: Object.assign({}, ...matches.map((match)=>match.params))
20
+ };
21
+ }
22
+ return snapshot;
23
+ },
24
+ subscribe (listener) {
25
+ const stops = [
26
+ 'onBeforeNavigate',
27
+ 'onBeforeLoad',
28
+ 'onLoad',
29
+ 'onResolved'
30
+ ].map((event)=>router.subscribe(event, listener));
31
+ return ()=>{
32
+ for (const stop of stops)stop();
33
+ };
34
+ },
35
+ navigate (href, options) {
36
+ return router.navigate({
37
+ to: href,
38
+ replace: options?.replace,
39
+ ...options?.state === void 0 ? {} : {
40
+ state: options.state
41
+ }
42
+ });
43
+ },
44
+ createLinkProps (target) {
45
+ const preload = void 0 !== target.preload ? target.preload : 'none' === target.prefetch ? false : target.prefetch;
46
+ return {
47
+ to: target.pathname,
48
+ ...void 0 !== target.search ? {
49
+ search: target.search
50
+ } : {},
51
+ ...void 0 !== target.hash && '' !== target.hash ? {
52
+ hash: target.hash
53
+ } : {},
54
+ ...void 0 === target.hashScrollIntoView ? {} : {
55
+ hashScrollIntoView: target.hashScrollIntoView
56
+ },
57
+ ...void 0 === preload ? {} : {
58
+ preload
59
+ }
60
+ };
61
+ }
62
+ };
63
+ }
64
+ export { createTanstackNavigation };
@@ -10,6 +10,7 @@ import { ModernRouterClient, getTanstackSsrHydrationPromise, hasTanstackSsrHydra
10
10
  import { routerProviderRegistryHooks } from "./hooks.mjs";
11
11
  import { wrapTanstackSsrHydrationBoundary } from "./hydrationBoundary.mjs";
12
12
  import { applyRouterRuntimeState } from "./lifecycle.mjs";
13
+ import { createTanstackNavigation } from "./navigation.mjs";
13
14
  import { createTanstackRouteObjects, getMergedRouterConfig, getTanstackRouteConfig, joinBasename } from "./pluginShared.mjs";
14
15
  import { Link } from "./prefetchLink.mjs";
15
16
  import { useMatches } from "./routeHooks.mjs";
@@ -77,7 +78,7 @@ const tanstackRouterPlugin = (userConfig = {})=>{
77
78
  const mergedConfig = getMergedConfig();
78
79
  const { supportHtml5History = true } = mergedConfig;
79
80
  const history = supportHtml5History ? createBrowserHistory() : createHashHistory();
80
- const rewrite = createModernBasepathRewrite(_basename);
81
+ const rewrite = createModernBasepathRewrite(_basename, false, getRouteObjects());
81
82
  const serializationAdapters = getGlobalEnableRsc() ? getTanstackRscSerializationAdapters() : void 0;
82
83
  const routerFastDefaults = getModernTanstackRouterFastDefaults(mergedConfig);
83
84
  cachedRouter = createRouter({
@@ -142,10 +143,14 @@ const tanstackRouterPlugin = (userConfig = {})=>{
142
143
  runtimeContext
143
144
  ]);
144
145
  if (!router) return App ? /*#__PURE__*/ jsx(App, {}) : null;
146
+ const navigation = useMemo(()=>createTanstackNavigation(router), [
147
+ router
148
+ ]);
145
149
  const runtimeState = applyRouterRuntimeState(runtimeContext, {
146
150
  framework: 'tanstack',
147
151
  basename: _basename,
148
- instance: router
152
+ instance: router,
153
+ navigation
149
154
  });
150
155
  const lifecycleContext = {
151
156
  framework: 'tanstack',