From 99df5ae4247142021caece58cdb5ba6638e4e0e6 Mon Sep 17 00:00:00 2001 From: Manuel Schiller <6340397+schiller-manuel@users.noreply.github.com> Date: Sun, 1 Nov 2026 23:38:51 +0100 Subject: [PATCH 01/14] feat: experimental route modules for file-based routing Route modules are workspace packages that own a subtree of file-based routes and are mounted into applications or other modules. A package declares `tanstack.router.module` in its package.json. The generator gives it qualified route ids (`:`), a generated route scope (`routeScope.gen.ts` plus one namespace file per included or used module), a public contract (`routeContract.gen.ts`, exported as `./route-types` after the package's own declaration build), a runtime entry (`routeModule.gen.ts`, exported as `./route-module`) and a topology manifest (`.tanstack/route-module.json`). Includers mount modules with the `routeModules` option: `includes` chooses the host route and mount path, optionally under path params, `uses` references modules mounted elsewhere, and an application installs a module several times by including it once per installation named with `as`, each with its own namespace and route ids (`#:`). Matches of module routes carry `localRouteId`, and the generated `isScopedMatch` guard narrows whole-router matches by module id prefix. Runtime: the generated host tree mounts module roots with the internal `mountRouteModule`; module-local ids, destinations, redirects and not-found errors resolve to the installation of the route that uses them; `HostedRouter` types the links of code that mounts modules under path params. Type composition is contract-based through `./route-types`; the framework packages augment `@tanstack/router-core/extensions` and export `RouteCore`. Start: modules get `createServerFn`, `createMiddleware` and `createStartModule` in their scope, declare required context by augmenting `StartModuleRequirements`, and contribute fragments that applications install with `createStart(() => ({ extends: startModules }))`; `startModules.gen.ts` type-checks installation and requirements. The Start plugin lists module routes in the routes manifest, selects the providers' client tree views, discovers prerenderable module pages and extends import protection to module packages. Build and tooling: the host bundler compiles, code-splits and hot-updates module routes, including every installation; `tsr generate` and `tsr watch` are the only commands and packages own their declaration builds; the devtools show modules; the `route-module-imports` ESLint rule enforces scope imports. Fixtures cover React, Solid, Vue and Start with Vite and Rsbuild, and a large example measures builds. --- .changeset/clever-buttons-push.md | 12 + .changeset/itchy-chairs-melt.md | 5 + .changeset/route-modules-devtools.md | 5 + .changeset/route-modules-eslint.md | 5 + .changeset/route-modules-generator.md | 7 + .changeset/route-modules-router.md | 8 + .changeset/route-modules-start.md | 9 + .changeset/router-core-extensions.md | 10 + .changeset/salty-dryers-move.md | 5 + .changeset/start-modules-many-fragments.md | 5 + .../start-rsbuild-compiler-esm-resolve.md | 5 + .changeset/true-houses-behave.md | 16 + .../client-nav/link-performance/cases.ts | 9 + .../link-performance/src/workload.tsx | 10 + docs/router/config.json | 8 + docs/router/eslint/eslint-plugin-router.md | 1 + docs/router/eslint/route-module-imports.md | 47 + docs/router/routing/route-modules.md | 445 ++++ docs/start/config.json | 4 + .../framework/react/guide/route-modules.md | 196 ++ e2e/react-router/route-modules/.gitignore | 8 + .../route-modules/e2e-dev/devtools.spec.ts | 46 + .../route-modules/e2e-dev/hmr.spec.ts | 109 + .../route-modules/e2e/app.spec.ts | 126 ++ .../route-modules/e2e/scope-parity.spec.ts | 215 ++ e2e/react-router/route-modules/package.json | 24 + .../packages/account/package.json | 43 + .../packages/account/src/routes/__root.tsx | 25 + .../packages/account/src/routes/index.tsx | 35 + .../account/src/routes/orders.$orderId.tsx | 44 + .../packages/account/tsconfig.json | 15 + .../account/tsconfig.route-types.json | 13 + .../packages/billing/package.json | 41 + .../packages/billing/src/routes/__root.tsx | 23 + .../packages/billing/src/routes/index.tsx | 29 + .../packages/billing/tsconfig.json | 15 + .../billing/tsconfig.route-types.json | 13 + .../packages/products/package.json | 43 + .../packages/products/src/api.ts | 12 + .../products/src/routes/$productId.tsx | 49 + .../packages/products/src/routes/__root.tsx | 24 + .../packages/products/src/routes/_layout.tsx | 10 + .../products/src/routes/_layout/deals.tsx | 12 + .../src/routes/catalog.{-$category}.tsx | 12 + .../packages/products/src/routes/compare.tsx | 17 + .../packages/products/src/routes/files.$.tsx | 10 + .../packages/products/src/routes/index.tsx | 22 + .../packages/products/src/routes/legacy.tsx | 10 + .../packages/products/src/schemas.ts | 6 + .../packages/products/tsconfig.json | 15 + .../products/tsconfig.route-types.json | 13 + .../packages/settings/package.json | 38 + .../packages/settings/src/routes/__root.tsx | 44 + .../packages/settings/src/routes/forward.tsx | 5 + .../packages/settings/src/routes/index.tsx | 16 + .../packages/settings/src/routes/legacy.tsx | 6 + .../packages/settings/src/routes/members.tsx | 12 + .../packages/settings/src/routes/missing.tsx | 6 + .../packages/settings/src/routes/profile.tsx | 81 + .../packages/settings/src/routes/search.tsx | 4 + .../packages/settings/tsconfig.json | 15 + .../settings/tsconfig.route-types.json | 13 + .../packages/storefront/package.json | 42 + .../packages/storefront/src/routes/__root.tsx | 26 + .../packages/storefront/src/routes/cart.tsx | 30 + .../packages/storefront/src/routes/index.tsx | 30 + .../packages/storefront/tsconfig.json | 15 + .../storefront/tsconfig.route-types.json | 13 + .../route-modules/packages/team/package.json | 38 + .../packages/team/src/routes/__root.tsx | 27 + .../packages/team/src/routes/index.tsx | 25 + .../team/src/routes/members.$memberId.tsx | 28 + .../route-modules/packages/team/tsconfig.json | 15 + .../packages/team/tsconfig.route-types.json | 13 + .../route-modules/packages/web/index.html | 11 + .../route-modules/packages/web/package.json | 33 + .../route-modules/packages/web/src/main.tsx | 28 + .../packages/web/src/profile-links.tsx | 18 + .../route-modules/packages/web/src/router.tsx | 20 + .../packages/web/src/routes/__root.tsx | 94 + .../web/src/routes/_authenticated.tsx | 6 + .../packages/web/src/routes/index.tsx | 122 ++ .../packages/web/src/routes/orgs.$orgId.tsx | 15 + .../web/src/routes/people.$personId.tsx | 13 + .../route-modules/packages/web/src/styles.css | 450 ++++ .../web/tests/match-identity.test.tsx | 139 ++ .../packages/web/tests/scope-options.test.tsx | 140 ++ .../packages/web/tsconfig.contracts.json | 7 + .../route-modules/packages/web/tsconfig.json | 15 + .../packages/web/tsr.config.json | 36 + .../web/type-tests/core-contracts.tsx | 211 ++ .../packages/web/type-tests/module-apis.tsx | 207 ++ .../web/type-tests/scope-contracts.tsx | 96 + .../web/type-tests/validation-aliases.tsx | 110 + .../route-modules/packages/web/vite.config.ts | 12 + .../route-modules/playwright.config.ts | 29 + .../route-modules/playwright.dev.config.ts | 29 + .../route-modules/scripts/prepare.mjs | 49 + .../tests/generated-api-bundles.test.ts | 446 ++++ .../tests/generated-scope-cache.test.ts | 114 + .../tests/host-context-contracts.test.ts | 52 + .../tests/host-parameter-contracts.test.ts | 73 + .../route-modules/tests/route-modules.test.ts | 511 +++++ .../route-modules/tests/workspace.ts | 287 +++ e2e/react-router/route-modules/tsconfig.json | 20 + .../route-modules/vitest.config.ts | 11 + e2e/react-start/route-modules/.gitignore | 9 + .../route-modules/e2e-dev/devtools.spec.ts | 50 + .../route-modules/e2e-dev/hmr.spec.ts | 169 ++ e2e/react-start/route-modules/e2e/app.spec.ts | 160 ++ e2e/react-start/route-modules/package.json | 54 + .../packages/catalog/package.json | 36 + .../route-modules/packages/catalog/src/api.ts | 41 + .../packages/catalog/src/money.ts | 20 + .../packages/catalog/src/requirements.ts | 7 + .../catalog/src/routes/$productId.tsx | 62 + .../packages/catalog/src/routes/__root.tsx | 21 + .../packages/catalog/src/routes/index.tsx | 25 + .../packages/catalog/src/start.ts | 8 + .../packages/catalog/tsconfig.json | 15 + .../catalog/tsconfig.route-types.json | 13 + .../route-modules/packages/notes/package.json | 34 + .../packages/notes/src/routes/__root.tsx | 18 + .../packages/notes/src/routes/index.tsx | 18 + .../packages/notes/tsconfig.json | 15 + .../packages/notes/tsconfig.route-types.json | 13 + .../packages/settings/package.json | 36 + .../packages/settings/src/api.ts | 6 + .../packages/settings/src/routes/__root.tsx | 38 + .../packages/settings/src/routes/index.tsx | 15 + .../packages/settings/src/routes/profile.tsx | 27 + .../packages/settings/tsconfig.json | 15 + .../settings/tsconfig.route-types.json | 13 + .../route-modules/packages/team/package.json | 41 + .../route-modules/packages/team/src/api.ts | 8 + .../packages/team/src/routes/__root.tsx | 25 + .../packages/team/src/routes/index.tsx | 27 + .../team/src/routes/members.$memberId.tsx | 28 + .../route-modules/packages/team/tsconfig.json | 15 + .../packages/team/tsconfig.route-types.json | 13 + .../route-modules/packages/web/package.json | 34 + .../packages/web/route-modules.ts | 28 + .../packages/web/rsbuild.config.ts | 16 + .../route-modules/packages/web/server.js | 19 + .../route-modules/packages/web/src/router.tsx | 6 + .../packages/web/src/routes/__root.tsx | 90 + .../packages/web/src/routes/index.tsx | 90 + .../packages/web/src/routes/orgs.$orgId.tsx | 15 + .../web/src/routes/people.$personId.tsx | 13 + .../route-modules/packages/web/src/start.ts | 12 + .../route-modules/packages/web/src/styles.css | 486 +++++ .../route-modules/packages/web/tsconfig.json | 15 + .../route-modules/packages/web/vite.config.ts | 14 + .../route-modules/playwright.config.ts | 31 + .../route-modules/playwright.dev.config.ts | 30 + .../route-modules/scripts/prepare.mjs | 43 + .../route-modules/tests/start-modules.test.ts | 328 +++ .../route-modules/tests/workspace.ts | 225 ++ e2e/react-start/route-modules/tsconfig.json | 20 + .../route-modules/vitest.config.ts | 11 + e2e/solid-router/route-modules/.gitignore | 2 + .../route-modules/e2e/scope-parity.spec.ts | 177 ++ e2e/solid-router/route-modules/index.html | 11 + e2e/solid-router/route-modules/package.json | 29 + .../packages/settings/package.json | 37 + .../packages/settings/src/routes/__root.tsx | 8 + .../packages/settings/src/routes/forward.tsx | 4 + .../packages/settings/src/routes/index.tsx | 4 + .../packages/settings/src/routes/legacy.tsx | 6 + .../packages/settings/src/routes/members.tsx | 11 + .../packages/settings/src/routes/missing.tsx | 6 + .../packages/settings/src/routes/profile.tsx | 56 + .../packages/settings/src/routes/search.tsx | 4 + .../packages/settings/tsconfig.json | 16 + .../settings/tsconfig.route-types.json | 13 + .../packages/settings/tsr.config.json | 3 + .../route-modules/playwright.config.ts | 17 + .../route-modules/scripts/prepare.mjs | 28 + e2e/solid-router/route-modules/src/main.tsx | 19 + .../route-modules/src/routes/__root.tsx | 29 + .../route-modules/src/routes/orgs.$orgId.tsx | 2 + .../src/routes/users.$userId.tsx | 2 + e2e/solid-router/route-modules/tsconfig.json | 16 + .../route-modules/tsr.config.json | 19 + .../type-tests/scope-contracts.tsx | 95 + .../type-tests/validation-aliases.tsx | 110 + e2e/solid-router/route-modules/vite.config.ts | 10 + e2e/vue-router/route-modules/.gitignore | 2 + .../route-modules/e2e/scope-parity.spec.ts | 175 ++ e2e/vue-router/route-modules/index.html | 11 + e2e/vue-router/route-modules/package.json | 29 + .../packages/settings/package.json | 37 + .../packages/settings/src/routes/__root.tsx | 9 + .../packages/settings/src/routes/forward.tsx | 5 + .../packages/settings/src/routes/index.tsx | 4 + .../packages/settings/src/routes/legacy.tsx | 6 + .../packages/settings/src/routes/members.tsx | 12 + .../packages/settings/src/routes/missing.tsx | 6 + .../packages/settings/src/routes/profile.tsx | 58 + .../packages/settings/src/routes/search.tsx | 4 + .../packages/settings/tsconfig.json | 16 + .../settings/tsconfig.route-types.json | 13 + .../packages/settings/tsr.config.json | 3 + .../route-modules/playwright.config.ts | 17 + .../route-modules/scripts/prepare.mjs | 28 + e2e/vue-router/route-modules/src/main.tsx | 16 + .../route-modules/src/routes/__root.tsx | 32 + .../route-modules/src/routes/orgs.$orgId.tsx | 2 + .../src/routes/users.$userId.tsx | 2 + e2e/vue-router/route-modules/tsconfig.json | 16 + e2e/vue-router/route-modules/tsr.config.json | 19 + .../type-tests/scope-contracts.tsx | 95 + .../type-tests/validation-aliases.tsx | 110 + e2e/vue-router/route-modules/vite.config.ts | 10 + eslint.config.js | 14 + .../start-large-route-modules/.gitignore | 21 + .../start-large-route-modules/.prettierignore | 4 + .../react/start-large-route-modules/README.md | 80 + .../app/rsbuild.config.ts | 11 + .../start-large-route-modules/app/server.js | 18 + .../app/src/router.tsx | 10 + .../app/src/routes/__root.tsx | 44 + .../app/src/routes/index.tsx | 23 + .../app/src/start.ts | 10 + .../app/src/styles.css | 114 + .../app/tsconfig.json | 20 + .../app/vite.config.ts | 11 + .../start-large-route-modules/package.json | 49 + .../start-large-route-modules/scripts/gen.mjs | 384 ++++ .../scripts/measure.mjs | 242 +++ .../template/account/src/api.ts | 8 + .../template/account/src/routes/__root.tsx | 18 + .../template/account/src/routes/index.tsx | 21 + .../template/feature/src/api.ts | 45 + .../template/feature/src/requirements.ts | 10 + .../template/feature/src/routes/$itemId.tsx | 28 + .../template/feature/src/routes/__root.tsx | 28 + .../template/feature/src/routes/index.tsx | 25 + .../feature/src/routes/pages/page.tsx | 30 + .../template/feature/src/routes/search.tsx | 44 + .../src/__tests__/fixtures/app/package.json | 4 + .../fixtures/route-module/package.json | 9 + .../route-module-imports.rule.test.ts | 101 + packages/eslint-plugin-router/src/index.ts | 2 + packages/eslint-plugin-router/src/rules.ts | 2 + .../rules/route-module-imports/constants.ts | 37 + .../route-module-imports.rule.ts | 90 + .../route-module-imports.utils.ts | 50 + packages/eslint-plugin-router/tsconfig.json | 3 +- packages/react-router/package.json | 24 +- packages/react-router/src/Match.tsx | 6 +- packages/react-router/src/Matches.tsx | 72 +- packages/react-router/src/fileRoute.ts | 142 +- packages/react-router/src/index.tsx | 47 + packages/react-router/src/link.tsx | 81 +- packages/react-router/src/matchContext.tsx | 2 +- .../react-router/src/route-module-internal.ts | 6 + packages/react-router/src/route.tsx | 130 +- packages/react-router/src/routeModule.tsx | 441 ++++ packages/react-router/src/router.ts | 2 +- packages/react-router/src/routerStores.ts | 2 +- packages/react-router/src/ssr/serializer.ts | 2 +- packages/react-router/src/useBlocker.tsx | 41 +- packages/react-router/src/useLoaderData.tsx | 26 +- packages/react-router/src/useLoaderDeps.tsx | 19 +- packages/react-router/src/useLocation.tsx | 15 + packages/react-router/src/useMatch.tsx | 51 +- packages/react-router/src/useNavigate.tsx | 55 +- packages/react-router/src/useParams.tsx | 31 +- packages/react-router/src/useRouteContext.ts | 19 +- packages/react-router/src/useRouter.tsx | 17 +- packages/react-router/src/useRouterState.tsx | 16 +- packages/react-router/src/useSearch.tsx | 31 +- .../tests/blocker-server.test.tsx | 33 + .../tests/navigate-options-parity.test.tsx | 96 + .../tests/registered-router-cycle/app.tsx | 95 + .../registered-router-cycle/tsconfig.json | 6 + .../react-router/tests/routeApi.test-d.tsx | 2 +- packages/react-router/tsconfig.json | 3 +- packages/react-router/vite.config.ts | 1 + packages/react-start-rsc/eslint.config.js | 3 +- packages/react-start-rsc/package.json | 2 +- .../src/ServerComponentTypes.ts | 2 +- packages/react-start/package.json | 10 +- packages/react-start/src/index.ts | 1 + .../react-start/src/route-module-internal.ts | 1 + packages/react-start/vite.config.ts | 1 + packages/router-cli/package.json | 2 +- packages/router-core/package.json | 22 +- packages/router-core/src/Matches.ts | 101 +- packages/router-core/src/RouterProvider.ts | 19 +- packages/router-core/src/extensions.ts | 32 + packages/router-core/src/index.ts | 57 +- packages/router-core/src/link.ts | 41 + packages/router-core/src/load-client.ts | 20 +- packages/router-core/src/load-server.ts | 16 +- packages/router-core/src/redirect.ts | 24 +- packages/router-core/src/route-id.ts | 27 + .../router-core/src/route-module-internal.ts | 4 + packages/router-core/src/route-module.ts | 820 ++++++++ packages/router-core/src/route.ts | 68 +- packages/router-core/src/router.ts | 85 +- packages/router-core/src/stores.ts | 4 +- packages/router-core/src/useNavigate.ts | 14 +- .../tests/route-module-unmounted.test.ts | 44 + .../router-core/tests/route-module.test.ts | 853 ++++++++ .../router-core/tests/route-modules.bench.ts | 342 +++ packages/router-core/vite.config.ts | 2 + .../src/BaseTanStackRouterDevtoolsPanel.tsx | 287 ++- .../router-devtools-core/src/routeModules.ts | 75 + .../router-devtools-core/src/useStyles.tsx | 48 + .../tests/route-modules.test.ts | 198 ++ packages/router-generator/src/config.ts | 25 +- .../router-generator/src/generated-names.ts | 120 ++ packages/router-generator/src/generator.ts | 1126 +++++++++- packages/router-generator/src/index.ts | 26 + .../src}/pruneServerOnlySubtrees.ts | 8 +- .../src/route-module/context.ts | 629 ++++++ .../src/route-module/declaration.ts | 252 +++ .../router-generator/src/route-module/emit.ts | 493 +++++ .../src/route-module/manifest.ts | 126 ++ .../src/routeClassification.ts | 11 + .../src/transform/transform.ts | 42 +- .../router-generator/src/transform/types.ts | 5 + packages/router-generator/src/types.ts | 10 + packages/router-generator/src/utils.ts | 44 +- .../tests/route-modules.test.ts | 1859 +++++++++++++++++ .../routeScope.catalog.snapshot.ts | 210 ++ .../application/routeScope.snapshot.ts | 9 + .../application/routeTree.snapshot.ts | 79 + .../host-params/routeContract.snapshot.ts | 49 + .../routeScope.catalog.snapshot.ts | 218 ++ .../host-params/routeScope.snapshot.ts | 261 +++ .../host-params/routeTree.snapshot.ts | 103 + .../includer/routeContract.snapshot.ts | 49 + .../includer/routeScope.catalog.snapshot.ts | 210 ++ .../includer/routeScope.snapshot.ts | 261 +++ .../includer/routeTree.snapshot.ts | 99 + .../routeScope.account.snapshot.ts | 218 ++ .../routeScope.orgCatalog.snapshot.ts | 249 +++ .../installations/routeScope.snapshot.ts | 13 + .../routeScope.userCatalog.snapshot.ts | 255 +++ .../installations/routeTree.snapshot.ts | 157 ++ .../module/routeContract.snapshot.ts | 33 + .../module/routeModule.snapshot.ts | 10 + .../module/routeScope.snapshot.ts | 277 +++ .../module/routeTree.snapshot.ts | 112 + .../startModules.snapshot.ts | 34 + .../start-module/routeModule.snapshot.ts | 18 + .../start-module/routeScope.snapshot.ts | 306 +++ packages/router-generator/tsconfig.json | 3 +- .../router-generator/tsconfig.legacy.json | 2 +- packages/router-plugin/package.json | 2 +- .../src/core/code-splitter/compilers.ts | 37 +- .../src/core/hmr/handle-route-update.ts | 76 +- .../src/core/hmr/vite-adapter.ts | 10 +- .../src/core/hmr/webpack-adapter.ts | 12 +- .../src/core/router-generator-plugin.ts | 42 +- packages/router-plugin/tests/add-hmr.test.ts | 2 +- .../snapshots/react/arrow-function@true.tsx | 70 +- .../react/arrow-function@webpack-hot.tsx | 72 +- ...ateFileRoute-lowercase-components@true.tsx | 70 +- .../createRootRoute-inline-component@true.tsx | 70 +- ...ateRootRoute-lowercase-components@true.tsx | 70 +- .../snapshots/react/createRootRoute@true.tsx | 70 +- ...ateRootRouteWithContext-type-args@true.tsx | 70 +- .../explicit-undefined-component@true.tsx | 70 +- .../react/function-declaration@true.tsx | 70 +- .../snapshots/react/multi-component@true.tsx | 70 +- .../react/string-literal-keys@true.tsx | 70 +- .../snapshots/solid/arrow-function@true.tsx | 70 +- .../router-plugin/tests/code-splitter.test.ts | 193 +- .../react/1-default/inline-memo-component.tsx | 7 + .../inline-memo-component@component.tsx | 6 + .../inline-memo-component@errorComponent.tsx | 0 ...nline-memo-component@notFoundComponent.tsx | 0 .../inline-memo-component@shared.tsx | 0 .../inline-memo-component.tsx | 7 + ...--notFoundComponent---pendingComponent.tsx | 6 + .../inline-memo-component@loader.tsx | 0 .../inline-memo-component@shared.tsx | 0 .../inline-memo-component.tsx | 7 + ...--notFoundComponent---pendingComponent.tsx | 6 + .../inline-memo-component@errorComponent.tsx | 0 .../inline-memo-component@shared.tsx | 0 .../vue/1-default/inline-define-component.tsx | 7 + .../inline-define-component@component.tsx | 8 + ...inline-define-component@errorComponent.tsx | 0 ...ine-define-component@notFoundComponent.tsx | 0 .../inline-define-component@shared.tsx | 0 .../inline-define-component.tsx | 7 + ...--notFoundComponent---pendingComponent.tsx | 8 + .../inline-define-component@loader.tsx | 0 .../inline-define-component@shared.tsx | 0 .../inline-define-component.tsx | 7 + ...--notFoundComponent---pendingComponent.tsx | 8 + ...inline-define-component@errorComponent.tsx | 0 .../inline-define-component@shared.tsx | 0 .../react/inline-memo-component.tsx | 9 + .../vue/inline-define-component.tsx | 11 + .../tests/handle-route-update.test.ts | 76 +- packages/router-vite-plugin/package.json | 2 +- packages/solid-router/package.json | 16 +- packages/solid-router/src/Match.tsx | 9 +- packages/solid-router/src/Matches.tsx | 69 +- packages/solid-router/src/fileRoute.ts | 142 +- packages/solid-router/src/index.tsx | 47 + packages/solid-router/src/link.tsx | 39 +- .../solid-router/src/route-module-internal.ts | 6 + packages/solid-router/src/route.tsx | 125 +- packages/solid-router/src/routeModule.tsx | 435 ++++ packages/solid-router/src/router.ts | 2 +- packages/solid-router/src/useBlocker.tsx | 41 +- packages/solid-router/src/useLoaderData.tsx | 19 +- packages/solid-router/src/useLoaderDeps.tsx | 18 +- packages/solid-router/src/useLocation.tsx | 13 + packages/solid-router/src/useMatch.tsx | 59 +- packages/solid-router/src/useNavigate.tsx | 65 +- packages/solid-router/src/useParams.tsx | 28 +- packages/solid-router/src/useRouteContext.ts | 19 +- packages/solid-router/src/useRouter.tsx | 17 +- packages/solid-router/src/useRouterState.tsx | 21 +- packages/solid-router/src/useSearch.tsx | 28 +- .../tests/blocker-server.test.tsx | 32 + .../tests/navigate-options-parity.test.tsx | 74 + .../solid-router/tests/routeApi.test-d.tsx | 2 +- .../tests/server/Navigate.test.tsx | 34 + packages/solid-router/vite.config.ts | 1 + packages/solid-start/package.json | 10 +- packages/solid-start/src/index.ts | 1 + .../solid-start/src/route-module-internal.ts | 1 + packages/solid-start/vite.config.ts | 1 + packages/start-client-core/package.json | 8 +- .../start-client-core/src/createMiddleware.ts | 42 +- .../start-client-core/src/createServerFn.ts | 4 +- packages/start-client-core/src/createStart.ts | 193 +- .../src/createStartModule.ts | 797 +++++++ packages/start-client-core/src/index.tsx | 15 + .../src/route-module-internal.ts | 1 + packages/start-client-core/src/serverRoute.ts | 2 +- .../start-client-core/src/startOptionList.ts | 11 + .../src/tests/createStartModule.test-d.ts | 331 +++ .../tests/moduleMiddlewareConsumers.test-d.ts | 111 + .../startModuleConditionalEntry.test-d.ts | 40 + .../startModuleConditionalOptions.test-d.ts | 331 +++ ...tartModuleContextProjectionEdges.test-d.ts | 316 +++ .../tests/startModuleContextScaling.test-d.ts | 211 ++ .../tests/startModuleGlobalOwner.test-d.ts | 106 + ...startModuleImpossibleRequirement.test-d.ts | 26 + .../tests/startModuleInstallation.test-d.ts | 56 + .../startModuleRequirementFreeArray.test-d.ts | 34 + .../startModuleUnionRequirement.test-d.ts | 178 ++ .../startModuleUnscopedConsumer.test-d.ts | 70 + .../startModuleWidenedGlobalDedupe.test-d.ts | 43 + .../tests/createStartModule.test.ts | 175 ++ packages/start-client-core/vite.config.ts | 1 + packages/start-plugin-core/package.json | 2 +- .../src/import-protection/adapterUtils.ts | 12 +- packages/start-plugin-core/src/prerender.ts | 11 +- .../src/rsbuild/import-protection.ts | 18 +- .../start-plugin-core/src/rsbuild/plugin.ts | 37 +- .../src/rsbuild/start-compiler-host.ts | 53 +- .../src/rsbuild/start-router-plugin.ts | 37 + .../start-router-plugin/client-route-tree.ts | 87 + .../prerender-routes-plugin.ts | 36 +- .../routes-manifest-plugin.ts | 79 +- .../route-module-directories.ts | 25 + .../vite/import-protection-plugin/plugin.ts | 17 +- .../vite/import-protection-plugin/types.ts | 2 + .../src/vite/start-router-plugin/plugin.ts | 82 +- .../tests/route-module-start-build.test.ts | 744 +++++++ packages/vue-router/package.json | 8 +- packages/vue-router/src/Match.tsx | 6 +- packages/vue-router/src/Matches.tsx | 76 +- packages/vue-router/src/fileRoute.ts | 142 +- packages/vue-router/src/index.tsx | 47 + packages/vue-router/src/link.tsx | 70 +- .../vue-router/src/route-module-internal.ts | 6 + packages/vue-router/src/route.ts | 128 +- packages/vue-router/src/routeModule.ts | 441 ++++ packages/vue-router/src/router.ts | 2 +- packages/vue-router/src/routerStores.ts | 2 +- packages/vue-router/src/useBlocker.tsx | 39 +- packages/vue-router/src/useLoaderData.tsx | 19 +- packages/vue-router/src/useLoaderDeps.tsx | 18 +- packages/vue-router/src/useLocation.tsx | 13 + packages/vue-router/src/useMatch.tsx | 89 +- packages/vue-router/src/useNavigate.tsx | 74 +- packages/vue-router/src/useParams.tsx | 28 +- packages/vue-router/src/useRouteContext.ts | 19 +- packages/vue-router/src/useRouter.tsx | 17 +- packages/vue-router/src/useRouterState.tsx | 17 +- packages/vue-router/src/useSearch.tsx | 28 +- .../vue-router/tests/blocker-server.test.tsx | 38 + .../tests/navigate-options-parity.test.tsx | 107 + packages/vue-router/vite.config.ts | 1 + packages/vue-start/package.json | 10 +- packages/vue-start/src/index.ts | 1 + .../vue-start/src/route-module-internal.ts | 1 + packages/vue-start/vite.config.ts | 1 + pnpm-lock.yaml | 685 +++++- pnpm-workspace.yaml | 8 +- scripts/benchmarks/route-modules/measure.mjs | 586 ++++++ .../benchmarks/route-modules/measure.test.mjs | 32 + .../benchmarks/route-modules/scoped-match.mjs | 241 +++ .../benchmarks/route-modules/start-types.mjs | 325 +++ 506 files changed, 33444 insertions(+), 1286 deletions(-) create mode 100644 .changeset/clever-buttons-push.md create mode 100644 .changeset/itchy-chairs-melt.md create mode 100644 .changeset/route-modules-devtools.md create mode 100644 .changeset/route-modules-eslint.md create mode 100644 .changeset/route-modules-generator.md create mode 100644 .changeset/route-modules-router.md create mode 100644 .changeset/route-modules-start.md create mode 100644 .changeset/router-core-extensions.md create mode 100644 .changeset/salty-dryers-move.md create mode 100644 .changeset/start-modules-many-fragments.md create mode 100644 .changeset/start-rsbuild-compiler-esm-resolve.md create mode 100644 .changeset/true-houses-behave.md create mode 100644 docs/router/eslint/route-module-imports.md create mode 100644 docs/router/routing/route-modules.md create mode 100644 docs/start/framework/react/guide/route-modules.md create mode 100644 e2e/react-router/route-modules/.gitignore create mode 100644 e2e/react-router/route-modules/e2e-dev/devtools.spec.ts create mode 100644 e2e/react-router/route-modules/e2e-dev/hmr.spec.ts create mode 100644 e2e/react-router/route-modules/e2e/app.spec.ts create mode 100644 e2e/react-router/route-modules/e2e/scope-parity.spec.ts create mode 100644 e2e/react-router/route-modules/package.json create mode 100644 e2e/react-router/route-modules/packages/account/package.json create mode 100644 e2e/react-router/route-modules/packages/account/src/routes/__root.tsx create mode 100644 e2e/react-router/route-modules/packages/account/src/routes/index.tsx create mode 100644 e2e/react-router/route-modules/packages/account/src/routes/orders.$orderId.tsx create mode 100644 e2e/react-router/route-modules/packages/account/tsconfig.json create mode 100644 e2e/react-router/route-modules/packages/account/tsconfig.route-types.json create mode 100644 e2e/react-router/route-modules/packages/billing/package.json create mode 100644 e2e/react-router/route-modules/packages/billing/src/routes/__root.tsx create mode 100644 e2e/react-router/route-modules/packages/billing/src/routes/index.tsx create mode 100644 e2e/react-router/route-modules/packages/billing/tsconfig.json create mode 100644 e2e/react-router/route-modules/packages/billing/tsconfig.route-types.json create mode 100644 e2e/react-router/route-modules/packages/products/package.json create mode 100644 e2e/react-router/route-modules/packages/products/src/api.ts create mode 100644 e2e/react-router/route-modules/packages/products/src/routes/$productId.tsx create mode 100644 e2e/react-router/route-modules/packages/products/src/routes/__root.tsx create mode 100644 e2e/react-router/route-modules/packages/products/src/routes/_layout.tsx create mode 100644 e2e/react-router/route-modules/packages/products/src/routes/_layout/deals.tsx create mode 100644 e2e/react-router/route-modules/packages/products/src/routes/catalog.{-$category}.tsx create mode 100644 e2e/react-router/route-modules/packages/products/src/routes/compare.tsx create mode 100644 e2e/react-router/route-modules/packages/products/src/routes/files.$.tsx create mode 100644 e2e/react-router/route-modules/packages/products/src/routes/index.tsx create mode 100644 e2e/react-router/route-modules/packages/products/src/routes/legacy.tsx create mode 100644 e2e/react-router/route-modules/packages/products/src/schemas.ts create mode 100644 e2e/react-router/route-modules/packages/products/tsconfig.json create mode 100644 e2e/react-router/route-modules/packages/products/tsconfig.route-types.json create mode 100644 e2e/react-router/route-modules/packages/settings/package.json create mode 100644 e2e/react-router/route-modules/packages/settings/src/routes/__root.tsx create mode 100644 e2e/react-router/route-modules/packages/settings/src/routes/forward.tsx create mode 100644 e2e/react-router/route-modules/packages/settings/src/routes/index.tsx create mode 100644 e2e/react-router/route-modules/packages/settings/src/routes/legacy.tsx create mode 100644 e2e/react-router/route-modules/packages/settings/src/routes/members.tsx create mode 100644 e2e/react-router/route-modules/packages/settings/src/routes/missing.tsx create mode 100644 e2e/react-router/route-modules/packages/settings/src/routes/profile.tsx create mode 100644 e2e/react-router/route-modules/packages/settings/src/routes/search.tsx create mode 100644 e2e/react-router/route-modules/packages/settings/tsconfig.json create mode 100644 e2e/react-router/route-modules/packages/settings/tsconfig.route-types.json create mode 100644 e2e/react-router/route-modules/packages/storefront/package.json create mode 100644 e2e/react-router/route-modules/packages/storefront/src/routes/__root.tsx create mode 100644 e2e/react-router/route-modules/packages/storefront/src/routes/cart.tsx create mode 100644 e2e/react-router/route-modules/packages/storefront/src/routes/index.tsx create mode 100644 e2e/react-router/route-modules/packages/storefront/tsconfig.json create mode 100644 e2e/react-router/route-modules/packages/storefront/tsconfig.route-types.json create mode 100644 e2e/react-router/route-modules/packages/team/package.json create mode 100644 e2e/react-router/route-modules/packages/team/src/routes/__root.tsx create mode 100644 e2e/react-router/route-modules/packages/team/src/routes/index.tsx create mode 100644 e2e/react-router/route-modules/packages/team/src/routes/members.$memberId.tsx create mode 100644 e2e/react-router/route-modules/packages/team/tsconfig.json create mode 100644 e2e/react-router/route-modules/packages/team/tsconfig.route-types.json create mode 100644 e2e/react-router/route-modules/packages/web/index.html create mode 100644 e2e/react-router/route-modules/packages/web/package.json create mode 100644 e2e/react-router/route-modules/packages/web/src/main.tsx create mode 100644 e2e/react-router/route-modules/packages/web/src/profile-links.tsx create mode 100644 e2e/react-router/route-modules/packages/web/src/router.tsx create mode 100644 e2e/react-router/route-modules/packages/web/src/routes/__root.tsx create mode 100644 e2e/react-router/route-modules/packages/web/src/routes/_authenticated.tsx create mode 100644 e2e/react-router/route-modules/packages/web/src/routes/index.tsx create mode 100644 e2e/react-router/route-modules/packages/web/src/routes/orgs.$orgId.tsx create mode 100644 e2e/react-router/route-modules/packages/web/src/routes/people.$personId.tsx create mode 100644 e2e/react-router/route-modules/packages/web/src/styles.css create mode 100644 e2e/react-router/route-modules/packages/web/tests/match-identity.test.tsx create mode 100644 e2e/react-router/route-modules/packages/web/tests/scope-options.test.tsx create mode 100644 e2e/react-router/route-modules/packages/web/tsconfig.contracts.json create mode 100644 e2e/react-router/route-modules/packages/web/tsconfig.json create mode 100644 e2e/react-router/route-modules/packages/web/tsr.config.json create mode 100644 e2e/react-router/route-modules/packages/web/type-tests/core-contracts.tsx create mode 100644 e2e/react-router/route-modules/packages/web/type-tests/module-apis.tsx create mode 100644 e2e/react-router/route-modules/packages/web/type-tests/scope-contracts.tsx create mode 100644 e2e/react-router/route-modules/packages/web/type-tests/validation-aliases.tsx create mode 100644 e2e/react-router/route-modules/packages/web/vite.config.ts create mode 100644 e2e/react-router/route-modules/playwright.config.ts create mode 100644 e2e/react-router/route-modules/playwright.dev.config.ts create mode 100644 e2e/react-router/route-modules/scripts/prepare.mjs create mode 100644 e2e/react-router/route-modules/tests/generated-api-bundles.test.ts create mode 100644 e2e/react-router/route-modules/tests/generated-scope-cache.test.ts create mode 100644 e2e/react-router/route-modules/tests/host-context-contracts.test.ts create mode 100644 e2e/react-router/route-modules/tests/host-parameter-contracts.test.ts create mode 100644 e2e/react-router/route-modules/tests/route-modules.test.ts create mode 100644 e2e/react-router/route-modules/tests/workspace.ts create mode 100644 e2e/react-router/route-modules/tsconfig.json create mode 100644 e2e/react-router/route-modules/vitest.config.ts create mode 100644 e2e/react-start/route-modules/.gitignore create mode 100644 e2e/react-start/route-modules/e2e-dev/devtools.spec.ts create mode 100644 e2e/react-start/route-modules/e2e-dev/hmr.spec.ts create mode 100644 e2e/react-start/route-modules/e2e/app.spec.ts create mode 100644 e2e/react-start/route-modules/package.json create mode 100644 e2e/react-start/route-modules/packages/catalog/package.json create mode 100644 e2e/react-start/route-modules/packages/catalog/src/api.ts create mode 100644 e2e/react-start/route-modules/packages/catalog/src/money.ts create mode 100644 e2e/react-start/route-modules/packages/catalog/src/requirements.ts create mode 100644 e2e/react-start/route-modules/packages/catalog/src/routes/$productId.tsx create mode 100644 e2e/react-start/route-modules/packages/catalog/src/routes/__root.tsx create mode 100644 e2e/react-start/route-modules/packages/catalog/src/routes/index.tsx create mode 100644 e2e/react-start/route-modules/packages/catalog/src/start.ts create mode 100644 e2e/react-start/route-modules/packages/catalog/tsconfig.json create mode 100644 e2e/react-start/route-modules/packages/catalog/tsconfig.route-types.json create mode 100644 e2e/react-start/route-modules/packages/notes/package.json create mode 100644 e2e/react-start/route-modules/packages/notes/src/routes/__root.tsx create mode 100644 e2e/react-start/route-modules/packages/notes/src/routes/index.tsx create mode 100644 e2e/react-start/route-modules/packages/notes/tsconfig.json create mode 100644 e2e/react-start/route-modules/packages/notes/tsconfig.route-types.json create mode 100644 e2e/react-start/route-modules/packages/settings/package.json create mode 100644 e2e/react-start/route-modules/packages/settings/src/api.ts create mode 100644 e2e/react-start/route-modules/packages/settings/src/routes/__root.tsx create mode 100644 e2e/react-start/route-modules/packages/settings/src/routes/index.tsx create mode 100644 e2e/react-start/route-modules/packages/settings/src/routes/profile.tsx create mode 100644 e2e/react-start/route-modules/packages/settings/tsconfig.json create mode 100644 e2e/react-start/route-modules/packages/settings/tsconfig.route-types.json create mode 100644 e2e/react-start/route-modules/packages/team/package.json create mode 100644 e2e/react-start/route-modules/packages/team/src/api.ts create mode 100644 e2e/react-start/route-modules/packages/team/src/routes/__root.tsx create mode 100644 e2e/react-start/route-modules/packages/team/src/routes/index.tsx create mode 100644 e2e/react-start/route-modules/packages/team/src/routes/members.$memberId.tsx create mode 100644 e2e/react-start/route-modules/packages/team/tsconfig.json create mode 100644 e2e/react-start/route-modules/packages/team/tsconfig.route-types.json create mode 100644 e2e/react-start/route-modules/packages/web/package.json create mode 100644 e2e/react-start/route-modules/packages/web/route-modules.ts create mode 100644 e2e/react-start/route-modules/packages/web/rsbuild.config.ts create mode 100644 e2e/react-start/route-modules/packages/web/server.js create mode 100644 e2e/react-start/route-modules/packages/web/src/router.tsx create mode 100644 e2e/react-start/route-modules/packages/web/src/routes/__root.tsx create mode 100644 e2e/react-start/route-modules/packages/web/src/routes/index.tsx create mode 100644 e2e/react-start/route-modules/packages/web/src/routes/orgs.$orgId.tsx create mode 100644 e2e/react-start/route-modules/packages/web/src/routes/people.$personId.tsx create mode 100644 e2e/react-start/route-modules/packages/web/src/start.ts create mode 100644 e2e/react-start/route-modules/packages/web/src/styles.css create mode 100644 e2e/react-start/route-modules/packages/web/tsconfig.json create mode 100644 e2e/react-start/route-modules/packages/web/vite.config.ts create mode 100644 e2e/react-start/route-modules/playwright.config.ts create mode 100644 e2e/react-start/route-modules/playwright.dev.config.ts create mode 100644 e2e/react-start/route-modules/scripts/prepare.mjs create mode 100644 e2e/react-start/route-modules/tests/start-modules.test.ts create mode 100644 e2e/react-start/route-modules/tests/workspace.ts create mode 100644 e2e/react-start/route-modules/tsconfig.json create mode 100644 e2e/react-start/route-modules/vitest.config.ts create mode 100644 e2e/solid-router/route-modules/.gitignore create mode 100644 e2e/solid-router/route-modules/e2e/scope-parity.spec.ts create mode 100644 e2e/solid-router/route-modules/index.html create mode 100644 e2e/solid-router/route-modules/package.json create mode 100644 e2e/solid-router/route-modules/packages/settings/package.json create mode 100644 e2e/solid-router/route-modules/packages/settings/src/routes/__root.tsx create mode 100644 e2e/solid-router/route-modules/packages/settings/src/routes/forward.tsx create mode 100644 e2e/solid-router/route-modules/packages/settings/src/routes/index.tsx create mode 100644 e2e/solid-router/route-modules/packages/settings/src/routes/legacy.tsx create mode 100644 e2e/solid-router/route-modules/packages/settings/src/routes/members.tsx create mode 100644 e2e/solid-router/route-modules/packages/settings/src/routes/missing.tsx create mode 100644 e2e/solid-router/route-modules/packages/settings/src/routes/profile.tsx create mode 100644 e2e/solid-router/route-modules/packages/settings/src/routes/search.tsx create mode 100644 e2e/solid-router/route-modules/packages/settings/tsconfig.json create mode 100644 e2e/solid-router/route-modules/packages/settings/tsconfig.route-types.json create mode 100644 e2e/solid-router/route-modules/packages/settings/tsr.config.json create mode 100644 e2e/solid-router/route-modules/playwright.config.ts create mode 100644 e2e/solid-router/route-modules/scripts/prepare.mjs create mode 100644 e2e/solid-router/route-modules/src/main.tsx create mode 100644 e2e/solid-router/route-modules/src/routes/__root.tsx create mode 100644 e2e/solid-router/route-modules/src/routes/orgs.$orgId.tsx create mode 100644 e2e/solid-router/route-modules/src/routes/users.$userId.tsx create mode 100644 e2e/solid-router/route-modules/tsconfig.json create mode 100644 e2e/solid-router/route-modules/tsr.config.json create mode 100644 e2e/solid-router/route-modules/type-tests/scope-contracts.tsx create mode 100644 e2e/solid-router/route-modules/type-tests/validation-aliases.tsx create mode 100644 e2e/solid-router/route-modules/vite.config.ts create mode 100644 e2e/vue-router/route-modules/.gitignore create mode 100644 e2e/vue-router/route-modules/e2e/scope-parity.spec.ts create mode 100644 e2e/vue-router/route-modules/index.html create mode 100644 e2e/vue-router/route-modules/package.json create mode 100644 e2e/vue-router/route-modules/packages/settings/package.json create mode 100644 e2e/vue-router/route-modules/packages/settings/src/routes/__root.tsx create mode 100644 e2e/vue-router/route-modules/packages/settings/src/routes/forward.tsx create mode 100644 e2e/vue-router/route-modules/packages/settings/src/routes/index.tsx create mode 100644 e2e/vue-router/route-modules/packages/settings/src/routes/legacy.tsx create mode 100644 e2e/vue-router/route-modules/packages/settings/src/routes/members.tsx create mode 100644 e2e/vue-router/route-modules/packages/settings/src/routes/missing.tsx create mode 100644 e2e/vue-router/route-modules/packages/settings/src/routes/profile.tsx create mode 100644 e2e/vue-router/route-modules/packages/settings/src/routes/search.tsx create mode 100644 e2e/vue-router/route-modules/packages/settings/tsconfig.json create mode 100644 e2e/vue-router/route-modules/packages/settings/tsconfig.route-types.json create mode 100644 e2e/vue-router/route-modules/packages/settings/tsr.config.json create mode 100644 e2e/vue-router/route-modules/playwright.config.ts create mode 100644 e2e/vue-router/route-modules/scripts/prepare.mjs create mode 100644 e2e/vue-router/route-modules/src/main.tsx create mode 100644 e2e/vue-router/route-modules/src/routes/__root.tsx create mode 100644 e2e/vue-router/route-modules/src/routes/orgs.$orgId.tsx create mode 100644 e2e/vue-router/route-modules/src/routes/users.$userId.tsx create mode 100644 e2e/vue-router/route-modules/tsconfig.json create mode 100644 e2e/vue-router/route-modules/tsr.config.json create mode 100644 e2e/vue-router/route-modules/type-tests/scope-contracts.tsx create mode 100644 e2e/vue-router/route-modules/type-tests/validation-aliases.tsx create mode 100644 e2e/vue-router/route-modules/vite.config.ts create mode 100644 examples/react/start-large-route-modules/.gitignore create mode 100644 examples/react/start-large-route-modules/.prettierignore create mode 100644 examples/react/start-large-route-modules/README.md create mode 100644 examples/react/start-large-route-modules/app/rsbuild.config.ts create mode 100644 examples/react/start-large-route-modules/app/server.js create mode 100644 examples/react/start-large-route-modules/app/src/router.tsx create mode 100644 examples/react/start-large-route-modules/app/src/routes/__root.tsx create mode 100644 examples/react/start-large-route-modules/app/src/routes/index.tsx create mode 100644 examples/react/start-large-route-modules/app/src/start.ts create mode 100644 examples/react/start-large-route-modules/app/src/styles.css create mode 100644 examples/react/start-large-route-modules/app/tsconfig.json create mode 100644 examples/react/start-large-route-modules/app/vite.config.ts create mode 100644 examples/react/start-large-route-modules/package.json create mode 100644 examples/react/start-large-route-modules/scripts/gen.mjs create mode 100644 examples/react/start-large-route-modules/scripts/measure.mjs create mode 100644 examples/react/start-large-route-modules/template/account/src/api.ts create mode 100644 examples/react/start-large-route-modules/template/account/src/routes/__root.tsx create mode 100644 examples/react/start-large-route-modules/template/account/src/routes/index.tsx create mode 100644 examples/react/start-large-route-modules/template/feature/src/api.ts create mode 100644 examples/react/start-large-route-modules/template/feature/src/requirements.ts create mode 100644 examples/react/start-large-route-modules/template/feature/src/routes/$itemId.tsx create mode 100644 examples/react/start-large-route-modules/template/feature/src/routes/__root.tsx create mode 100644 examples/react/start-large-route-modules/template/feature/src/routes/index.tsx create mode 100644 examples/react/start-large-route-modules/template/feature/src/routes/pages/page.tsx create mode 100644 examples/react/start-large-route-modules/template/feature/src/routes/search.tsx create mode 100644 packages/eslint-plugin-router/src/__tests__/fixtures/app/package.json create mode 100644 packages/eslint-plugin-router/src/__tests__/fixtures/route-module/package.json create mode 100644 packages/eslint-plugin-router/src/__tests__/route-module-imports.rule.test.ts create mode 100644 packages/eslint-plugin-router/src/rules/route-module-imports/constants.ts create mode 100644 packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.rule.ts create mode 100644 packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.utils.ts create mode 100644 packages/react-router/src/route-module-internal.ts create mode 100644 packages/react-router/src/routeModule.tsx create mode 100644 packages/react-router/tests/blocker-server.test.tsx create mode 100644 packages/react-router/tests/navigate-options-parity.test.tsx create mode 100644 packages/react-router/tests/registered-router-cycle/app.tsx create mode 100644 packages/react-router/tests/registered-router-cycle/tsconfig.json create mode 100644 packages/react-start/src/route-module-internal.ts create mode 100644 packages/router-core/src/extensions.ts create mode 100644 packages/router-core/src/route-id.ts create mode 100644 packages/router-core/src/route-module-internal.ts create mode 100644 packages/router-core/src/route-module.ts create mode 100644 packages/router-core/tests/route-module-unmounted.test.ts create mode 100644 packages/router-core/tests/route-module.test.ts create mode 100644 packages/router-core/tests/route-modules.bench.ts create mode 100644 packages/router-devtools-core/src/routeModules.ts create mode 100644 packages/router-devtools-core/tests/route-modules.test.ts create mode 100644 packages/router-generator/src/generated-names.ts rename packages/{start-plugin-core/src/start-router-plugin => router-generator/src}/pruneServerOnlySubtrees.ts (85%) create mode 100644 packages/router-generator/src/route-module/context.ts create mode 100644 packages/router-generator/src/route-module/declaration.ts create mode 100644 packages/router-generator/src/route-module/emit.ts create mode 100644 packages/router-generator/src/route-module/manifest.ts create mode 100644 packages/router-generator/src/routeClassification.ts create mode 100644 packages/router-generator/tests/route-modules.test.ts create mode 100644 packages/router-generator/tests/route-modules/application/routeScope.catalog.snapshot.ts create mode 100644 packages/router-generator/tests/route-modules/application/routeScope.snapshot.ts create mode 100644 packages/router-generator/tests/route-modules/application/routeTree.snapshot.ts create mode 100644 packages/router-generator/tests/route-modules/host-params/routeContract.snapshot.ts create mode 100644 packages/router-generator/tests/route-modules/host-params/routeScope.catalog.snapshot.ts create mode 100644 packages/router-generator/tests/route-modules/host-params/routeScope.snapshot.ts create mode 100644 packages/router-generator/tests/route-modules/host-params/routeTree.snapshot.ts create mode 100644 packages/router-generator/tests/route-modules/includer/routeContract.snapshot.ts create mode 100644 packages/router-generator/tests/route-modules/includer/routeScope.catalog.snapshot.ts create mode 100644 packages/router-generator/tests/route-modules/includer/routeScope.snapshot.ts create mode 100644 packages/router-generator/tests/route-modules/includer/routeTree.snapshot.ts create mode 100644 packages/router-generator/tests/route-modules/installations/routeScope.account.snapshot.ts create mode 100644 packages/router-generator/tests/route-modules/installations/routeScope.orgCatalog.snapshot.ts create mode 100644 packages/router-generator/tests/route-modules/installations/routeScope.snapshot.ts create mode 100644 packages/router-generator/tests/route-modules/installations/routeScope.userCatalog.snapshot.ts create mode 100644 packages/router-generator/tests/route-modules/installations/routeTree.snapshot.ts create mode 100644 packages/router-generator/tests/route-modules/module/routeContract.snapshot.ts create mode 100644 packages/router-generator/tests/route-modules/module/routeModule.snapshot.ts create mode 100644 packages/router-generator/tests/route-modules/module/routeScope.snapshot.ts create mode 100644 packages/router-generator/tests/route-modules/module/routeTree.snapshot.ts create mode 100644 packages/router-generator/tests/route-modules/start-application/startModules.snapshot.ts create mode 100644 packages/router-generator/tests/route-modules/start-module/routeModule.snapshot.ts create mode 100644 packages/router-generator/tests/route-modules/start-module/routeScope.snapshot.ts create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline-memo-component.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline-memo-component@component.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline-memo-component@errorComponent.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline-memo-component@notFoundComponent.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline-memo-component@shared.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline-memo-component.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline-memo-component@component---errorComponent---notFoundComponent---pendingComponent.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline-memo-component@loader.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline-memo-component@shared.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline-memo-component.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline-memo-component@component---loader---notFoundComponent---pendingComponent.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline-memo-component@errorComponent.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline-memo-component@shared.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/1-default/inline-define-component.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/1-default/inline-define-component@component.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/1-default/inline-define-component@errorComponent.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/1-default/inline-define-component@notFoundComponent.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/1-default/inline-define-component@shared.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/2-components-combined-loader-separate/inline-define-component.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/2-components-combined-loader-separate/inline-define-component@component---errorComponent---notFoundComponent---pendingComponent.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/2-components-combined-loader-separate/inline-define-component@loader.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/2-components-combined-loader-separate/inline-define-component@shared.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/3-all-combined-errorComponent-separate/inline-define-component.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/3-all-combined-errorComponent-separate/inline-define-component@component---loader---notFoundComponent---pendingComponent.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/3-all-combined-errorComponent-separate/inline-define-component@errorComponent.tsx create mode 100644 packages/router-plugin/tests/code-splitter/snapshots/vue/3-all-combined-errorComponent-separate/inline-define-component@shared.tsx create mode 100644 packages/router-plugin/tests/code-splitter/test-files/react/inline-memo-component.tsx create mode 100644 packages/router-plugin/tests/code-splitter/test-files/vue/inline-define-component.tsx create mode 100644 packages/solid-router/src/route-module-internal.ts create mode 100644 packages/solid-router/src/routeModule.tsx create mode 100644 packages/solid-router/tests/blocker-server.test.tsx create mode 100644 packages/solid-router/tests/navigate-options-parity.test.tsx create mode 100644 packages/solid-router/tests/server/Navigate.test.tsx create mode 100644 packages/solid-start/src/route-module-internal.ts create mode 100644 packages/start-client-core/src/createStartModule.ts create mode 100644 packages/start-client-core/src/route-module-internal.ts create mode 100644 packages/start-client-core/src/startOptionList.ts create mode 100644 packages/start-client-core/src/tests/createStartModule.test-d.ts create mode 100644 packages/start-client-core/src/tests/moduleMiddlewareConsumers.test-d.ts create mode 100644 packages/start-client-core/src/tests/startModuleConditionalEntry.test-d.ts create mode 100644 packages/start-client-core/src/tests/startModuleConditionalOptions.test-d.ts create mode 100644 packages/start-client-core/src/tests/startModuleContextProjectionEdges.test-d.ts create mode 100644 packages/start-client-core/src/tests/startModuleContextScaling.test-d.ts create mode 100644 packages/start-client-core/src/tests/startModuleGlobalOwner.test-d.ts create mode 100644 packages/start-client-core/src/tests/startModuleImpossibleRequirement.test-d.ts create mode 100644 packages/start-client-core/src/tests/startModuleInstallation.test-d.ts create mode 100644 packages/start-client-core/src/tests/startModuleRequirementFreeArray.test-d.ts create mode 100644 packages/start-client-core/src/tests/startModuleUnionRequirement.test-d.ts create mode 100644 packages/start-client-core/src/tests/startModuleUnscopedConsumer.test-d.ts create mode 100644 packages/start-client-core/src/tests/startModuleWidenedGlobalDedupe.test-d.ts create mode 100644 packages/start-client-core/tests/createStartModule.test.ts create mode 100644 packages/start-plugin-core/src/start-router-plugin/client-route-tree.ts create mode 100644 packages/start-plugin-core/src/start-router-plugin/route-module-directories.ts create mode 100644 packages/start-plugin-core/tests/route-module-start-build.test.ts create mode 100644 packages/vue-router/src/route-module-internal.ts create mode 100644 packages/vue-router/src/routeModule.ts create mode 100644 packages/vue-router/tests/blocker-server.test.tsx create mode 100644 packages/vue-router/tests/navigate-options-parity.test.tsx create mode 100644 packages/vue-start/src/route-module-internal.ts create mode 100644 scripts/benchmarks/route-modules/measure.mjs create mode 100644 scripts/benchmarks/route-modules/measure.test.mjs create mode 100644 scripts/benchmarks/route-modules/scoped-match.mjs create mode 100644 scripts/benchmarks/route-modules/start-types.mjs diff --git a/.changeset/clever-buttons-push.md b/.changeset/clever-buttons-push.md new file mode 100644 index 0000000000..d9fb637d2d --- /dev/null +++ b/.changeset/clever-buttons-push.md @@ -0,0 +1,12 @@ +--- +'@tanstack/router-cli': minor +'@tanstack/router-plugin': minor +'@tanstack/router-vite-plugin': minor +'@tanstack/start-plugin-core': minor +'@tanstack/react-start': minor +'@tanstack/solid-start': minor +'@tanstack/vue-start': minor +'@tanstack/react-start-rsc': minor +--- + +Require Node.js 22.22.0 or later for Router and Start build tooling. Upgrade file watching to Chokidar 6. diff --git a/.changeset/itchy-chairs-melt.md b/.changeset/itchy-chairs-melt.md new file mode 100644 index 0000000000..2ea0e1e902 --- /dev/null +++ b/.changeset/itchy-chairs-melt.md @@ -0,0 +1,5 @@ +--- +'@tanstack/router-plugin': patch +--- + +Preserve JSX and TypeScript syntax when splitting route components wrapped in calls such as React `memo` and Vue `defineComponent`. diff --git a/.changeset/route-modules-devtools.md b/.changeset/route-modules-devtools.md new file mode 100644 index 0000000000..e60fb2c888 --- /dev/null +++ b/.changeset/route-modules-devtools.md @@ -0,0 +1,5 @@ +--- +'@tanstack/router-devtools-core': minor +--- + +Experimental: The router devtools show route modules. Each mounted module's routes form a collapsible group, nested where the module is mounted, and a filter narrows the route tree to one module. A module panel shows the module's mount path, parent module, routes with their module-local and final paths, and active matches. Matches carry a module badge, and match details show the module, the local path and the final path. diff --git a/.changeset/route-modules-eslint.md b/.changeset/route-modules-eslint.md new file mode 100644 index 0000000000..14f07932fc --- /dev/null +++ b/.changeset/route-modules-eslint.md @@ -0,0 +1,5 @@ +--- +'@tanstack/eslint-plugin-router': minor +--- + +Experimental: Add the `route-module-imports` rule, enabled in the recommended configs: files of a route module must import routing and Start APIs from the module's generated route scope. The rule only applies to packages that declare `tanstack.router.module`. diff --git a/.changeset/route-modules-generator.md b/.changeset/route-modules-generator.md new file mode 100644 index 0000000000..08d84ef3bb --- /dev/null +++ b/.changeset/route-modules-generator.md @@ -0,0 +1,7 @@ +--- +'@tanstack/router-generator': minor +'@tanstack/router-cli': minor +'@tanstack/router-plugin': minor +--- + +Experimental: Generate route modules. A package that declares `tanstack.router.module` in its `package.json` gets qualified route ids (`:`), a generated route scope (`routeScope.gen.ts`, with one namespace file per included or used module), a public contract (`routeContract.gen.ts`, exported as `./route-types` after the package's own declaration build), a runtime entry (`routeModule.gen.ts`, exported as `./route-module`) and a topology manifest (`.tanstack/route-module.json`) for includers. Module identity is the package name. Applications and modules mount modules with the `routeModules` option: `includes` chooses the host route and mount path of each module and `uses` references modules mounted elsewhere. An application installs a module several times by including it once per installation, each named with `as`; every installation gets its own namespace and route ids, and a module that uses it links to the installation mounted above it. A module mounted under path params gets a namespace typed with them in its includers; the generator rejects a module that uses it without being mounted below those params, and rejects mounts whose full paths collide. `tsr generate` emits the module files. Packages emit and check declarations with their own TypeScript projects; Nx or similar workspace tooling reruns generation and compilation in dependency order when sources, configuration or provider artifacts change. `tsr watch` retains its standalone route-directory and configuration watching. The bundler plugin compiles, code-splits and hot-updates mounted module routes, including every installation of a module installed several times. Applications without route modules generate the same output as before. diff --git a/.changeset/route-modules-router.md b/.changeset/route-modules-router.md new file mode 100644 index 0000000000..b8f42ebc86 --- /dev/null +++ b/.changeset/route-modules-router.md @@ -0,0 +1,8 @@ +--- +'@tanstack/router-core': minor +'@tanstack/react-router': minor +'@tanstack/solid-router': minor +'@tanstack/vue-router': minor +--- + +Experimental: Add route modules: workspace packages that own a subtree of file-based routes and are mounted into applications or other modules. The generated host route tree mounts a module root under a host route and type-checks the mount: a static mount path, no required search params above the module, the router context the module requires, and serializable lifecycle results in server-rendered applications. Module routes, links, navigation, redirects and hooks come from the module's generated route scope and take module-local paths and qualified route ids wherever the module is mounted; `getRouteApi` and route-bound hooks resolve the nearest installation. A module mounted under path params keeps the params of the current location in its own links, and `HostedRouter` types the links of code that mounts it. A module installed several times gets one copy of its routes per installation, with ids `#:/…`; module-local ids, destinations, redirects and not-found errors resolve to the installation of the route that uses them, and `InstallationRoutesById` types an installation's routes. Matches of module routes carry `localRouteId`, the installation-independent id, and the generated `isScopedMatch` guard narrows whole-router matches to the routes of a scope. Applications without route modules are unaffected. diff --git a/.changeset/route-modules-start.md b/.changeset/route-modules-start.md new file mode 100644 index 0000000000..fea474bcd0 --- /dev/null +++ b/.changeset/route-modules-start.md @@ -0,0 +1,9 @@ +--- +'@tanstack/start-client-core': minor +'@tanstack/start-plugin-core': minor +'@tanstack/react-start': minor +'@tanstack/solid-start': minor +'@tanstack/vue-start': minor +--- + +Experimental: Support route modules in TanStack Start. A module that depends on the Start framework package gets `createServerFn`, `createMiddleware` and `createStartModule` in its generated route scope. It declares the context it requires from the application by augmenting `StartModuleRequirements`, keyed by its package name, with `requestContext` and `functionContext`; the declaration emits no JavaScript. A module that contributes serialization adapters or middleware exports a fragment created with `createStartModule` from `start.ts`, and applications install the generated list with `createStart(() => ({ extends: startModules }))`; the application's own entries run first and entries are deduplicated by identity. The generated `startModules.gen.ts` type-checks that the application installs every fragment and provides the required context. The Start plugin lists module routes in the routes manifest, selects the providers' client tree views for client builds, discovers prerenderable module pages and extends import protection to installed module packages. diff --git a/.changeset/router-core-extensions.md b/.changeset/router-core-extensions.md new file mode 100644 index 0000000000..eb667c584e --- /dev/null +++ b/.changeset/router-core-extensions.md @@ -0,0 +1,10 @@ +--- +'@tanstack/router-core': minor +'@tanstack/react-router': minor +'@tanstack/solid-router': minor +'@tanstack/vue-router': minor +'@tanstack/start-client-core': patch +'@tanstack/react-start-rsc': patch +--- + +Declarations emitted by packages that use the router now import router types from the framework package, for example `@tanstack/react-router`, instead of `@tanstack/router-core`, which pnpm does not let those packages resolve unless they depend on it. The framework packages augment the new `@tanstack/router-core/extensions` entry instead of `@tanstack/router-core`, and the router packages export router-core's `Route` interface, which `createFileRoute` returns, as `RouteCore`. Existing augmentations of `@tanstack/router-core` keep working. diff --git a/.changeset/salty-dryers-move.md b/.changeset/salty-dryers-move.md new file mode 100644 index 0000000000..d9612eaf47 --- /dev/null +++ b/.changeset/salty-dryers-move.md @@ -0,0 +1,5 @@ +--- +'@tanstack/router-generator': patch +--- + +Use the package name as the route module's identity. Remove the experimental custom module ID override so generated routes and consumer scopes use the same identity. diff --git a/.changeset/start-modules-many-fragments.md b/.changeset/start-modules-many-fragments.md new file mode 100644 index 0000000000..99e34250c2 --- /dev/null +++ b/.changeset/start-modules-many-fragments.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-client-core': patch +--- + +Type-check `createStart(() => ({ extends: startModules }))` for applications that install the Start fragments of many route modules. With about 50 fragments, TypeScript reported "Type instantiation is excessively deep and possibly infinite". diff --git a/.changeset/start-rsbuild-compiler-esm-resolve.md b/.changeset/start-rsbuild-compiler-esm-resolve.md new file mode 100644 index 0000000000..fe04e03124 --- /dev/null +++ b/.changeset/start-rsbuild-compiler-esm-resolve.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +Rsbuild: the Start compiler resolves the imports it follows, such as those of a module that re-exports `createServerFn`, as ES module imports. It used the loader's base resolver, so packages whose exports only list `import`, like `@tanstack/react-start`, failed to resolve and the build stopped. diff --git a/.changeset/true-houses-behave.md b/.changeset/true-houses-behave.md new file mode 100644 index 0000000000..722483ca4d --- /dev/null +++ b/.changeset/true-houses-behave.md @@ -0,0 +1,16 @@ +--- +'@tanstack/router-core': patch +'@tanstack/react-router': patch +'@tanstack/solid-router': patch +'@tanstack/vue-router': patch +'@tanstack/router-devtools-core': patch +'@tanstack/router-cli': patch +'@tanstack/router-generator': patch +'@tanstack/start-client-core': patch +'@tanstack/start-plugin-core': patch +'@tanstack/react-start': patch +'@tanstack/solid-start': patch +'@tanstack/vue-start': patch +--- + +Correct experimental route-module installation identity, scope ownership, framework navigation parity, and Start context validation. Generate independently tree-shakeable scope APIs and explicit dependency namespaces, and keep module composition helpers internal. Use ordinary TypeScript declaration builds, refresh route topology during development, and include provider routes in Start client pruning and prerender discovery. diff --git a/benchmarks/client-nav/link-performance/cases.ts b/benchmarks/client-nav/link-performance/cases.ts index a25eac563b..9203d3ff35 100644 --- a/benchmarks/client-nav/link-performance/cases.ts +++ b/benchmarks/client-nav/link-performance/cases.ts @@ -25,6 +25,12 @@ export const LINK_CASES = [ label: 'Relative targets', description: 'Parent and child targets inherit current params and search.', }, + { + id: 'route-bound', + label: 'Route-bound relative targets', + description: + 'The relative case through Route.Link, which resolves from its route.', + }, { id: 'middleware', label: 'Search middleware chain', @@ -103,6 +109,7 @@ export function sourceSearch( switch (caseId) { case 'location-updaters': case 'relative': + case 'route-bound': case 'middleware': case 'active': return { @@ -157,6 +164,7 @@ function url(pathname: string, search: Partial = {}, hash = '') { function sourcePath(caseId: LinkCaseId, stateIndex: number) { switch (caseId) { case 'relative': + case 'route-bound': return `/teams/team-${stateIndex}/item-${stateIndex}` case 'numeric-params': return `/numbers/${stateIndex}` @@ -210,6 +218,7 @@ function expectedHref(caseId: LinkCaseId, stateIndex: number, index: number) { `source-${stateIndex}-link-${index % 5}`, ) case 'relative': + case 'route-bound': return url( index % 2 === 0 ? `/teams/team-${stateIndex}` diff --git a/benchmarks/client-nav/link-performance/src/workload.tsx b/benchmarks/client-nav/link-performance/src/workload.tsx index 8315b85b8b..62107e525c 100644 --- a/benchmarks/client-nav/link-performance/src/workload.tsx +++ b/benchmarks/client-nav/link-performance/src/workload.tsx @@ -238,6 +238,7 @@ function sourceOptions(caseId: LinkCaseId, stateIndex: number) { } switch (caseId) { case 'relative': + case 'route-bound': return linkOptions({ ...common, to: '/teams/$teamId/$itemId', @@ -386,6 +387,15 @@ function measuredLink( search /> ) + case 'route-bound': + return ( + + ) case 'middleware': return ( [!WARNING] +> This rule supports [route modules](../routing/route-modules.md), which are experimental. The rule may change with them in any release. + +Files of a [route module](../routing/route-modules.md) must import routing and Start APIs from the module's generated route scope (`routeScope.gen.ts`), which types them against the module's own routes. The same APIs imported from `@tanstack/react-router`, `@tanstack/solid-router`, `@tanstack/vue-router` or the framework's Start package are typed against an application the module does not know. + +The rule reports value imports of these APIs from the framework packages: + +- Route constructors and routing APIs: `createFileRoute`, `Link`, `createLink`, `linkOptions`, `Navigate`, `useNavigate`, `redirect`, `MatchRoute`, `useMatchRoute`, `useRouter`, `getRouteApi`, `useMatch`, `useMatches`, `useParentMatches`, `useChildMatches`, `useLoaderData`, `useLoaderDeps`, `useSearch`, `useParams`, `useRouteContext`, `useLocation` and `useRouterState`. +- Root route constructors (`createRootRoute`, `createRootRouteWithContext`): a module root is created with `createModuleRoot`. +- Start APIs of Start route modules: `createServerFn` and `createStartModule`. + +The rule only applies to files whose nearest `package.json` declares `tanstack.router.module`. It ignores generated files and type-only imports. + +## Rule Details + +Examples of **incorrect** code for this rule: + +```tsx title="packages/products/src/routes/$productId.tsx" +/* eslint "@tanstack/router/route-module-imports": "error" */ +import { createFileRoute, Link } from '@tanstack/react-router' + +export const Route = createFileRoute('@acme/products:/$productId')({ + component: () => All products, +}) +``` + +Examples of **correct** code for this rule: + +```tsx title="packages/products/src/routes/$productId.tsx" +/* eslint "@tanstack/router/route-module-imports": "error" */ +import { Outlet } from '@tanstack/react-router' +import { createFileRoute, Link } from '../routeScope.gen' + +export const Route = createFileRoute('@acme/products:/$productId')({ + component: () => All products, +}) +``` + +## Attributes + +- [x] ✅ Recommended +- [ ] 🔧 Fixable diff --git a/docs/router/routing/route-modules.md b/docs/router/routing/route-modules.md new file mode 100644 index 0000000000..a510731b55 --- /dev/null +++ b/docs/router/routing/route-modules.md @@ -0,0 +1,445 @@ +--- +id: route-modules +title: Route Modules (Experimental) +--- + +> [!WARNING] +> Route modules are experimental. Their APIs, generated files, `package.json` fields, CLI commands and TanStack Start integration may change in any release, including minor and patch releases. Pin your TanStack Router versions when you adopt them. + +A **route module** is a workspace package that owns a subtree of file-based routes. Applications, and other route modules, mount it into their route tree. Each module is generated and type-checked by its own package, and links into it stay fully typed wherever it is mounted. + +Use route modules when several teams or applications share routes in a monorepo: + +- A feature (a product catalog, an account area) lives in its own package with its own routes, loaders and components. +- Applications choose where a module is mounted, so the same module can appear at `/shop/products` in one app and at `/catalog` in another. +- A module only sees what it declares: its own routes, the modules it mounts or uses, and the router context it requires. + +Route modules are opt-in. Applications without them are generated exactly as before. + +> [!NOTE] +> Route modules require TypeScript, and the generator rejects `disableTypes`. Lazy route files (`createLazyFileRoute`, `.lazy.tsx`) are not supported in route modules: [automatic code splitting](../guide/automatic-code-splitting.md) splits module routes like any other route. + +## Declaring a route module + +A package is a route module when its `package.json` has a `tanstack.router.module` field: + +```json title="packages/products/package.json" +{ + "name": "@acme/products", + "type": "module", + "tanstack": { + "router": { + "module": {} + } + }, + "exports": { + "./route-types": { + "types": "./.tanstack/types/src/routeContract.gen.d.ts" + }, + "./route-module": { + "types": "./.tanstack/types/src/routeModule.gen.d.ts", + "default": "./src/routeModule.gen.ts" + }, + "./package.json": "./package.json" + }, + "scripts": { + "generate": "tsr generate", + "build:types": "node -e \"require('node:fs').rmSync('.tanstack/types', { recursive: true, force: true })\" && tsc -p tsconfig.route-types.json", + "check": "tsc --noEmit" + }, + "dependencies": { + "@tanstack/react-router": "^1.0.0" + }, + "devDependencies": { + "@tanstack/router-cli": "^1.0.0", + "typescript": "^5.6.0" + } +} +``` + +The module's identity is its `package.json` name. Generated route IDs use that +name as their prefix, for example `@acme/products:/$productId`. + +The module field accepts these options. `true` is the same as `{}`. + +| Option | Description | +| ---------- | -------------------------------------------------------------------------- | +| `includes` | Modules installed into this module's tree, with includer-owned mount paths | +| `uses` | Explicit references to other modules' routes; defaults to an empty list | + +The two `exports` entries are the module's public surface: + +- `./route-types` points to the emitted declarations of the module's contract: its router type and route ids. Consumers only read these declarations, never the module's sources. +- `./route-module` points to the module's runtime entry, which includers mount. Applications compile it from source like any other workspace code. + +Route ids and module-local paths are part of this public surface. Consumers reference them in `getRouteApi`, `useMatch`, namespaced links and `isScopedMatch`, so renaming or moving a route file is a breaking change for them, like renaming an export. + +The package build must verify that its exported declarations and their imports resolve in consumers. Build and check declarations before publishing, including a consumer with `skipLibCheck: false` and no provider source files. + +Declarations are emitted with a `tsconfig.route-types.json` that you own: + +```json title="packages/products/tsconfig.route-types.json" +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "emitDeclarationOnly": true, + "noEmitOnError": true, + "declarationMap": true, + "rootDir": ".", + "outDir": ".tanstack/types" + }, + "include": ["src"] +} +``` + +## Authoring module routes + +Module routes live in the module's routes directory as usual. Two things differ from an application: + +1. **Import routing APIs from the generated scope.** `src/routeScope.gen.ts` exports `createFileRoute`, `createModuleRoot`, `Link`, `useNavigate`, `redirect`, the hooks and `useRouter`, all typed against the module's own routes. Imports from `@tanstack/react-router` would be typed against an application the module does not know. The [`route-module-imports`](../eslint/route-module-imports.md) lint rule enforces this. +2. **Route ids are qualified with the module id.** The generator writes them, exactly as it writes ids in an application. + +```tsx title="packages/products/src/routes/$productId.tsx" +import { createFileRoute } from '../routeScope.gen' + +export const Route = createFileRoute('@acme/products:/$productId')({ + loader: ({ params, context }) => + context.productsApi.getProduct(params.productId), + component: ProductPage, +}) + +function ProductPage() { + const product = Route.useLoaderData() + return ( +
+

{product.name}

+ {/* Module-local path: resolves to wherever the module is mounted. */} + All products +
+ ) +} +``` + +Paths inside a module are **module-local**. `to="/"` is the module's index route, whether the module is mounted at `/products` or `/shop/catalog`. + +### The module root and its requirements + +`src/routes/__root.tsx` creates the module root with `createModuleRoot`. Its type parameter is the router context the module requires from wherever it is mounted: + +```tsx title="packages/products/src/routes/__root.tsx" +import { Outlet } from '@tanstack/react-router' +import { createModuleRoot } from '../routeScope.gen' +import type { ProductsApi } from '../api' + +export const Route = createModuleRoot<{ productsApi: ProductsApi }>()({ + component: () => , +}) +``` + +The module type-checks on its own against this requirement. When an application mounts the module, the mount fails to type-check unless the parent route provides that context. It does not matter whether the context comes from the application's root, `createRouter({ context })`, or a layout's `beforeLoad`. + +Shared libraries with nominal types, such as a `QueryClient` class, must resolve to one declaration in the whole workspace. Make them `peerDependencies` of route modules. + +## Mounting modules + +An application mounts modules with the `routeModules` option. It is accepted by `tsr.config.json`, the bundler plugin and the `router` option of TanStack Start: + +```json title="apps/web/tsr.config.json" +{ + "routesDirectory": "./src/routes", + "generatedRouteTree": "./src/routeTree.gen.ts", + "routeModules": { + "includes": [ + { "module": "@acme/storefront", "at": "/shop" }, + { + "module": "@acme/account", + "parent": "/_authenticated", + "at": "/account" + } + ] + } +} +``` + +A route module mounts other modules with `includes` in its own `package.json`. A string entry mounts the module under the root without adding a path segment. Use an object to select the mount and installation name: + +| Field | Description | +| -------- | ------------------------------------------------------------------------------ | +| `module` | Package name of the module, declared as a dependency of the includer | +| `parent` | Host route ID; defaults to the root | +| `at` | Static path below the parent; defaults to no additional segment | +| `as` | Generated namespace and installation name, including for a single installation | + +The includer owns the URL. Relative and leading-slash `at` spellings are normalized as paths below the selected parent before collision checks. + +Mounting follows these rules, and the generator or the type checker reports every violation: + +- **The host chain has no required search params.** Links carry the path params of the current location over, but not its search params, so a module's own links could not provide them. Routes above a module may have path params (see [Mounting under path params](#mounting-under-path-params)). `at` itself must be a static path. +- **The parent provides the context the module root requires.** +- **A module is mounted once per route tree,** unless an application names several installations of it (see [Installing a module several times](#installing-a-module-several-times)). Several includers can depend on the same module, but only one of them can mount it. The others use it. +- **Each package declares its direct providers.** Declare the modules it mounts or uses as dependencies. Generated declarations reference those providers' symbolic contracts; each provider resolves its own dependencies from its package. An application need not list every transitive module as a direct dependency. The package declaration build reports unresolved imports. +- **Full paths must not collide** with routes of the includer or other modules. + +Generated code performs the mounting and emits the corresponding type checks. Mounting helpers are internal; author composition through configuration and generated APIs. + +### Mounting under path params + +A module can be mounted below routes with path params, for example once per organization: + +```json title="apps/web/tsr.config.json" +{ + "routeModules": { + "includes": [ + { "module": "@acme/team", "parent": "/orgs/$orgId", "at": "/team" } + ] + } +} +``` + +The module never sees `orgId` in its types: its own links keep the path params of the current location, which always has them while the module renders. At runtime `useParams()` and `match.params` contain them, like the final paths in `match.fullPath`. Whatever an installation needs about its host comes through the context its root requires, which the host route provides: + +```tsx title="apps/web/src/routes/orgs.$orgId.tsx" +export const Route = createFileRoute('/orgs/$orgId')({ + beforeLoad: ({ params }) => ({ org: { id: params.orgId } }), +}) +``` + +The includer's namespace for the module is typed from where it is mounted, so links from outside the module pass the host params: + +```tsx + + Ada + +``` + +A module that only uses a module mounted under path params fills them from the current location, so the generator requires it to be mounted below the routes that declare them. It reports a using module mounted elsewhere, naming both modules and the routes with the params. + +### Installing a module several times + +An application can install a module more than once, for example the same settings per organization and per person. Every include of the module names its installation with `as`: + +```json title="apps/web/tsr.config.json" +{ + "routeModules": { + "includes": [ + { + "module": "@acme/settings", + "parent": "/orgs/$orgId", + "at": "/settings", + "as": "orgSettings" + }, + { + "module": "@acme/settings", + "parent": "/people/$personId", + "at": "/settings", + "as": "personSettings" + } + ] + } +} +``` + +Each installation gets its own routes, with ids `#:` such as `@acme/settings#orgSettings:/profile`. They share the module's components, loaders and code-split chunks, and a hot update reaches every installation. An explicitly named single installation uses this identity too. Only an unnamed single installation uses `:`, so adding another installation does not rename an existing named one. + +The module's code does not change. Its route ids, `Route` APIs, links, navigation and redirects resolve to the installation it renders under. Configure each installation through the context the module root requires: each host route provides its own. + +Outside the module, address one installation at a time: + +- **Through its namespace.** The application gets a namespace per installation, named by `as`. It takes the module's local paths and ids and addresses that installation: `orgSettings.Link`, `orgSettings.getRouteApi('@acme/settings:/profile')`. +- **By its installation ids.** `useMatch({ from: '@acme/settings#orgSettings:/profile' })`. The module's plain ids (`@acme/settings:/profile`) are type errors outside the module. + +A module that uses a module installed several times links to the installation whose host routes are above its own mount: a billing module mounted below `/orgs/$orgId` links to `orgSettings`. The generator reports a using module with no such installation, or with several. + +Only applications install a module several times. A module installed several times cannot itself install other modules. + +## Linking across modules + +Every module the includer mounts or uses gets a **namespace** in its `routeScope.gen.ts`. A namespace has the same APIs as the module's own scope, typed against that module's local paths: + +```tsx title="apps/web/src/routes/index.tsx" +import { createFileRoute } from '@tanstack/react-router' +import { products } from '../routeScope.gen' + +export const Route = createFileRoute('/')({ + component: () => ( + + Pick of the day + + ), +}) +``` + +The namespace name is the last segment of the package name in camel case. Choose another with `as` when two modules would get the same name. + +In `includes`, `as` also names the installation. In a `uses` reference, `{ "module": "@acme/products", "as": "catalog" }` only renames the local namespace; it does not create or rename an installation. + +An application cannot link to a module route by its final path: `` is a type error. This keeps modules independent of where they are mounted. + +APIs that take a route id work across modules with qualified ids: + +```tsx +const productApi = getRouteApi('@acme/products:/$productId') +const match = useMatch({ from: '@acme/products:/$productId' }) +``` + +A module can reference another module's routes without mounting it by listing it in `uses`: + +```json title="packages/account/package.json" +{ + "name": "@acme/account", + "tanstack": { + "router": { + "module": { "uses": ["@acme/products"] } + } + }, + "dependencies": { "@acme/products": "workspace:*" } +} +``` + +The application must install that provider somewhere, directly or through an include. The generator reports a reference whose provider is not installed. A dependency used only for schemas, utilities or server functions needs no `uses` entry and imposes no route-installation requirement. Dependencies are resolved as packages; they are not automatically discovered as route consumers. An include already exposes its installed subtree, so it need not be repeated in `uses`. + +Namespaces are read-only generated ESM namespaces. Each API and namespace can be tree-shaken independently: using `products.Link` should not retain every routing helper. Do not mutate namespace members. + +Options created by a scope retain their ownership. Reuse `products.linkOptions(...)` with the products APIs; passing them to a conflicting scope is rejected instead of silently changing their destination. + +### Match identity and whole-router state + +`match.routeId` is the final installed ID. Module matches also carry `match.localRouteId`, for example `@acme/settings:/profile` even when the final ID is `@acme/settings#orgSettings:/profile`. Ordinary application matches omit this property. + +Scoped `useMatches` keeps the whole active match chain, including foreign host routes. Those foreign matches retain common metadata, but their loader data and context are `unknown`. Narrow membership before using module-specific data. `isScopedMatch` accepts every route of the modules in the scope, identified by their module id, including routes a module adds later: + +```ts +import { isScopedMatch, useMatches } from '../routeScope.gen' + +for (const match of useMatches()) { + if ( + isScopedMatch(match) && + match.localRouteId === '@acme/settings:/profile' + ) { + const profile = match.loaderData + } +} +``` + +Known-route APIs such as `useMatch({ from: ... })` retain precise types. Constructing `getRouteApi(...)` at module scope is valid; its hooks resolve the nearest installation when called in a component. An ambiguous lookup outside a matching context needs an explicit installation. + +The generated scope also includes `useLinkProps`, `useBlocker` and targeted `notFound`. `useBlocker` observes whole-router transitions. Import `Outlet` from the framework package. `Navigate` navigates on mount and on option changes across React, Solid and Vue; it does not navigate during SSR. + +Generated validation type aliases bind the module's router while retaining the corresponding framework type's other argument order and defaults: + +- `ValidateLinkOptions` and `ValidateLinkOptionsArray` +- `ValidateNavigateOptions` and `ValidateNavigateOptionsArray` +- `ValidateRedirectOptions` and `ValidateRedirectOptionsArray` +- `ValidateUseSearchOptions` and `ValidateUseParamsOptions` +- `ValidateId`, `ValidateFromPath`, `ValidateToPath`, `ValidateSearch` and `ValidateParams` + +> [!NOTE] +> A module match's `fullPath` is the final installed path pattern and is typed as `string`; the paths accepted by its generated APIs are module-local. Read `match.pathname` for the current concrete URL. Module source route objects are shared definitions, so use the current match when you need an installation's identity or path. + +## Generated files + +| File | Purpose | +| ------------------------------------ | ---------------------------------------------------------------------------- | +| `src/routeTree.gen.ts` | Full route tree and type maps | +| `src/routeTree.gen.client.ts` | Provider-owned client view used by Start's client bundlers | +| `src/routeScope.gen.ts` | Module-scoped exports and namespace re-exports | +| `src/routeScope.gen.namespace.ts` | Independent ESM exports for a referenced installation | +| `src/routeContract.gen.ts` | Public route contract, exposed as `./route-types` after declaration emission | +| `src/routeModule.gen.ts` | Runtime entry exposed as `./route-module` | +| `src/startModules.gen.ts` | Start contributions and erased application contract checks | +| `.tanstack/route-module.json` | Portable route/source topology, installation metadata and client-view paths | +| `.tanstack/types/` | Example declaration output directory, owned by the package build | + +The generated files sit beside the configured route tree. Do not edit them. They can be committed or ignored; generation must precede any task that reads them. Add `.tanstack` to `.gitignore`. + +Package runtime exports must retain every referenced route source or compiled JavaScript file, generated namespace/client-tree file and topology manifest. Declaration exports must retain their complete reachable declaration graph. Keep framework versions compatible with the generated source's internal implementation imports. + +## Building and watching + +Router generates routes; the package's TypeScript build emits and checks declarations; a task runner schedules, caches and reruns those operations when inputs change. + +| Command | Responsibility | +| ---------------------------------- | --------------------------------------------------------------- | +| `tsr generate` | Generate the package's route topology, source APIs and manifest | +| `tsc -p tsconfig.route-types.json` | Emit declarations with the package's own compiler project | +| `tsc --noEmit` | Check a package's sources against current provider declarations | + +A declaration build should clean its configured output first, because TypeScript does not remove declarations for deleted source files. The example `build:types` script above owns that cleanup. A failed build must fail the task graph. Router has no declaration-status file, compiler wrapper or stale-output health check. + +Order work by the route-package dependency graph: + +1. Generate providers before packages that include or reference them. +2. Emit provider declarations before emitting or checking consumers. +3. Regenerate packages that include or reference a provider after its topology changes; recheck consumers after contract changes. +4. Build the application from the resulting artifacts. + +An implementation edit can produce identical declaration bytes. Whether that suppresses a consumer task depends on the task runner's cache policy, not Router. + +Router CLI and bundler plugins require Node.js 22.22.0 or later. + +### Nx and Turborepo + +Expose ordinary `generate`, `build:types` and `check` package scripts. For example, an Nx graph can start with these uncached targets: + +```json title="nx.json" +{ + "targetDefaults": { + "generate": { "cache": false, "dependsOn": ["^generate"] }, + "build:types": { + "cache": false, + "dependsOn": ["generate", "^build:types"] + }, + "check": { + "cache": false, + "dependsOn": ["generate", "^build:types"] + } + } +} +``` + +The equivalent Turborepo tasks use `dependsOn: ["^generate"]` for generation and `dependsOn: ["generate", "^build:types"]` for declaration builds/checks. Use the task runner's watch mode to rerun these finite tasks in dependency order. + +Configure that workflow to react to route source and generation-config changes, module `package.json` metadata, and Start-entry additions or removals beside the configured route tree. A provider topology change must regenerate packages that include or reference it. Provider declaration changes must rebuild or recheck their consumers. Include custom generated directories and TypeScript project inputs in the task configuration. + +`tsr watch` remains available for standalone route-directory and configuration watching. Route-module development uses the workspace task runner to watch the complete build graph and invoke `tsr generate`. + +When enabling caches, model every source/configuration and provider artifact a task reads. Restore every generated scope/namespace/client-tree file, the topology manifest, the complete declaration output/maps and the intended runtime output. Match custom generation directories and declaration `outDir` settings. A task whose inputs include ignored generated workloads must model those inputs or remain uncached. Cache hits must restore the same usable package as a successful uncached run. + +The application bundler compiles module runtime source and handles code splitting/HMR. It also consumes provider manifests; it does not generate into provider packages. Run the workspace task watcher alongside the application dev server so provider artifacts stay current. + +## TanStack Start + +Route modules work in TanStack Start applications. A module can declare type-only Start context requirements and can separately contribute an executable **Start fragment** that the application installs. See [Route Modules in TanStack Start](../../start/framework/react/guide/route-modules.md). + +A module without Start features can be mounted in a Start application as is. When the application renders on the server, the mount checks that the loader and `beforeLoad` results of the module's routes can be serialized. + +## Migrating from a router package + +The `router-monorepo-*` examples share one router between packages: a router package builds the route tree from routes defined in feature packages and registers it globally. To move a feature package to a route module: + +1. Move its routes into `src/routes` of the package and add `tanstack.router.module` and the `exports` entries to its `package.json`. +2. Replace route constructors and routing APIs imported from the framework package with imports from `./routeScope.gen`. Create the root with `createModuleRoot` and declare the context the routes need. +3. Replace absolute paths that pointed into other features, in the features and in the application, with their namespaces. The type checker reports each one: + + ```tsx + // Before + + // After + + ``` + +4. Mount the module from the application with `routeModules.includes`, and remove the hand-written route tree assembly and the shared `Register` augmentation. +5. Declare cross-module route references in `uses`. Add generation, ordinary declaration-build and source-check tasks in dependency order. + +## Limitations + +- Route modules require TypeScript and emit declarations with the module's own compiler. TypeScript 5.6 or newer is supported. +- Consumer declarations use `moduleResolution: "bundler"`. `node16`/`nodenext` compatibility is not supported by this workflow. +- A module is mounted at a static path, under a host chain without required search params. Only applications install a module more than once, and a module installed several times cannot install other modules. +- A module that another module installs cannot link to a module the application installs several times. +- Lazy route files are not supported in route modules. +- `Register.server.requestContext` of TanStack Start stays global to the application. +- Mixed code-based and file-based route-module composition is a future TODO. Use generated file-based composition for now; the mounting and scope factories remain internal. Existing physical/virtual file-routing configuration remains supported. +- Router instances own their runtime state, including request-specific SSR state; shared module definitions must not store user context. diff --git a/docs/start/config.json b/docs/start/config.json index 36af0e6e0d..df475b821d 100644 --- a/docs/start/config.json +++ b/docs/start/config.json @@ -90,6 +90,10 @@ "label": "Import Protection", "to": "framework/react/guide/import-protection" }, + { + "label": "Route Modules (Experimental)", + "to": "framework/react/guide/route-modules" + }, { "label": "Path Aliases", "to": "framework/react/guide/path-aliases" diff --git a/docs/start/framework/react/guide/route-modules.md b/docs/start/framework/react/guide/route-modules.md new file mode 100644 index 0000000000..fd953445ab --- /dev/null +++ b/docs/start/framework/react/guide/route-modules.md @@ -0,0 +1,196 @@ +--- +id: route-modules +title: Route Modules (Experimental) +--- + +Start build tooling requires Node.js 22.22.0 or later. + +> [!WARNING] +> Route modules are experimental. Their APIs, generated files and build integration may change in any release, including minor and patch releases. Pin your TanStack Start versions when you adopt them. + +[Route modules](../../../../router/routing/route-modules.md) are packages that own a subtree of file-based routes. A module that depends on `@tanstack/react-start` also receives generated Start APIs. The same design applies to Solid and Vue through their framework packages. + +```json title="packages/catalog/package.json" +{ + "name": "@acme/catalog", + "tanstack": { "router": { "module": {} } }, + "dependencies": { + "@tanstack/react-router": "^1.0.0", + "@tanstack/react-start": "^1.0.0" + } +} +``` + +Use `createServerFn`, `createMiddleware` and `createStartModule` from the module's generated `routeScope.gen.ts`. These APIs select the module's requirements and serialization types. The application continues to import its APIs from `@tanstack/react-start`. + +## Declare required context with types + +Requirements describe context that the host must provide. Augment `StartModuleRequirements` in the framework package, keyed by the module's package name: + +```ts title="packages/catalog/src/requirements.ts" +export type { StartModuleRequirements } from '@tanstack/react-start' + +interface User { + id: string +} + +declare module '@tanstack/react-start' { + interface StartModuleRequirements { + '@acme/catalog': { + requestContext: { user: User } + functionContext: { permissions: Array } + } + } +} +``` + +The two fields are optional and independent: + +- `requestContext` is available during requests and server functions. The application can supply it through `handler.fetch` context or request middleware. +- `functionContext` is required by server functions and their server middleware. Global function middleware can provide it, in addition to the request context already available at that stage. It does not describe client middleware or context sent over the transport. + +The generated application assertion selects installed route modules. An application's unrelated dependency does not impose a requirement merely because TypeScript loads its types. Installing a module more than once reuses its package's requirement. Explicitly consuming module middleware also checks its requirements at that consumer. + +These declarations emit no JavaScript and need no runtime marker, middleware entry or empty Start fragment. They are separate from `Register.server.requestContext`, which describes context supplied by the host. + +### Preserve requirements in published declarations + +Consumers must reach the augmentation through the package's declaration exports. Keep it in a `.ts` source file, preserve the framework registry re-export above, and add a type-only re-export to the module's root route: + +```tsx title="packages/catalog/src/routes/__root.tsx" +import { Outlet } from '@tanstack/react-router' +import { createModuleRoot } from '../routeScope.gen' +export type {} from '../requirements' + +export const Route = createModuleRoot()({ + component: () => , +}) +``` + +The emitted route contract reaches the root declaration, which reaches `requirements.d.ts`. Both re-exports are erased from JavaScript. A standalone `.d.ts` that is never referenced by an exported declaration is insufficient; ordinary declaration emission does not copy arbitrary input declaration files. An unused empty type import may also disappear during emission. + +Verify the published package from a consumer that has only its declarations, with `skipLibCheck: false`. Requirements can also be authored in a shared package, provided the module's public declaration graph retains the augmentation and its framework registry reference. + +## Author middleware and server functions + +The generated middleware factory knows the module's requirements without reading the inferred type of its Start fragment: + +```ts title="packages/catalog/src/api.ts" +import { createMiddleware, createServerFn } from './routeScope.gen' + +const pricing = createMiddleware({ type: 'function' }).server( + ({ context, next }) => + next({ + context: { + currency: context.permissions.includes('europe') ? 'EUR' : 'USD', + }, + }), +) + +export const getProduct = createServerFn() + .middleware([pricing]) + .validator((id: string) => id) + .handler(({ data, context }) => ({ + id: data, + shopper: context.user.id, + currency: context.currency, + })) +``` + +Middleware attached to a server function runs for that function. This is the appropriate place for feature-specific authorization or pricing logic. Global contributions run for the whole application. + +Context validation follows middleware execution order, including nested middleware and replacement of existing context properties. A later incompatible replacement cannot be hidden by an earlier valid provider. The checks also apply when module middleware is consumed from an application or another module. Use concrete compatible context types; an `any` value cannot establish the required contract. + +## Contribute application-wide behavior + +A Start fragment contains executable contributions: `serializationAdapters`, `requestMiddleware` and `functionMiddleware`. Create one only when the module contributes such behavior. Put it in `start.ts` or `start.tsx` next to the configured generated route tree, and export it as `start`: + +```ts title="packages/catalog/src/start.ts" +import { createStartModule } from './routeScope.gen' +import { moneyAdapter } from './money' + +export const start = createStartModule(() => ({ + serializationAdapters: [moneyAdapter], +})) +``` + +A fragment cannot set application-wide options such as `defaultSsr` or `serverFns`. Its factory is independent of the application's Start instance. Loader and `beforeLoad` results, as well as server-function results, are checked for serialization with the appropriate adapters. + +| Need | Author it with | +| ---------------------------------------------------------- | ----------------------------------------------------- | +| Context supplied by the host | `StartModuleRequirements` augmentation | +| Logic used by particular server functions | Generated `createMiddleware` and `.middleware([...])` | +| Middleware or adapters installed for the whole application | `createStartModule(() => ({ ... }))` | + +Shared authentication normally belongs in the host. Modules can require the resulting user context instead of contributing duplicate authentication middleware. Runtime deduplication recognizes the same middleware or adapter object; two separately created objects still both run. + +Run `tsr generate` after adding or removing the fragment file. During development, configure Nx or another workspace task runner to rerun generation and dependent builds/checks for these changes. Include the fragment beside the configured route tree in the task inputs, including when that directory is outside `src`. + +## Install modules in an application + +Choose mount paths in the application configuration: + +```ts title="apps/web/vite.config.ts" +import { defineConfig } from 'vite' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' + +export default defineConfig({ + plugins: [ + tanstackStart({ + router: { + routeModules: { + includes: [{ module: '@acme/catalog', at: '/shop' }], + }, + }, + }), + ], +}) +``` + +For modules with executable fragments, install the generated list in the application's Start instance: + +```ts title="apps/web/src/start.ts" +import { createMiddleware, createStart } from '@tanstack/react-start' +import { startModules } from './startModules.gen' + +const user = createMiddleware().server(({ next }) => + next({ context: { user: { id: 'ada' } } }), +) +const permissions = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { permissions: ['europe'] } }), +) + +export const startInstance = createStart(() => ({ + extends: startModules, + requestMiddleware: [user], + functionMiddleware: [permissions], +})) +``` + +The generated type check validates the requirements of every installed module, including modules without a fragment. A requirements-only module needs no `extends` entry. Executable contributions still need installation through `extends: startModules`. + +Validation needs concrete tuples and rejects a required entry or provider that may be absent. It checks request and function lists independently: conditionally supplying the same field through one list or the other may work at runtime but cannot establish the contract. Keep a common provider in an unconditional tuple entry when the requirement depends on that relationship. + +Prefer named context properties for module requirements. A `Record` does not establish that a required `user` property exists. Optional properties and index signatures may leave earlier context values untouched. The validator keeps those possibilities; repairing one named property may not prove a broad index contract again. + +Application entries run first, followed by contributed entries. Entries are deduplicated by object identity, preserving their first position. If an application explicitly places a contributed middleware earlier in its own list, that is its execution position. Compatible host context providers can satisfy a requirement; they need not come from a particular authentication package. Subsequent middleware must preserve the context promised to each consumer. + +Without an application `start.ts`, requirements-only modules are checked against the default Start configuration, including registered `handler.fetch` context. Create an entry exporting `startInstance` when the application needs its own middleware or must install executable fragments. Executable fragments require that entry and `extends: startModules`; mounting them into an application without the framework's Start package is rejected. + +## Build and publish modules + +Use the [ordinary package build workflow](../../../../router/routing/route-modules.md#building-and-watching): route generation, the package's TypeScript declaration build, and consumer source checks in dependency order. Nx, Turborepo or another task runner owns scheduling, caching and rerunning tasks when sources, package metadata or provider artifacts change. Router does not run TypeScript, publish declaration health records or detect whether a task runner restored stale declarations. + +Publish the generated runtime entry, its referenced route sources or compiled JavaScript, the generated client tree views, the topology manifest and the complete reachable declaration output. Include all of them in cached task outputs when caching is enabled. A package build must remove obsolete declaration output and verify its export paths and dependencies. + +## Client and server builds + +Vite and Rsbuild use the same rules across React, Solid and Vue: + +- Module sources participate in normal code splitting, Start compilation and [import protection](./import-protection.md). +- Client trees remove a route whose only recorded option is `server` when all of its children are also removed. Mixed UI/server routes and ancestors needed by surviving children remain. Server trees preserve the endpoints. +- Providers generate their own client tree views. The host bundler selects those views for client imports; it does not write files into provider packages or filter routes in the browser. +- Automatic prerender discovery includes eligible mounted module pages, including nested and named installations. Dynamic installed URLs and handler-only endpoints are excluded. Explicit pages, disabling discovery, filters and basepaths continue to apply. + +> [!NOTE] +> In a module installed several times, loader and `beforeLoad` redirects resolve from the matched route. Redirects returned through a component's `useServerFn` do not yet capture its nearest installation. Return data and navigate with the module's `useNavigate` in that case. diff --git a/e2e/react-router/route-modules/.gitignore b/e2e/react-router/route-modules/.gitignore new file mode 100644 index 0000000000..2634249916 --- /dev/null +++ b/e2e/react-router/route-modules/.gitignore @@ -0,0 +1,8 @@ +# Generated by the route generator and TypeScript; the tests generate +# them from a clean copy of the packages. +**/routeTree.gen.ts +**/routeScope.gen.ts +**/routeContract.gen.ts +**/routeModule.gen.ts +**/routeScope.gen.*.ts +**/routeTree.gen.*.ts diff --git a/e2e/react-router/route-modules/e2e-dev/devtools.spec.ts b/e2e/react-router/route-modules/e2e-dev/devtools.spec.ts new file mode 100644 index 0000000000..6fb9e0a0ea --- /dev/null +++ b/e2e/react-router/route-modules/e2e-dev/devtools.spec.ts @@ -0,0 +1,46 @@ +import { expect, test } from '@playwright/test' + +test('the router devtools group the routes of mounted modules', async ({ + page, +}) => { + await page.goto('/shop/products/7') + await page + .getByRole('button', { name: 'Open TanStack Router Devtools' }) + .click() + + // A module's group sits inside the group of the module that mounts it. + const outer = page.getByRole('group', { + name: 'Route module @route-modules/storefront', + }) + await expect(outer).toBeVisible() + await expect( + outer.getByRole('group', { name: 'Route module @route-modules/products' }), + ).toBeVisible() + + await page + .getByRole('button', { + name: 'Open module details for @route-modules/products', + }) + .first() + .click() + const details = page.getByRole('region', { name: 'Module details' }) + await expect(details).toContainText('Mount path:/shop/products') + await expect(details).toContainText('Parent module:@route-modules/storefront') +}) + +test('the router devtools show each installation of a module installed twice', async ({ + page, +}) => { + await page.goto('/people/ada/settings') + await page + .getByRole('button', { name: 'Open TanStack Router Devtools' }) + .click() + + for (const installation of ['orgSettings', 'personSettings']) { + await expect( + page.getByRole('group', { + name: `Route module @route-modules/settings#${installation}`, + }), + ).toBeVisible() + } +}) diff --git a/e2e/react-router/route-modules/e2e-dev/hmr.spec.ts b/e2e/react-router/route-modules/e2e-dev/hmr.spec.ts new file mode 100644 index 0000000000..7eacbaaa9e --- /dev/null +++ b/e2e/react-router/route-modules/e2e-dev/hmr.spec.ts @@ -0,0 +1,109 @@ +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { expect } from '@playwright/test' +import { createHmrFileEditor, test } from '@tanstack/router-e2e-utils' +import { Generator, getConfig } from '@tanstack/router-generator' + +const packages = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../packages', +) +const products = path.join(packages, 'products') + +const editor = createHmrFileEditor({ + rootDir: products, + files: { + product: 'src/routes/$productId.tsx', + }, +}) +const settingsEditor = createHmrFileEditor({ + rootDir: path.join(packages, 'settings'), + files: { + profile: 'src/routes/profile.tsx', + }, +}) + +test.afterEach(async () => { + await editor.restoreFiles() + await settingsEditor.restoreFiles() +}) + +test('editing a module route file hot-updates it in the application', async ({ + page, +}) => { + await page.goto('/shop/products/7') + await expect(page.getByRole('heading')).toHaveText('Product 7') + await page.evaluate(() => { + ;(window as any).__beforeHmr = true + }) + + await editor.replaceText( + 'product', + '

{product.name}

', + '

Updated {product.name}

', + ) + await expect(page.getByRole('heading')).toHaveText('Updated Product 7') + // A hot update, not a reload: page state survives. + expect(await page.evaluate(() => (window as any).__beforeHmr)).toBe(true) + await expect(page).toHaveURL('/shop/products/7?tab=specs') +}) + +test('editing a route of a module installed twice hot-updates every installation', async ({ + page, +}) => { + await page.goto('/people/ada/settings/profile') + await expect(page.getByRole('heading', { name: 'Profile' })).toBeVisible() + await page.evaluate(() => { + ;(window as any).__beforeHmr = true + }) + + await settingsEditor.replaceText( + 'profile', + '

Profile

', + '

Updated profile

', + ) + await expect( + page.getByRole('heading', { name: 'Updated profile' }), + ).toBeVisible() + + // The installation of the organizations runs the updated route too. + await page.evaluate(() => + (window as any).__TSR_ROUTER__.navigate({ + to: '/orgs/acme/settings/profile', + }), + ) + await expect(page.getByTestId('profile-kind')).toHaveText('organization') + await expect( + page.getByRole('heading', { name: 'Updated profile' }), + ).toBeVisible() + // Hot updates, not reloads: page state survives. + expect(await page.evaluate(() => (window as any).__beforeHmr)).toBe(true) +}) + +test('a route added to a module is served after the module regenerates', async ({ + page, +}) => { + const newRoute = path.join(products, 'src/routes/brands.tsx') + const { writeFile, rm } = await import('node:fs/promises') + await writeFile( + newRoute, + `import { createFileRoute } from '../routeScope.gen' + +export const Route = createFileRoute('@route-modules/products:/brands')({ + component: () =>

Brands

, +}) +`, + ) + try { + // A workspace task reruns the provider's generation after the edit. + const config = getConfig({ disableLogging: true }, products) + await new Generator({ config, root: products }).run() + + await page.goto('/shop/products/brands') + await expect(page.getByRole('heading')).toHaveText('Brands') + } finally { + await rm(newRoute) + const config = getConfig({ disableLogging: true }, products) + await new Generator({ config, root: products }).run() + } +}) diff --git a/e2e/react-router/route-modules/e2e/app.spec.ts b/e2e/react-router/route-modules/e2e/app.spec.ts new file mode 100644 index 0000000000..51afb3509d --- /dev/null +++ b/e2e/react-router/route-modules/e2e/app.spec.ts @@ -0,0 +1,126 @@ +import { expect, test } from '@playwright/test' + +test('the application links into mounted modules by namespace', async ({ + page, +}) => { + await page.goto('/') + await expect(page.getByRole('link', { name: 'Cart' })).toHaveAttribute( + 'href', + '/shop/cart', + ) + await page.getByRole('link', { name: 'Pick of the day' }).click() + await expect(page).toHaveURL('/shop/products/home-pick?tab=specs') + await expect(page.getByRole('heading')).toHaveText('Product home-pick') +}) + +test('module-local links resolve inside the module', async ({ page }) => { + await page.goto('/shop/products/3') + await page.getByRole('link', { name: 'All products' }).click() + await expect(page).toHaveURL('/shop/products') + await expect(page.getByRole('link', { name: 'Product 1' })).toHaveAttribute( + 'href', + '/shop/products/1', + ) +}) + +test('a module mounted under a layout gets its context and links into other modules', async ({ + page, +}) => { + await page.goto('/account') + await expect(page.getByRole('heading')).toHaveText('u-1') + await expect( + page.getByRole('link', { name: 'Last viewed product' }), + ).toHaveAttribute('href', '/shop/products/last-viewed?tab=reviews') + + await page.getByRole('link', { name: 'Last order' }).click() + await expect(page).toHaveURL('/account/orders/1') + await page.getByRole('button', { name: 'Ordered product' }).click() + await expect(page).toHaveURL('/shop/products/p-1?tab=specs') + await expect(page.getByRole('heading')).toHaveText('Product p-1') +}) + +test('module routes are code-split from the application bundle', async ({ + page, +}) => { + const scripts: Array = [] + page.on('request', (request) => { + if (request.resourceType() === 'script') { + scripts.push(new URL(request.url()).pathname) + } + }) + await page.goto('/') + await expect(page.getByRole('link', { name: 'Home' })).toBeVisible() + expect(scripts.some((script) => script.includes('_productId'))).toBe(false) + + await page.getByRole('link', { name: 'Pick of the day' }).click() + await expect(page.getByRole('heading')).toHaveText('Product home-pick') + expect(scripts.some((script) => script.includes('_productId'))).toBe(true) +}) + +test('a module mounted under path params links within its organization', async ({ + page, +}) => { + await page.goto('/') + // The application passes the path params above the module. + await page.getByRole('link', { name: 'Acme team' }).click() + await expect(page).toHaveURL('/orgs/acme/team') + await expect( + page.getByRole('heading', { name: 'Team of ACME' }), + ).toBeVisible() + + // Module-local links keep the path params of the current location. + await page.getByRole('link', { name: 'grace' }).click() + await expect(page).toHaveURL('/orgs/acme/team/members/grace') + await expect( + page.getByRole('heading', { name: 'grace at ACME' }), + ).toBeVisible() + await page.getByRole('link', { name: 'All members' }).click() + await expect(page).toHaveURL('/orgs/acme/team') +}) + +test('a module that uses a module mounted under path params fills them from the location', async ({ + page, +}) => { + await page.goto('/orgs/globex/billing') + const contact = page.getByRole('link', { name: 'Billing contact' }) + await expect(contact).toHaveAttribute('href', '/orgs/globex/team/members/ada') + await contact.click() + await expect( + page.getByRole('heading', { name: 'ada at GLOBEX' }), + ).toBeVisible() +}) + +test('a module installed twice renders each installation with its own owner', async ({ + page, +}) => { + await page.goto('/') + await page.getByRole('link', { name: 'Globex settings' }).click() + await expect(page).toHaveURL('/orgs/globex/settings') + await expect( + page.getByRole('heading', { name: 'Settings of GLOBEX' }), + ).toBeVisible() + // Module-local links stay in the installation they render under. + await page.getByRole('link', { name: 'Profile' }).click() + await expect(page).toHaveURL('/orgs/globex/settings/profile') + await expect(page.getByTestId('profile-kind')).toHaveText('organization') + + await page.goto('/') + await page.getByRole('link', { name: "Ada's profile" }).click() + await expect(page).toHaveURL('/people/ada/settings/profile') + await expect( + page.getByRole('heading', { name: 'Settings of Ada' }), + ).toBeVisible() + await expect(page.getByTestId('profile-kind')).toHaveText('person') + await page.getByRole('link', { name: 'All settings' }).click() + await expect(page).toHaveURL('/people/ada/settings') +}) + +test('a module that uses a module installed twice links to the installation above it', async ({ + page, +}) => { + await page.goto('/orgs/globex/billing') + const profile = page.getByRole('link', { name: 'Organization profile' }) + await expect(profile).toHaveAttribute('href', '/orgs/globex/settings/profile') + await profile.click() + await expect(page.getByTestId('profile-kind')).toHaveText('organization') +}) diff --git a/e2e/react-router/route-modules/e2e/scope-parity.spec.ts b/e2e/react-router/route-modules/e2e/scope-parity.spec.ts new file mode 100644 index 0000000000..1e762a0d6c --- /dev/null +++ b/e2e/react-router/route-modules/e2e/scope-parity.spec.ts @@ -0,0 +1,215 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' + +for (const base of ['/orgs/globex/settings', '/people/ada/settings']) { + test(`RouteApi and custom links resolve ${base}`, async ({ page }) => { + await page.goto(`${base}/profile`) + await expect( + page.getByRole('link', { name: 'API members' }), + ).toHaveAttribute('href', `${base}/members`) + await expect( + page.getByRole('link', { name: 'Custom members' }), + ).toHaveAttribute('href', `${base}/members`) + expect( + await page + .getByRole('link', { name: 'API members' }) + .getAttribute('_module'), + ).toBeNull() + expect( + await page + .getByRole('link', { name: 'Custom members' }) + .getAttribute('_module'), + ).toBeNull() + const hostId = base.split('/')[2]! + const hostParams = base.startsWith('/orgs/') + ? { orgId: hostId } + : base.startsWith('/people/') + ? { personId: hostId } + : { userId: hostId } + await expect(page.getByTestId('runtime-params')).toHaveText( + JSON.stringify(hostParams), + ) + await expect(page.getByText('PROFILE_MATCH', { exact: true })).toBeVisible() + await expect(page.getByText('MEMBERS_MATCH', { exact: true })).toHaveCount( + 0, + ) + await page.getByRole('link', { name: 'API members' }).click() + await expect(page.getByText('MEMBERS_PAGE')).toBeVisible() + await expect(page).toHaveURL(`${base}/members`) + }) + + test(`useLinkProps navigates within the document under ${base}`, async ({ + page, + }) => { + await page.goto(`${base}/profile`) + await expect( + page.getByRole('link', { name: 'Custom members' }), + ).toBeVisible() + const documentRequests: Array = [] + page.on('request', (request) => { + if ( + request.isNavigationRequest() && + request.frame() === page.mainFrame() + ) { + documentRequests.push(request.url()) + } + }) + await page.getByRole('link', { name: 'Custom members' }).click() + await expect(page.getByText('MEMBERS_PAGE')).toBeVisible() + await expect(page).toHaveURL(`${base}/members`) + expect(documentRequests).toEqual([]) + }) + + test(`RouteApi navigation resolves ${base}`, async ({ page }) => { + await page.goto(`${base}/profile`) + await page.getByRole('button', { name: 'Navigate members' }).click() + await expect(page.getByText('MEMBERS_PAGE')).toBeVisible() + await expect(page).toHaveURL(`${base}/members`) + }) + + test(`Navigate captures installation under ${base}`, async ({ page }) => { + await page.goto(`${base}/forward`) + await expect(page.getByText('MEMBERS_PAGE')).toBeVisible() + await expect(page).toHaveURL(`${base}/members`) + }) + + test.describe(`component notFound under ${base}`, () => { + test.use({ + // React reports the deliberately thrown value before the boundary handles it. + whitelistErrors: [ + /^\{routeId: @route-modules\/settings:, isNotFound: true\}$/, + ], + }) + test('reaches the module boundary', async ({ page }) => { + await page.goto(`${base}/missing`) + await expect(page.getByText('MODULE_NOT_FOUND')).toBeVisible() + }) + }) + for (const button of ['Route up', 'Explicit from home']) { + test(`${button} uses the route origin under ${base}`, async ({ page }) => { + await page.goto(`${base}/profile`) + await page.getByRole('button', { name: button, exact: true }).click() + await expect(page).toHaveURL(base) + await expect( + page.getByRole('link', { name: 'Profile', exact: true }), + ).toHaveAttribute('href', `${base}/profile`) + }) + } + + test(`scoped router view builds and navigates under ${base}`, async ({ + page, + }) => { + await page.goto(`${base}/profile`) + await expect(page.getByTestId('scoped-href')).toHaveText(`${base}/members`) + await page.getByRole('button', { name: 'Router members' }).click() + await expect(page).toHaveURL(`${base}/members`) + const profile = page.getByRole('link', { name: 'Profile', exact: true }) + await expect(profile).toHaveAttribute('href', `${base}/profile`) + await profile.click() + await expect(page).toHaveURL(`${base}/profile`) + }) + + test(`Route.Link keeps the installation under ${base}`, async ({ page }) => { + await page.goto(`${base}/profile`) + const home = page.getByRole('link', { name: 'Route home', exact: true }) + await expect(home).toHaveAttribute('href', base) + await home.click() + await expect(page).toHaveURL(base) + await expect( + page.getByRole('link', { name: 'Profile', exact: true }), + ).toHaveAttribute('href', `${base}/profile`) + }) + + test(`scoped lifecycle redirects retain the installation under ${base}`, async ({ + page, + }) => { + await page.goto(`${base}/legacy`) + await expect(page).toHaveURL(`${base}/profile`) + await expect(page.getByText('PROFILE_MATCH', { exact: true })).toBeVisible() + }) + + test(`framework imports keep application coordinates inside ${base}`, async ({ + page, + }) => { + await page.goto(`${base}/profile`) + const host = page.getByRole('link', { name: 'Application host' }) + await expect(host).toHaveAttribute('href', '/orgs/9') + await host.click() + await expect(page).toHaveURL('/orgs/9') + }) +} + +test('a local Link resolves options already wrapped by the same local scope', async ({ + page, +}) => { + await page.goto('/orgs/7/settings/profile') + const members = page.getByRole('link', { + name: 'Deferred members', + exact: true, + }) + await expect(members).toHaveAttribute('href', '/orgs/7/settings/members') + await members.click() + await expect(page).toHaveURL('/orgs/7/settings/members') + await expect(page.getByText('MEMBERS_PAGE')).toBeVisible() +}) + +test('module observers and router views follow real installation changes', async ({ + page, +}) => { + await page.goto('/orgs/globex/settings/profile') + await expect(page.getByTestId('organization-profile')).toHaveText( + '@route-modules/settings#orgSettings:/profile', + ) + await expect(page.getByTestId('scoped-href')).toHaveText( + '/orgs/globex/settings/members', + ) + await page.getByRole('link', { name: 'API members' }).click() + await expect(page).toHaveURL('/orgs/globex/settings/members') + await page.getByRole('link', { name: 'Switch to person' }).click() + await expect(page).toHaveURL('/people/ada/settings/profile') + await expect(page.getByTestId('organization-profile')).toHaveText('none') + await expect(page.getByTestId('scoped-href')).toHaveText( + '/people/ada/settings/members', + ) + await page.getByRole('link', { name: 'Switch to organization' }).click() + await expect(page).toHaveURL('/orgs/globex/settings/profile') + await expect(page.getByRole('link', { name: 'API members' })).toHaveAttribute( + 'href', + '/orgs/globex/settings/members', + ) + const readObserved = () => + page.evaluate( + () => + ( + window as Window & { + observedModuleMatches: Array + } + ).observedModuleMatches, + ) + await expect + .poll(readObserved) + .toContain('@route-modules/settings#personSettings:/profile') + const observed = await readObserved() + expect(observed).toContain('@route-modules/settings#orgSettings:/profile') + expect(observed).not.toContain(undefined) +}) + +test('singleton scoped redirects and namespaced search input survive generation', async ({ + page, +}) => { + await page.goto('/shop/products/legacy') + await expect( + page.getByRole('heading', { name: 'Product 42', exact: true }), + ).toBeVisible() + expect(new URL(page.url()).pathname).toBe('/shop/products/42') + await expect(page.getByText('Dimensions, materials and care.')).toBeVisible() + + await page.goto('/shop') + const compare = page.getByRole('link', { name: 'Compare', exact: true }) + await expect(compare).toHaveAttribute( + 'href', + '/shop/products/compare?ids=%5B%221%22%2C%222%22%5D', + ) + await compare.click() + await expect(page.getByText('Comparing products 1 and 2.')).toBeVisible() +}) diff --git a/e2e/react-router/route-modules/package.json b/e2e/react-router/route-modules/package.json new file mode 100644 index 0000000000..926b6a727a --- /dev/null +++ b/e2e/react-router/route-modules/package.json @@ -0,0 +1,24 @@ +{ + "name": "tanstack-router-e2e-react-route-modules", + "private": true, + "type": "module", + "scripts": { + "test:e2e": "node scripts/prepare.mjs && pnpm --filter @route-modules/web generate && vitest run && playwright test --project=chromium && playwright test --config playwright.dev.config.ts --project=chromium", + "test:types": "node scripts/prepare.mjs && pnpm --filter @route-modules/web generate && pnpm --filter @route-modules/web check:contracts" + }, + "devDependencies": { + "@playwright/test": "^1.61.0", + "@tanstack/router-e2e-utils": "workspace:^", + "@tanstack/router-generator": "workspace:^", + "@types/node": "catalog:", + "vitest": "catalog:", + "vite-plugin-solid": "^2.11.11" + }, + "nx": { + "implicitDependencies": [ + "@tanstack/react-start", + "@tanstack/solid-start", + "@tanstack/vue-start" + ] + } +} diff --git a/e2e/react-router/route-modules/packages/account/package.json b/e2e/react-router/route-modules/packages/account/package.json new file mode 100644 index 0000000000..f9e2d889d9 --- /dev/null +++ b/e2e/react-router/route-modules/packages/account/package.json @@ -0,0 +1,43 @@ +{ + "name": "@route-modules/account", + "private": true, + "type": "module", + "tanstack": { + "router": { + "module": { + "uses": [ + "@route-modules/products" + ] + } + } + }, + "exports": { + "./route-types": { + "types": "./.tanstack/types/src/routeContract.gen.d.ts" + }, + "./route-module": { + "types": "./.tanstack/types/src/routeModule.gen.d.ts", + "default": "./src/routeModule.gen.ts" + }, + "./package.json": "./package.json", + "./scope": { + "types": "./.tanstack/types/src/routeScope.gen.d.ts", + "default": "./src/routeScope.gen.ts" + } + }, + "scripts": { + "generate": "tsr generate", + "emit-types": "node -e \"require('node:fs').rmSync('.tanstack/types',{recursive:true,force:true})\" && tsc -p tsconfig.route-types.json", + "check": "tsc --noEmit" + }, + "dependencies": { + "@route-modules/products": "workspace:*", + "@tanstack/react-router": "workspace:^", + "react": "^19.0.0" + }, + "devDependencies": { + "@tanstack/router-cli": "workspace:^", + "@tanstack/router-core": "workspace:^", + "@types/react": "^19.0.8" + } +} diff --git a/e2e/react-router/route-modules/packages/account/src/routes/__root.tsx b/e2e/react-router/route-modules/packages/account/src/routes/__root.tsx new file mode 100644 index 0000000000..6941c2546a --- /dev/null +++ b/e2e/react-router/route-modules/packages/account/src/routes/__root.tsx @@ -0,0 +1,25 @@ +import { Outlet } from '@tanstack/react-router' +import { createModuleRoot } from '../routeScope.gen' + +// Account pages need the signed-in user, provided by whatever host route the +// application mounts the module under. +export const Route = createModuleRoot<{ user: { id: string } }>()({ + component: AccountRoom, +}) + +// The module's region: a room tagged with its package and where it is +// mounted (with the URL it resolved to when the mount path has params). +function AccountRoom() { + const pathname = Route.useMatch({ select: (match) => match.pathname }) + return ( +
+

+ @route-modules/account {Route.fullPath} + {pathname !== Route.fullPath && ( + → {pathname} + )} +

+ +
+ ) +} diff --git a/e2e/react-router/route-modules/packages/account/src/routes/index.tsx b/e2e/react-router/route-modules/packages/account/src/routes/index.tsx new file mode 100644 index 0000000000..bfaa88f9de --- /dev/null +++ b/e2e/react-router/route-modules/packages/account/src/routes/index.tsx @@ -0,0 +1,35 @@ +import { Link, createFileRoute, products } from '../routeScope.gen' + +export const Route = createFileRoute('@route-modules/account:/')({ + component: AccountHome, +}) + +function AccountHome() { + const { user } = Route.useRouteContext() + return ( +
+

{user.id}

+

+ Signed in. Your orders and what you looked at last. +

+
    +
  • + + Last order + + Order 1 +
  • +
  • + + Last viewed product + + Opens its reviews +
  • +
+
+ ) +} diff --git a/e2e/react-router/route-modules/packages/account/src/routes/orders.$orderId.tsx b/e2e/react-router/route-modules/packages/account/src/routes/orders.$orderId.tsx new file mode 100644 index 0000000000..21387d26d0 --- /dev/null +++ b/e2e/react-router/route-modules/packages/account/src/routes/orders.$orderId.tsx @@ -0,0 +1,44 @@ +import { createFileRoute, getRouteApi, products } from '../routeScope.gen' + +const productRoute = getRouteApi('@route-modules/products:/$productId') + +export const Route = createFileRoute('@route-modules/account:/orders/$orderId')( + { + loader: ({ params }) => ({ orderId: params.orderId, productId: 'p-1' }), + component: OrderPage, + }, +) + +function OrderPage() { + const order = Route.useLoaderData() + const navigateToProduct = products.useNavigate() + return ( +
+

{order.orderId}

+
+
Status
+
Delivered
+
Product
+
+ {order.productId} +
+
+ +
+ ) +} + +export function useOrderedProduct() { + return productRoute.useLoaderData() +} diff --git a/e2e/react-router/route-modules/packages/account/tsconfig.json b/e2e/react-router/route-modules/packages/account/tsconfig.json new file mode 100644 index 0000000000..1de72ddc24 --- /dev/null +++ b/e2e/react-router/route-modules/packages/account/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "skipLibCheck": true, + "noEmit": true, + "types": [] + }, + "include": ["src"] +} diff --git a/e2e/react-router/route-modules/packages/account/tsconfig.route-types.json b/e2e/react-router/route-modules/packages/account/tsconfig.route-types.json new file mode 100644 index 0000000000..0c9aec3caf --- /dev/null +++ b/e2e/react-router/route-modules/packages/account/tsconfig.route-types.json @@ -0,0 +1,13 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "emitDeclarationOnly": true, + "noEmitOnError": true, + "declarationMap": true, + "rootDir": ".", + "outDir": ".tanstack/types" + }, + "include": ["src"] +} diff --git a/e2e/react-router/route-modules/packages/billing/package.json b/e2e/react-router/route-modules/packages/billing/package.json new file mode 100644 index 0000000000..cbba643a5a --- /dev/null +++ b/e2e/react-router/route-modules/packages/billing/package.json @@ -0,0 +1,41 @@ +{ + "name": "@route-modules/billing", + "private": true, + "type": "module", + "tanstack": { + "router": { + "module": { + "uses": [ + "@route-modules/settings", + "@route-modules/team" + ] + } + } + }, + "exports": { + "./route-types": { + "types": "./.tanstack/types/src/routeContract.gen.d.ts" + }, + "./route-module": { + "types": "./.tanstack/types/src/routeModule.gen.d.ts", + "default": "./src/routeModule.gen.ts" + }, + "./package.json": "./package.json" + }, + "scripts": { + "generate": "tsr generate", + "emit-types": "node -e \"require('node:fs').rmSync('.tanstack/types',{recursive:true,force:true})\" && tsc -p tsconfig.route-types.json", + "check": "tsc --noEmit" + }, + "dependencies": { + "@route-modules/settings": "workspace:*", + "@route-modules/team": "workspace:*", + "@tanstack/react-router": "workspace:^", + "react": "^19.0.0" + }, + "devDependencies": { + "@tanstack/router-cli": "workspace:^", + "@tanstack/router-core": "workspace:^", + "@types/react": "^19.0.8" + } +} diff --git a/e2e/react-router/route-modules/packages/billing/src/routes/__root.tsx b/e2e/react-router/route-modules/packages/billing/src/routes/__root.tsx new file mode 100644 index 0000000000..59673b7586 --- /dev/null +++ b/e2e/react-router/route-modules/packages/billing/src/routes/__root.tsx @@ -0,0 +1,23 @@ +import { Outlet } from '@tanstack/react-router' +import { createModuleRoot } from '../routeScope.gen' + +export const Route = createModuleRoot()({ + component: BillingRoom, +}) + +// The module's region: a room tagged with its package and where it is +// mounted (with the URL it resolved to when the mount path has params). +function BillingRoom() { + const pathname = Route.useMatch({ select: (match) => match.pathname }) + return ( +
+

+ @route-modules/billing {Route.fullPath} + {pathname !== Route.fullPath && ( + → {pathname} + )} +

+ +
+ ) +} diff --git a/e2e/react-router/route-modules/packages/billing/src/routes/index.tsx b/e2e/react-router/route-modules/packages/billing/src/routes/index.tsx new file mode 100644 index 0000000000..78087ff2c0 --- /dev/null +++ b/e2e/react-router/route-modules/packages/billing/src/routes/index.tsx @@ -0,0 +1,29 @@ +import { createFileRoute, settings, team } from '../routeScope.gen' + +export const Route = createFileRoute('@route-modules/billing:/')({ + component: Billing, +}) + +function Billing() { + return ( +
+

Billing

+
+
Plan
+
Team, billed monthly
+
Seats
+
2
+
+ {/* Billing uses the team without mounting it: the organization comes + from the current location, below the same route as the team. */} +
+ + Billing contact + + {/* The settings are installed for organizations and for people: + billing links to the installation of its own organization. */} + Organization profile +
+
+ ) +} diff --git a/e2e/react-router/route-modules/packages/billing/tsconfig.json b/e2e/react-router/route-modules/packages/billing/tsconfig.json new file mode 100644 index 0000000000..1de72ddc24 --- /dev/null +++ b/e2e/react-router/route-modules/packages/billing/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "skipLibCheck": true, + "noEmit": true, + "types": [] + }, + "include": ["src"] +} diff --git a/e2e/react-router/route-modules/packages/billing/tsconfig.route-types.json b/e2e/react-router/route-modules/packages/billing/tsconfig.route-types.json new file mode 100644 index 0000000000..0c9aec3caf --- /dev/null +++ b/e2e/react-router/route-modules/packages/billing/tsconfig.route-types.json @@ -0,0 +1,13 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "emitDeclarationOnly": true, + "noEmitOnError": true, + "declarationMap": true, + "rootDir": ".", + "outDir": ".tanstack/types" + }, + "include": ["src"] +} diff --git a/e2e/react-router/route-modules/packages/products/package.json b/e2e/react-router/route-modules/packages/products/package.json new file mode 100644 index 0000000000..61b3b459fb --- /dev/null +++ b/e2e/react-router/route-modules/packages/products/package.json @@ -0,0 +1,43 @@ +{ + "name": "@route-modules/products", + "private": true, + "type": "module", + "tanstack": { + "router": { + "module": true + } + }, + "exports": { + "./route-types": { + "types": "./.tanstack/types/src/routeContract.gen.d.ts" + }, + "./route-module": { + "types": "./.tanstack/types/src/routeModule.gen.d.ts", + "default": "./src/routeModule.gen.ts" + }, + "./api": { + "types": "./.tanstack/types/src/api.d.ts", + "default": "./src/api.ts" + }, + "./package.json": "./package.json", + "./scope": { + "types": "./.tanstack/types/src/routeScope.gen.d.ts", + "default": "./src/routeScope.gen.ts" + } + }, + "scripts": { + "generate": "tsr generate", + "emit-types": "node -e \"require('node:fs').rmSync('.tanstack/types',{recursive:true,force:true})\" && tsc -p tsconfig.route-types.json", + "check": "tsc --noEmit" + }, + "dependencies": { + "@tanstack/react-router": "workspace:^", + "react": "^19.0.0", + "zod": "^4.4.3" + }, + "devDependencies": { + "@tanstack/router-cli": "workspace:^", + "@tanstack/router-core": "workspace:^", + "@types/react": "^19.0.8" + } +} diff --git a/e2e/react-router/route-modules/packages/products/src/api.ts b/e2e/react-router/route-modules/packages/products/src/api.ts new file mode 100644 index 0000000000..49b3c720f6 --- /dev/null +++ b/e2e/react-router/route-modules/packages/products/src/api.ts @@ -0,0 +1,12 @@ +export type Price = number & { readonly __brand: 'Price' } + +export interface Product { + id: string + name: string + price: Price +} + +export interface ProductsApi { + getProduct: (id: string) => Promise + listProducts: () => Promise> +} diff --git a/e2e/react-router/route-modules/packages/products/src/routes/$productId.tsx b/e2e/react-router/route-modules/packages/products/src/routes/$productId.tsx new file mode 100644 index 0000000000..4ee4cbe25b --- /dev/null +++ b/e2e/react-router/route-modules/packages/products/src/routes/$productId.tsx @@ -0,0 +1,49 @@ +import { createFileRoute } from '../routeScope.gen' +import { productSearchSchema } from '../schemas' + +export const Route = createFileRoute('@route-modules/products:/$productId')({ + validateSearch: productSearchSchema, + loader: ({ params, context }) => + context.productsApi.getProduct(params.productId), + component: ProductPage, +}) + +function ProductPage() { + const product = Route.useLoaderData() + const { tab } = Route.useSearch() + return ( +
+

{product.name}

+
+
Price
+
{product.price.toFixed(2)}
+
Product id
+
+ {product.id} +
+
+ +

+ {tab === 'specs' + ? 'Dimensions, materials and care.' + : 'What customers say about it.'} +

+ All products +
+ ) +} diff --git a/e2e/react-router/route-modules/packages/products/src/routes/__root.tsx b/e2e/react-router/route-modules/packages/products/src/routes/__root.tsx new file mode 100644 index 0000000000..dae776c4c9 --- /dev/null +++ b/e2e/react-router/route-modules/packages/products/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { Outlet } from '@tanstack/react-router' +import { createModuleRoot } from '../routeScope.gen' +import type { ProductsApi } from '../api' + +export const Route = createModuleRoot<{ productsApi: ProductsApi }>()({ + component: ProductsRoom, +}) + +// The module's region: a room tagged with its package and where it is +// mounted (with the URL it resolved to when the mount path has params). +function ProductsRoom() { + const pathname = Route.useMatch({ select: (match) => match.pathname }) + return ( +
+

+ @route-modules/products {Route.fullPath} + {pathname !== Route.fullPath && ( + → {pathname} + )} +

+ +
+ ) +} diff --git a/e2e/react-router/route-modules/packages/products/src/routes/_layout.tsx b/e2e/react-router/route-modules/packages/products/src/routes/_layout.tsx new file mode 100644 index 0000000000..2193644739 --- /dev/null +++ b/e2e/react-router/route-modules/packages/products/src/routes/_layout.tsx @@ -0,0 +1,10 @@ +import { Outlet } from '@tanstack/react-router' +import { createFileRoute } from '../routeScope.gen' + +export const Route = createFileRoute('@route-modules/products:/_layout')({ + component: () => ( +
+ +
+ ), +}) diff --git a/e2e/react-router/route-modules/packages/products/src/routes/_layout/deals.tsx b/e2e/react-router/route-modules/packages/products/src/routes/_layout/deals.tsx new file mode 100644 index 0000000000..4b557668c5 --- /dev/null +++ b/e2e/react-router/route-modules/packages/products/src/routes/_layout/deals.tsx @@ -0,0 +1,12 @@ +import { createFileRoute } from '../../routeScope.gen' + +export const Route = createFileRoute('@route-modules/products:/_layout/deals')({ + component: () => ( + <> +

Deals

+

+ Rendered through a pathless layout of the products module. +

+ + ), +}) diff --git a/e2e/react-router/route-modules/packages/products/src/routes/catalog.{-$category}.tsx b/e2e/react-router/route-modules/packages/products/src/routes/catalog.{-$category}.tsx new file mode 100644 index 0000000000..0afa1254c1 --- /dev/null +++ b/e2e/react-router/route-modules/packages/products/src/routes/catalog.{-$category}.tsx @@ -0,0 +1,12 @@ +import { createFileRoute } from '../routeScope.gen' + +export const Route = createFileRoute( + '@route-modules/products:/catalog/{-$category}', +)({ + component: () => ( + <> +

Catalog

+

The category segment of this path is optional.

+ + ), +}) diff --git a/e2e/react-router/route-modules/packages/products/src/routes/compare.tsx b/e2e/react-router/route-modules/packages/products/src/routes/compare.tsx new file mode 100644 index 0000000000..9c787a278d --- /dev/null +++ b/e2e/react-router/route-modules/packages/products/src/routes/compare.tsx @@ -0,0 +1,17 @@ +import { z } from 'zod' +import { createFileRoute } from '../routeScope.gen' + +export const Route = createFileRoute('@route-modules/products:/compare')({ + validateSearch: z.object({ ids: z.array(z.string()) }), + component: Compare, +}) + +function Compare() { + const { ids } = Route.useSearch() + return ( + <> +

Compare

+

Comparing products {ids.join(' and ')}.

+ + ) +} diff --git a/e2e/react-router/route-modules/packages/products/src/routes/files.$.tsx b/e2e/react-router/route-modules/packages/products/src/routes/files.$.tsx new file mode 100644 index 0000000000..aee6d73969 --- /dev/null +++ b/e2e/react-router/route-modules/packages/products/src/routes/files.$.tsx @@ -0,0 +1,10 @@ +import { createFileRoute } from '../routeScope.gen' + +export const Route = createFileRoute('@route-modules/products:/files/$')({ + component: () => ( + <> +

Files

+

Every path below files/ lands here.

+ + ), +}) diff --git a/e2e/react-router/route-modules/packages/products/src/routes/index.tsx b/e2e/react-router/route-modules/packages/products/src/routes/index.tsx new file mode 100644 index 0000000000..1f7c159a3f --- /dev/null +++ b/e2e/react-router/route-modules/packages/products/src/routes/index.tsx @@ -0,0 +1,22 @@ +import { Link, createFileRoute } from '../routeScope.gen' + +export const Route = createFileRoute('@route-modules/products:/')({ + loader: ({ context }) => context.productsApi.listProducts(), + component: ProductList, +}) + +function ProductList() { + const products = Route.useLoaderData() + return ( +
    + {products.map((product) => ( +
  • + + {product.name} + + {product.price.toFixed(2)} +
  • + ))} +
+ ) +} diff --git a/e2e/react-router/route-modules/packages/products/src/routes/legacy.tsx b/e2e/react-router/route-modules/packages/products/src/routes/legacy.tsx new file mode 100644 index 0000000000..cb4643dbb0 --- /dev/null +++ b/e2e/react-router/route-modules/packages/products/src/routes/legacy.tsx @@ -0,0 +1,10 @@ +import { createFileRoute, redirect } from '../routeScope.gen' +export const Route = createFileRoute('@route-modules/products:/legacy')({ + beforeLoad: () => { + throw redirect({ + to: '/$productId', + params: { productId: '42' }, + search: { tab: 'specs' }, + }) + }, +}) diff --git a/e2e/react-router/route-modules/packages/products/src/schemas.ts b/e2e/react-router/route-modules/packages/products/src/schemas.ts new file mode 100644 index 0000000000..9f7276a4fb --- /dev/null +++ b/e2e/react-router/route-modules/packages/products/src/schemas.ts @@ -0,0 +1,6 @@ +import { z } from 'zod' + +/** Search params of the product page: `tab` is optional when navigating. */ +export const productSearchSchema = z.object({ + tab: z.enum(['specs', 'reviews']).default('specs'), +}) diff --git a/e2e/react-router/route-modules/packages/products/tsconfig.json b/e2e/react-router/route-modules/packages/products/tsconfig.json new file mode 100644 index 0000000000..1de72ddc24 --- /dev/null +++ b/e2e/react-router/route-modules/packages/products/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "skipLibCheck": true, + "noEmit": true, + "types": [] + }, + "include": ["src"] +} diff --git a/e2e/react-router/route-modules/packages/products/tsconfig.route-types.json b/e2e/react-router/route-modules/packages/products/tsconfig.route-types.json new file mode 100644 index 0000000000..0c9aec3caf --- /dev/null +++ b/e2e/react-router/route-modules/packages/products/tsconfig.route-types.json @@ -0,0 +1,13 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "emitDeclarationOnly": true, + "noEmitOnError": true, + "declarationMap": true, + "rootDir": ".", + "outDir": ".tanstack/types" + }, + "include": ["src"] +} diff --git a/e2e/react-router/route-modules/packages/settings/package.json b/e2e/react-router/route-modules/packages/settings/package.json new file mode 100644 index 0000000000..435fe0a77c --- /dev/null +++ b/e2e/react-router/route-modules/packages/settings/package.json @@ -0,0 +1,38 @@ +{ + "name": "@route-modules/settings", + "private": true, + "type": "module", + "tanstack": { + "router": { + "module": true + } + }, + "exports": { + "./route-types": { + "types": "./.tanstack/types/src/routeContract.gen.d.ts" + }, + "./route-module": { + "types": "./.tanstack/types/src/routeModule.gen.d.ts", + "default": "./src/routeModule.gen.ts" + }, + "./package.json": "./package.json", + "./scope": { + "types": "./.tanstack/types/src/routeScope.gen.d.ts", + "default": "./src/routeScope.gen.ts" + } + }, + "scripts": { + "generate": "tsr generate", + "emit-types": "node -e \"require('node:fs').rmSync('.tanstack/types',{recursive:true,force:true})\" && tsc -p tsconfig.route-types.json", + "check": "tsc --noEmit" + }, + "dependencies": { + "@tanstack/react-router": "workspace:^", + "react": "^19.0.0" + }, + "devDependencies": { + "@tanstack/router-cli": "workspace:^", + "@tanstack/router-core": "workspace:^", + "@types/react": "^19.0.8" + } +} diff --git a/e2e/react-router/route-modules/packages/settings/src/routes/__root.tsx b/e2e/react-router/route-modules/packages/settings/src/routes/__root.tsx new file mode 100644 index 0000000000..ec3599af26 --- /dev/null +++ b/e2e/react-router/route-modules/packages/settings/src/routes/__root.tsx @@ -0,0 +1,44 @@ +import { Outlet } from '@tanstack/react-router' +import { createModuleRoot } from '../routeScope.gen' +import type { ComponentType } from 'react' + +/** Whose settings an installation shows, provided by its host route. */ +export interface Owner { + kind: 'organization' | 'person' + id: string + name: string +} + +// The application installs the settings twice: below `/orgs/$orgId` and +// below `/people/$personId`. Each host route provides its owner. +export const Route = createModuleRoot<{ + owner: Owner + onProfileMatch?: (routeId: string | undefined) => void + profileLinks?: ComponentType +}>()({ + component: SettingsRoom, + notFoundComponent: () =>

MODULE_NOT_FOUND

, +}) + +// The module's region: a room tagged with the installation it renders and +// where that installation is mounted. +function SettingsRoom() { + const { owner } = Route.useRouteContext() + const match = Route.useMatch({ + select: ({ routeId, fullPath, pathname }) => ({ + installation: routeId.slice(0, routeId.indexOf(':')), + fullPath, + pathname, + }), + }) + return ( +
+

+ {match.installation} {match.fullPath} + → {match.pathname} +

+

Settings of {owner.name}

+ +
+ ) +} diff --git a/e2e/react-router/route-modules/packages/settings/src/routes/forward.tsx b/e2e/react-router/route-modules/packages/settings/src/routes/forward.tsx new file mode 100644 index 0000000000..c9520d47a6 --- /dev/null +++ b/e2e/react-router/route-modules/packages/settings/src/routes/forward.tsx @@ -0,0 +1,5 @@ +import * as React from 'react' +import { createFileRoute, Navigate } from '../routeScope.gen' +export const Route = createFileRoute('@route-modules/settings:/forward')({ + component: () => , +}) diff --git a/e2e/react-router/route-modules/packages/settings/src/routes/index.tsx b/e2e/react-router/route-modules/packages/settings/src/routes/index.tsx new file mode 100644 index 0000000000..8bdbffdb73 --- /dev/null +++ b/e2e/react-router/route-modules/packages/settings/src/routes/index.tsx @@ -0,0 +1,16 @@ +import { Link, createFileRoute } from '../routeScope.gen' + +export const Route = createFileRoute('@route-modules/settings:/')({ + component: SettingsIndex, +}) + +function SettingsIndex() { + return ( +
    +
  • + Profile + Name and contact +
  • +
+ ) +} diff --git a/e2e/react-router/route-modules/packages/settings/src/routes/legacy.tsx b/e2e/react-router/route-modules/packages/settings/src/routes/legacy.tsx new file mode 100644 index 0000000000..93d42fe065 --- /dev/null +++ b/e2e/react-router/route-modules/packages/settings/src/routes/legacy.tsx @@ -0,0 +1,6 @@ +import { createFileRoute, redirect } from '../routeScope.gen' +export const Route = createFileRoute('@route-modules/settings:/legacy')({ + beforeLoad: () => { + throw redirect({ to: '/profile' }) + }, +}) diff --git a/e2e/react-router/route-modules/packages/settings/src/routes/members.tsx b/e2e/react-router/route-modules/packages/settings/src/routes/members.tsx new file mode 100644 index 0000000000..cc255a1964 --- /dev/null +++ b/e2e/react-router/route-modules/packages/settings/src/routes/members.tsx @@ -0,0 +1,12 @@ +import * as React from 'react' +import { createFileRoute, getRouteApi } from '../routeScope.gen' +const ProfileLink = getRouteApi('@route-modules/settings:/profile').Link +export const Route = createFileRoute('@route-modules/settings:/members')({ + loader: () => ({ label: 'members' as const }), + component: () => ( + <> +

MEMBERS_PAGE

+ Profile + + ), +}) diff --git a/e2e/react-router/route-modules/packages/settings/src/routes/missing.tsx b/e2e/react-router/route-modules/packages/settings/src/routes/missing.tsx new file mode 100644 index 0000000000..61911c6a98 --- /dev/null +++ b/e2e/react-router/route-modules/packages/settings/src/routes/missing.tsx @@ -0,0 +1,6 @@ +import { createFileRoute, notFound } from '../routeScope.gen' +export const Route = createFileRoute('@route-modules/settings:/missing')({ + component: () => { + throw notFound({ routeId: '@route-modules/settings:' }) + }, +}) diff --git a/e2e/react-router/route-modules/packages/settings/src/routes/profile.tsx b/e2e/react-router/route-modules/packages/settings/src/routes/profile.tsx new file mode 100644 index 0000000000..29e5fdec2b --- /dev/null +++ b/e2e/react-router/route-modules/packages/settings/src/routes/profile.tsx @@ -0,0 +1,81 @@ +import * as React from 'react' +import { Link as ApplicationLink } from '@tanstack/react-router' +import { + createFileRoute, + getRouteApi, + MatchRoute, + useLinkProps, + useRouter, + useNavigate, +} from '../routeScope.gen' + +const api = getRouteApi('@route-modules/settings:/profile') + +export const Route = createFileRoute('@route-modules/settings:/profile')({ + // Each installation loads the profile of the owner its host provides. + loader: ({ context }) => ({ + kind: context.owner.kind, + handle: `@${context.owner.id}`, + }), + component: Profile, +}) + +function Profile() { + const profile = Route.useLoaderData() + const ProfileLinks = Route.useRouteContext().profileLinks + const navigate = api.useNavigate() + const anchor = useLinkProps({ to: '/members' }) + const match = Route.useMatch({ shouldThrow: false }) + const routeNavigate = Route.useNavigate() + const relativeNavigate = useNavigate({ from: '/profile' }) + const scopedRouter = useRouter() + const observe = scopedRouter.options.context?.onProfileMatch + React.useEffect(() => { + observe?.(match?.routeId) + }, [observe, match?.routeId]) + return ( +
+

Profile

+ {match?.routeId} + {match?.localRouteId} + + {JSON.stringify(match?.params)} + + API members + {ProfileLinks ? : null} + + Custom members + + PROFILE_MATCH + + + MEMBERS_MATCH + + + {scopedRouter.buildLocation({ to: '/members' }).href} + + + + + Route home + + Application host + +
+
Kind
+
{profile.kind}
+
Handle
+
+ {profile.handle} +
+
+ All settings +
+ ) +} diff --git a/e2e/react-router/route-modules/packages/settings/src/routes/search.tsx b/e2e/react-router/route-modules/packages/settings/src/routes/search.tsx new file mode 100644 index 0000000000..bdd6fb1f94 --- /dev/null +++ b/e2e/react-router/route-modules/packages/settings/src/routes/search.tsx @@ -0,0 +1,4 @@ +import { createFileRoute } from '../routeScope.gen' +export const Route = createFileRoute('@route-modules/settings:/search')({ + validateSearch: (search: { query: string }) => search, +}) diff --git a/e2e/react-router/route-modules/packages/settings/tsconfig.json b/e2e/react-router/route-modules/packages/settings/tsconfig.json new file mode 100644 index 0000000000..1de72ddc24 --- /dev/null +++ b/e2e/react-router/route-modules/packages/settings/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "skipLibCheck": true, + "noEmit": true, + "types": [] + }, + "include": ["src"] +} diff --git a/e2e/react-router/route-modules/packages/settings/tsconfig.route-types.json b/e2e/react-router/route-modules/packages/settings/tsconfig.route-types.json new file mode 100644 index 0000000000..0c9aec3caf --- /dev/null +++ b/e2e/react-router/route-modules/packages/settings/tsconfig.route-types.json @@ -0,0 +1,13 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "emitDeclarationOnly": true, + "noEmitOnError": true, + "declarationMap": true, + "rootDir": ".", + "outDir": ".tanstack/types" + }, + "include": ["src"] +} diff --git a/e2e/react-router/route-modules/packages/storefront/package.json b/e2e/react-router/route-modules/packages/storefront/package.json new file mode 100644 index 0000000000..78420d0ede --- /dev/null +++ b/e2e/react-router/route-modules/packages/storefront/package.json @@ -0,0 +1,42 @@ +{ + "name": "@route-modules/storefront", + "private": true, + "type": "module", + "tanstack": { + "router": { + "module": { + "includes": [ + { + "module": "@route-modules/products", + "at": "/products" + } + ] + } + } + }, + "exports": { + "./route-types": { + "types": "./.tanstack/types/src/routeContract.gen.d.ts" + }, + "./route-module": { + "types": "./.tanstack/types/src/routeModule.gen.d.ts", + "default": "./src/routeModule.gen.ts" + }, + "./package.json": "./package.json" + }, + "scripts": { + "generate": "tsr generate", + "emit-types": "node -e \"require('node:fs').rmSync('.tanstack/types',{recursive:true,force:true})\" && tsc -p tsconfig.route-types.json", + "check": "tsc --noEmit" + }, + "dependencies": { + "@route-modules/products": "workspace:*", + "@tanstack/react-router": "workspace:^", + "react": "^19.0.0" + }, + "devDependencies": { + "@tanstack/router-cli": "workspace:^", + "@tanstack/router-core": "workspace:^", + "@types/react": "^19.0.8" + } +} diff --git a/e2e/react-router/route-modules/packages/storefront/src/routes/__root.tsx b/e2e/react-router/route-modules/packages/storefront/src/routes/__root.tsx new file mode 100644 index 0000000000..c9ac060bc1 --- /dev/null +++ b/e2e/react-router/route-modules/packages/storefront/src/routes/__root.tsx @@ -0,0 +1,26 @@ +import { Outlet } from '@tanstack/react-router' +import { createModuleRoot } from '../routeScope.gen' +import type { ProductsApi } from '@route-modules/products/api' + +// The products module mounted below requires `productsApi`: the storefront +// requires it from its own host and passes it on. +export const Route = createModuleRoot<{ productsApi: ProductsApi }>()({ + component: StorefrontRoom, +}) + +// The module's region: a room tagged with its package and where it is +// mounted (with the URL it resolved to when the mount path has params). +function StorefrontRoom() { + const pathname = Route.useMatch({ select: (match) => match.pathname }) + return ( +
+

+ @route-modules/storefront {Route.fullPath} + {pathname !== Route.fullPath && ( + → {pathname} + )} +

+ +
+ ) +} diff --git a/e2e/react-router/route-modules/packages/storefront/src/routes/cart.tsx b/e2e/react-router/route-modules/packages/storefront/src/routes/cart.tsx new file mode 100644 index 0000000000..79f6644d2e --- /dev/null +++ b/e2e/react-router/route-modules/packages/storefront/src/routes/cart.tsx @@ -0,0 +1,30 @@ +import { createFileRoute } from '../routeScope.gen' + +export const Route = createFileRoute('@route-modules/storefront:/cart')({ + // The products API comes from the context the storefront requires. + loader: ({ context }) => + Promise.all(['1', '2'].map((id) => context.productsApi.getProduct(id))), + component: Cart, +}) + +function Cart() { + const items = Route.useLoaderData() + const total = items.reduce((sum, item) => sum + item.price, 0) + return ( + <> +

Cart

+
    + {items.map((item) => ( +
  • + {item.name} + {item.price.toFixed(2)} +
  • + ))} +
  • + Total + {total.toFixed(2)} +
  • +
+ + ) +} diff --git a/e2e/react-router/route-modules/packages/storefront/src/routes/index.tsx b/e2e/react-router/route-modules/packages/storefront/src/routes/index.tsx new file mode 100644 index 0000000000..9963a42c5a --- /dev/null +++ b/e2e/react-router/route-modules/packages/storefront/src/routes/index.tsx @@ -0,0 +1,30 @@ +import { Link, createFileRoute, products } from '../routeScope.gen' + +export const Route = createFileRoute('@route-modules/storefront:/')({ + component: StorefrontHome, +}) + +function StorefrontHome() { + return ( + + ) +} diff --git a/e2e/react-router/route-modules/packages/storefront/tsconfig.json b/e2e/react-router/route-modules/packages/storefront/tsconfig.json new file mode 100644 index 0000000000..1de72ddc24 --- /dev/null +++ b/e2e/react-router/route-modules/packages/storefront/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "skipLibCheck": true, + "noEmit": true, + "types": [] + }, + "include": ["src"] +} diff --git a/e2e/react-router/route-modules/packages/storefront/tsconfig.route-types.json b/e2e/react-router/route-modules/packages/storefront/tsconfig.route-types.json new file mode 100644 index 0000000000..0c9aec3caf --- /dev/null +++ b/e2e/react-router/route-modules/packages/storefront/tsconfig.route-types.json @@ -0,0 +1,13 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "emitDeclarationOnly": true, + "noEmitOnError": true, + "declarationMap": true, + "rootDir": ".", + "outDir": ".tanstack/types" + }, + "include": ["src"] +} diff --git a/e2e/react-router/route-modules/packages/team/package.json b/e2e/react-router/route-modules/packages/team/package.json new file mode 100644 index 0000000000..1574523fe5 --- /dev/null +++ b/e2e/react-router/route-modules/packages/team/package.json @@ -0,0 +1,38 @@ +{ + "name": "@route-modules/team", + "private": true, + "type": "module", + "tanstack": { + "router": { + "module": true + } + }, + "exports": { + "./route-types": { + "types": "./.tanstack/types/src/routeContract.gen.d.ts" + }, + "./route-module": { + "types": "./.tanstack/types/src/routeModule.gen.d.ts", + "default": "./src/routeModule.gen.ts" + }, + "./package.json": "./package.json", + "./scope": { + "types": "./.tanstack/types/src/routeScope.gen.d.ts", + "default": "./src/routeScope.gen.ts" + } + }, + "scripts": { + "generate": "tsr generate", + "emit-types": "node -e \"require('node:fs').rmSync('.tanstack/types',{recursive:true,force:true})\" && tsc -p tsconfig.route-types.json", + "check": "tsc --noEmit" + }, + "dependencies": { + "@tanstack/react-router": "workspace:^", + "react": "^19.0.0" + }, + "devDependencies": { + "@tanstack/router-cli": "workspace:^", + "@tanstack/router-core": "workspace:^", + "@types/react": "^19.0.8" + } +} diff --git a/e2e/react-router/route-modules/packages/team/src/routes/__root.tsx b/e2e/react-router/route-modules/packages/team/src/routes/__root.tsx new file mode 100644 index 0000000000..c3c342479f --- /dev/null +++ b/e2e/react-router/route-modules/packages/team/src/routes/__root.tsx @@ -0,0 +1,27 @@ +import { Outlet } from '@tanstack/react-router' +import { createModuleRoot } from '../routeScope.gen' + +// The organization comes from the host route the application mounts the team +// under, so the team works below any route that provides it. +export const Route = createModuleRoot<{ org: { id: string; name: string } }>()({ + component: TeamRoom, +}) + +// The module's region: a room tagged with its package and where it is +// mounted (with the URL it resolved to when the mount path has params). +function TeamRoom() { + const { org } = Route.useRouteContext() + const pathname = Route.useMatch({ select: (match) => match.pathname }) + return ( +
+

+ @route-modules/team {Route.fullPath} + {pathname !== Route.fullPath && ( + → {pathname} + )} +

+

Team of {org.name}

+ +
+ ) +} diff --git a/e2e/react-router/route-modules/packages/team/src/routes/index.tsx b/e2e/react-router/route-modules/packages/team/src/routes/index.tsx new file mode 100644 index 0000000000..ee221db55d --- /dev/null +++ b/e2e/react-router/route-modules/packages/team/src/routes/index.tsx @@ -0,0 +1,25 @@ +import { Link, createFileRoute } from '../routeScope.gen' + +const members = [ + { id: 'ada', role: 'Engineering' }, + { id: 'grace', role: 'Operations' }, +] + +export const Route = createFileRoute('@route-modules/team:/')({ + component: Members, +}) + +function Members() { + return ( +
    + {members.map((member) => ( +
  • + + {member.id} + + {member.role} +
  • + ))} +
+ ) +} diff --git a/e2e/react-router/route-modules/packages/team/src/routes/members.$memberId.tsx b/e2e/react-router/route-modules/packages/team/src/routes/members.$memberId.tsx new file mode 100644 index 0000000000..6ed53bd48d --- /dev/null +++ b/e2e/react-router/route-modules/packages/team/src/routes/members.$memberId.tsx @@ -0,0 +1,28 @@ +import { Link, createFileRoute } from '../routeScope.gen' + +export const Route = createFileRoute('@route-modules/team:/members/$memberId')({ + component: Member, +}) + +function Member() { + const { memberId } = Route.useParams() + const { org } = Route.useRouteContext() + return ( +
+

+ {memberId} at {org.name} +

+
+
Organization
+
+ {org.id} +
+
Member
+
+ {memberId} +
+
+ All members +
+ ) +} diff --git a/e2e/react-router/route-modules/packages/team/tsconfig.json b/e2e/react-router/route-modules/packages/team/tsconfig.json new file mode 100644 index 0000000000..1de72ddc24 --- /dev/null +++ b/e2e/react-router/route-modules/packages/team/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "skipLibCheck": true, + "noEmit": true, + "types": [] + }, + "include": ["src"] +} diff --git a/e2e/react-router/route-modules/packages/team/tsconfig.route-types.json b/e2e/react-router/route-modules/packages/team/tsconfig.route-types.json new file mode 100644 index 0000000000..0c9aec3caf --- /dev/null +++ b/e2e/react-router/route-modules/packages/team/tsconfig.route-types.json @@ -0,0 +1,13 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "emitDeclarationOnly": true, + "noEmitOnError": true, + "declarationMap": true, + "rootDir": ".", + "outDir": ".tanstack/types" + }, + "include": ["src"] +} diff --git a/e2e/react-router/route-modules/packages/web/index.html b/e2e/react-router/route-modules/packages/web/index.html new file mode 100644 index 0000000000..df728d8f44 --- /dev/null +++ b/e2e/react-router/route-modules/packages/web/index.html @@ -0,0 +1,11 @@ + + + + + Acme Workspace + + +
+ + + diff --git a/e2e/react-router/route-modules/packages/web/package.json b/e2e/react-router/route-modules/packages/web/package.json new file mode 100644 index 0000000000..117353b05d --- /dev/null +++ b/e2e/react-router/route-modules/packages/web/package.json @@ -0,0 +1,33 @@ +{ + "name": "@route-modules/web", + "private": true, + "type": "module", + "scripts": { + "generate": "tsr generate", + "check": "tsc --noEmit", + "build": "vite build && tsc -p tsconfig.contracts.json --noEmit", + "dev": "vite", + "check:contracts": "tsc -p tsconfig.contracts.json --noEmit" + }, + "dependencies": { + "@route-modules/account": "workspace:*", + "@route-modules/billing": "workspace:*", + "@route-modules/products": "workspace:*", + "@route-modules/settings": "workspace:*", + "@route-modules/storefront": "workspace:*", + "@route-modules/team": "workspace:*", + "@tanstack/react-router": "workspace:^", + "@tanstack/react-router-devtools": "workspace:^", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@tanstack/router-cli": "workspace:^", + "@tanstack/router-plugin": "workspace:^", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^6.0.1", + "vite": "^8.0.14", + "vitest": "catalog:" + } +} diff --git a/e2e/react-router/route-modules/packages/web/src/main.tsx b/e2e/react-router/route-modules/packages/web/src/main.tsx new file mode 100644 index 0000000000..d5f7da7f39 --- /dev/null +++ b/e2e/react-router/route-modules/packages/web/src/main.tsx @@ -0,0 +1,28 @@ +import ReactDOM from 'react-dom/client' +import { RouterProvider } from '@tanstack/react-router' +import { createAppRouter } from './router' +import './styles.css' +import type { Price, Product } from '@route-modules/products/api' + +// Fixture data: every price is derived from the product id. +const product = (id: string): Product => ({ + id, + name: `Product ${id}`, + price: (([...id].reduce((sum, char) => sum + char.charCodeAt(0), 0) % 90) + + 10) as Price, +}) + +const observedModuleMatches: Array = [] +Object.assign(window, { observedModuleMatches }) +const router = createAppRouter( + { + getProduct: (id) => Promise.resolve(product(id)), + listProducts: () => + Promise.resolve([product('1'), product('2'), product('3')]), + }, + (routeId) => observedModuleMatches.push(routeId), +) + +ReactDOM.createRoot(document.getElementById('app')!).render( + , +) diff --git a/e2e/react-router/route-modules/packages/web/src/profile-links.tsx b/e2e/react-router/route-modules/packages/web/src/profile-links.tsx new file mode 100644 index 0000000000..f05267a00b --- /dev/null +++ b/e2e/react-router/route-modules/packages/web/src/profile-links.tsx @@ -0,0 +1,18 @@ +import * as settings from '@route-modules/settings/scope' +import { orgSettings } from './routeScope.gen' + +const deferredMembers = settings.linkOptions( + orgSettings.linkOptions({ to: '/members', params: { orgId: '7' } }), +) + +export function ProfileLinks() { + const organizationProfile = orgSettings.useMatch({ + from: '@route-modules/settings:/profile', + shouldThrow: false, + }) + // The host owns its installation namespace; the provider renders this slot + // inside the profile match so the local receiver has a real nearest scope. + return organizationProfile ? ( + Deferred members + ) : null +} diff --git a/e2e/react-router/route-modules/packages/web/src/router.tsx b/e2e/react-router/route-modules/packages/web/src/router.tsx new file mode 100644 index 0000000000..94fe903a8a --- /dev/null +++ b/e2e/react-router/route-modules/packages/web/src/router.tsx @@ -0,0 +1,20 @@ +import { createRouter } from '@tanstack/react-router' +import { ProfileLinks } from './profile-links' +import { routeTree } from './routeTree.gen' +import type { ProductsApi } from '@route-modules/products/api' + +export function createAppRouter( + productsApi: ProductsApi, + onProfileMatch?: (routeId: string | undefined) => void, +) { + return createRouter({ + routeTree, + context: { productsApi, onProfileMatch, profileLinks: ProfileLinks }, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/e2e/react-router/route-modules/packages/web/src/routes/__root.tsx b/e2e/react-router/route-modules/packages/web/src/routes/__root.tsx new file mode 100644 index 0000000000..72374fa0e4 --- /dev/null +++ b/e2e/react-router/route-modules/packages/web/src/routes/__root.tsx @@ -0,0 +1,94 @@ +import * as React from 'react' +import { + Link, + Outlet, + createRootRouteWithContext, +} from '@tanstack/react-router' +import { + account, + products, + storefront, + team, + orgSettings, + personSettings, +} from '../routeScope.gen' +import type { ProductsApi } from '@route-modules/products/api' + +// The router devtools, in development only. +const RouterDevtools = import.meta.env.DEV + ? React.lazy(() => + import('@tanstack/react-router-devtools').then((module) => ({ + default: module.TanStackRouterDevtools, + })), + ) + : () => null + +export const Route = createRootRouteWithContext<{ + productsApi: ProductsApi + onProfileMatch?: (routeId: string | undefined) => void + profileLinks?: React.ComponentType +}>()({ + component: AppShell, +}) + +function AppShell() { + const organizationProfile = orgSettings.useMatch({ + from: '@route-modules/settings:/profile', + shouldThrow: false, + }) + return ( + <> +
+ + + Acme Workspace + + +
+ +
+ +
+ + + + + ) +} + +/** A small floor plan: outer walls with a door, two inner walls. */ +function PlanMark() { + return ( + + ) +} diff --git a/e2e/react-router/route-modules/packages/web/src/routes/_authenticated.tsx b/e2e/react-router/route-modules/packages/web/src/routes/_authenticated.tsx new file mode 100644 index 0000000000..9cad2d227a --- /dev/null +++ b/e2e/react-router/route-modules/packages/web/src/routes/_authenticated.tsx @@ -0,0 +1,6 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/_authenticated')({ + beforeLoad: () => ({ user: { id: 'u-1' } }), + component: () => , +}) diff --git a/e2e/react-router/route-modules/packages/web/src/routes/index.tsx b/e2e/react-router/route-modules/packages/web/src/routes/index.tsx new file mode 100644 index 0000000000..90e3aa0f76 --- /dev/null +++ b/e2e/react-router/route-modules/packages/web/src/routes/index.tsx @@ -0,0 +1,122 @@ +import { createFileRoute, useMatch } from '@tanstack/react-router' +import { + account, + billing, + orgSettings, + personSettings, + products, + storefront, + team, +} from '../routeScope.gen' + +export const Route = createFileRoute('/')({ + component: Home, +}) + +// A key plan of the workspace: every module's room where the workspace mounts +// it, nested like the routes. +function Home() { + const productMatch = useMatch({ + from: '@route-modules/products:/$productId', + shouldThrow: false, + }) + return ( + <> +

Acme workspace

+

+ Each region of this workspace is a route module, drawn as a room: its + tag names the package and where the workspace mounts it. +

+
+
+

+ @route-modules/storefront /shop +

+

+ Cart +

+
+

+ @route-modules/products /shop/products +

+

+ + Pick of the day + + {productMatch?.loaderData?.name} +

+
+
+
+

+ @route-modules/account /account +

+

+ Your account +

+
+ {/* The organization route is the workspace's own: both modules below + it get `orgId` from the URL. */} +
+

+ Host route /orgs/$orgId +

+
+
+

+ @route-modules/team /team +

+

+ {/* The team is mounted below `/orgs/$orgId`: links into it pass `orgId`. */} + + Acme team + +

+
+
+

+ @route-modules/billing /billing +

+

+ + Globex billing + +

+
+
+

+ @route-modules/settings#orgSettings /settings +

+

+ + Globex settings + +

+
+
+
+ {/* The settings are installed a second time, per person. */} +
+

+ Host route /people/$personId +

+
+
+

+ @route-modules/settings#personSettings /settings +

+

+ + Ada's profile + +

+
+
+
+
+ + ) +} diff --git a/e2e/react-router/route-modules/packages/web/src/routes/orgs.$orgId.tsx b/e2e/react-router/route-modules/packages/web/src/routes/orgs.$orgId.tsx new file mode 100644 index 0000000000..3c08aa0637 --- /dev/null +++ b/e2e/react-router/route-modules/packages/web/src/routes/orgs.$orgId.tsx @@ -0,0 +1,15 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +// The host route of the modules mounted per organization: they get its path +// params in their URLs and the organization as context, and its settings +// installation the organization as their owner. +export const Route = createFileRoute('/orgs/$orgId')({ + beforeLoad: ({ params }) => { + const name = params.orgId.toUpperCase() + return { + org: { id: params.orgId, name }, + owner: { kind: 'organization' as const, id: params.orgId, name }, + } + }, + component: () => , +}) diff --git a/e2e/react-router/route-modules/packages/web/src/routes/people.$personId.tsx b/e2e/react-router/route-modules/packages/web/src/routes/people.$personId.tsx new file mode 100644 index 0000000000..19ac32e5c7 --- /dev/null +++ b/e2e/react-router/route-modules/packages/web/src/routes/people.$personId.tsx @@ -0,0 +1,13 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +// The host route of the settings installation per person. +export const Route = createFileRoute('/people/$personId')({ + beforeLoad: ({ params }) => ({ + owner: { + kind: 'person' as const, + id: params.personId, + name: params.personId[0]!.toUpperCase() + params.personId.slice(1), + }, + }), + component: () => , +}) diff --git a/e2e/react-router/route-modules/packages/web/src/styles.css b/e2e/react-router/route-modules/packages/web/src/styles.css new file mode 100644 index 0000000000..edcaf3ef9b --- /dev/null +++ b/e2e/react-router/route-modules/packages/web/src/styles.css @@ -0,0 +1,450 @@ +/* + * Acme: the route-module fixtures drawn as a floor plan. Every route module is + * a room: a wall line, a zoning tint and a room tag with its package and mount + * path. Violet marks the active route and nothing else. + */ + +:root { + color-scheme: light; + + --ground: #f4f6f9; + --sheet: #ffffff; + --ink: #1f2328; + --ink-2: #4b535c; + --ink-3: #59616b; + --line: #d3d7db; + --wall: #2a3036; + --route: #5b3fd1; + --route-wash: #e9e5fb; + /* Link underlines: 3:1 or better on the ground and on every zone. */ + --underline: color-mix(in srgb, var(--wall) 55%, transparent); + --zone: #eef0f2; + + --font: + ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, + 'Helvetica Neue', Arial, sans-serif; + /* Plan lettering: a local condensed face where there is one. */ + --font-lettering: + 'Avenir Next Condensed', 'Roboto Condensed', 'Arial Narrow', ui-sans-serif, + system-ui, sans-serif; + --mono: ui-monospace, 'SF Mono', Menlo, Consolas, monospace; + + --s1: 4px; + --s2: 8px; + --s3: 12px; + --s4: 16px; + --s5: 20px; + --s6: 24px; + --s8: 32px; + --s10: 40px; + --s12: 48px; + + /* A drafted wall: two lines with the wall's thickness between them. */ + --wall-line: 6px double var(--wall); + --ease-out: cubic-bezier(0.16, 1, 0.3, 1); +} + +/* Zoning: one tint per module, as on a zoning plan. */ +[data-route-module='@route-modules/storefront'] { + --zone: #e7e9e4; +} +[data-route-module='@route-modules/products'] { + --zone: #e1ebdd; +} +[data-route-module='@route-modules/account'] { + --zone: #dce7f2; +} +[data-route-module='@route-modules/team'] { + --zone: #d9eeeb; +} +[data-route-module='@route-modules/billing'] { + --zone: #f2e1e1; +} +[data-route-module='@route-modules/settings'] { + --zone: #efecd2; +} + +*, +*::before, +*::after { + box-sizing: border-box; +} + +html { + background: var(--ground); + scrollbar-color: var(--line) transparent; +} + +body { + margin: 0; + color: var(--ink); + font: 400 15px/1.55 var(--font); + -webkit-font-smoothing: antialiased; +} + +::selection { + background: var(--route-wash); + color: var(--ink); +} + +:focus-visible { + outline: 2px solid var(--wall); + outline-offset: 2px; + border-radius: 2px; +} + +h1, +h2, +h3 { + margin: 0 0 var(--s3); + font-weight: 650; + letter-spacing: -0.02em; + line-height: 1.2; + text-wrap: balance; +} +h1 { + font-size: 30px; +} +h2 { + font-size: 22px; +} +h3 { + font-size: 18px; +} + +p { + margin: 0 0 var(--s3); + max-width: 68ch; +} + +code { + font: 500 0.92em var(--mono); +} + +a { + color: var(--ink); + text-decoration: underline; + text-decoration-color: var(--underline); + text-decoration-thickness: 1px; + text-underline-offset: 3px; + transition: text-decoration-color 160ms var(--ease-out); +} +a:hover { + text-decoration-color: var(--ink); +} + +button { + font: inherit; +} + +/* Shell */ + +.topbar { + position: sticky; + top: 0; + z-index: 10; + display: flex; + align-items: center; + gap: var(--s8); + min-height: 52px; + padding: 0 var(--s6); + background: var(--sheet); + border-bottom: 1px solid var(--line); +} + +.brand { + display: inline-flex; + align-items: center; + gap: var(--s2); + font-weight: 650; + letter-spacing: -0.01em; + text-decoration: none; + white-space: nowrap; +} +.brand-mark { + flex: none; + width: 18px; + height: 18px; + color: var(--wall); +} +.brand small { + color: var(--ink-3); + font-size: 13px; + font-weight: 500; +} + +.nav { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--s1) var(--s5); + font-size: 14px; +} +.nav a { + position: relative; + margin: 0 calc(-1 * var(--s1)); + padding: var(--s3) var(--s1); + color: var(--ink-2); + text-decoration: none; +} +.nav a:hover { + color: var(--ink); +} +.nav a[data-status='active'] { + color: var(--route); +} +.nav a[data-status='active']::after { + content: ''; + position: absolute; + inset: auto var(--s1) 0; + height: 2px; + background: var(--route); +} +.nav-group { + display: inline-flex; + align-items: center; + gap: var(--s4); + padding-left: var(--s5); + border-left: 1px solid var(--line); +} +.nav-label { + color: var(--ink-3); + font-size: 13px; +} + +.page { + max-width: 1080px; + margin: 0 auto; + padding: var(--s10) var(--s6) 120px; +} + +.lead { + color: var(--ink-2); + font-size: 17px; +} + +/* Rooms: the signature. A module's region is a room with a wall line, its + zoning tint, and a tag on the wall naming the package and its mount. */ + +.room { + margin-top: var(--s5); + padding: 0 var(--s6) var(--s6); + background: var(--zone) padding-box; + border: var(--wall-line); + animation: room-in 420ms var(--ease-out); +} +.room .room { + margin-top: var(--s8); +} +.room > :last-child { + margin-bottom: 0; +} +/* A room's title has one size whatever its level. */ +.room h1 { + font-size: 22px; +} + +/* The tag sits on the wall: pulled up onto its center line, it wraps on + narrow screens instead of clipping the resolved path. Names and paths keep + their source case: they are identifiers maintainers copy. */ +.room-tag { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 0 var(--s2); + width: fit-content; + max-width: 100%; + margin: -14px 0 var(--s5) calc(var(--s4) - var(--s6)); + padding: 2px var(--s2); + background: var(--sheet); + border: 1px solid var(--wall); + font: 600 12px/16px var(--font-lettering); + font-stretch: condensed; + font-variant-numeric: tabular-nums; + letter-spacing: 0.04em; +} +.room-tag code { + font: 500 11px/16px var(--mono); + color: var(--ink-2); +} +.room-tag .resolved { + color: var(--route); +} + +@keyframes room-in { + from { + background-color: var(--sheet); + } +} + +/* Lists, facts and controls inside rooms */ + +.rows { + margin: 0 0 var(--s4); + padding: 0; + list-style: none; + font-variant-numeric: tabular-nums; + border-top: 1px solid color-mix(in srgb, var(--wall) 22%, transparent); +} +.rows > li { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: var(--s4); + padding: var(--s3) 0; + border-bottom: 1px solid color-mix(in srgb, var(--wall) 22%, transparent); +} +.rows .meta { + color: var(--ink-3); + font-size: 13px; +} + +.facts { + display: grid; + grid-template-columns: max-content 1fr; + align-items: baseline; + gap: var(--s2) var(--s6); + margin: 0 0 var(--s5); + font-variant-numeric: tabular-nums; +} +.facts dt { + color: var(--ink-3); + font-size: 13px; +} +.facts dd { + margin: 0; +} + +.tabs { + display: flex; + gap: var(--s5); + margin: 0 0 var(--s4); + border-bottom: 1px solid color-mix(in srgb, var(--wall) 22%, transparent); + font-size: 14px; +} +.tabs a { + margin-bottom: -1px; + padding: var(--s2) 0; + color: var(--ink-2); + text-decoration: none; + border-bottom: 2px solid transparent; +} +.tabs a:hover { + color: var(--ink); +} +.tabs a[aria-current] { + color: var(--route); + border-bottom-color: var(--route); +} + +.button { + display: inline-flex; + align-items: center; + min-height: 36px; + padding: 0 var(--s4); + color: var(--sheet); + background: var(--wall); + border: 0; + border-radius: 6px; + font-weight: 600; + font-size: 14px; + cursor: pointer; + transition: + background-color 160ms var(--ease-out), + transform 160ms var(--ease-out); +} +.button:hover { + background: var(--ink); +} +.button:active { + transform: translateY(1px); +} + +/* Key plan on the home page: every room where the application mounts it. + A host route that is not a module is a plot boundary around its rooms. */ + +.plan { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + align-items: start; + gap: var(--s8) var(--s6); + margin-top: var(--s10); +} +.plan .room { + margin-top: 0; +} +.plan .room .room { + margin-top: var(--s6); +} +.plan .room > p:not(.room-tag) { + color: var(--ink-2); +} +.plot { + grid-column: 1 / -1; + padding: 0 var(--s6) var(--s6); + border: 1.5px dashed var(--ink-3); +} +.plot-rooms { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); + align-items: start; + gap: var(--s8) var(--s6); + padding-top: var(--s3); +} +.plot > .room-tag { + margin-top: -12px; + margin-bottom: var(--s4); + border-style: dashed; + border-color: var(--ink-3); + font-weight: 500; +} + +@media (max-width: 720px) { + .topbar { + position: static; + flex-wrap: wrap; + gap: 0 var(--s4); + padding: var(--s2) var(--s4) 0; + } + /* One scrolling row below the brand. */ + .nav { + order: 1; + flex-basis: 100%; + flex-wrap: nowrap; + gap: var(--s2); + overflow-x: auto; + scrollbar-width: none; + } + .nav a, + .nav-group { + flex: none; + } + .nav-group { + gap: var(--s2); + padding-left: var(--s2); + } + .nav-label { + display: none; + } + .page { + padding: var(--s6) var(--s4) 120px; + } + .room { + padding: 0 var(--s4) var(--s4); + } + .room-tag { + margin-left: 0; + } + .plan { + grid-template-columns: minmax(0, 1fr); + } + .plot { + padding: 0 var(--s4) var(--s4); + } +} + +@media (prefers-reduced-motion: reduce) { + .room { + animation: none; + } +} diff --git a/e2e/react-router/route-modules/packages/web/tests/match-identity.test.tsx b/e2e/react-router/route-modules/packages/web/tests/match-identity.test.tsx new file mode 100644 index 0000000000..7aedbb6ae6 --- /dev/null +++ b/e2e/react-router/route-modules/packages/web/tests/match-identity.test.tsx @@ -0,0 +1,139 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory, createRouter } from '@tanstack/react-router' +import { routeTree } from '../src/routeTree.gen' +import { + account, + products, + storefront, + orgSettings, + personSettings, +} from '../src/routeScope.gen' +import { isScopedMatch } from '@route-modules/settings/scope' + +function createApp(pathname: string) { + return createRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: [pathname] }), + // This server harness drives load explicitly. Browser e2e tests exercise + // the navigation subscription owned by a mounted RouterProvider. + isServer: true, + context: { + productsApi: { + getProduct: async (id) => ({ id, name: id, price: 10 as never }), + listProducts: async () => [], + }, + }, + }) +} + +describe('installed module match identity', () => { + test.each([ + ['/orgs/globex/settings/profile', 'orgSettings', '/orgs/$orgId'], + ['/people/ada/settings/profile', 'personSettings', '/people/$personId'], + ])( + 'keeps final and module-local identities for %s', + async (pathname, installation, parent) => { + const router = createApp(pathname) + await router.load() + expect( + router.state.matches.map(({ routeId, localRouteId }) => ({ + routeId, + localRouteId, + })), + ).toEqual([ + { routeId: '__root__', localRouteId: undefined }, + { routeId: parent, localRouteId: undefined }, + { + routeId: `@route-modules/settings#${installation}:`, + localRouteId: '@route-modules/settings:', + }, + { + routeId: `@route-modules/settings#${installation}:/profile`, + localRouteId: '@route-modules/settings:/profile', + }, + ]) + expect(Object.hasOwn(router.state.matches[0]!, 'localRouteId')).toBe( + false, + ) + expect(Object.hasOwn(router.state.matches[1]!, 'localRouteId')).toBe( + false, + ) + }, + ) + + test('loading a new location keeps local identity across installations', async () => { + const router = createApp('/orgs/globex/settings/profile') + await router.load() + router.history.push('/people/ada/settings/profile') + await router.load() + expect(router.state.matches.at(-1)).toMatchObject({ + routeId: '@route-modules/settings#personSettings:/profile', + localRouteId: '@route-modules/settings:/profile', + loaderData: { kind: 'person', handle: '@ada' }, + }) + }) +}) + +test('context-free match guards select the installed subtree and exact namespace', async () => { + const router = createApp('/orgs/globex/settings/profile') + await router.load() + expect( + router.state.matches + .filter(orgSettings.isScopedMatch) + .map((match) => match.routeId), + ).toEqual([ + '@route-modules/settings#orgSettings:', + '@route-modules/settings#orgSettings:/profile', + ]) + expect(router.state.matches.filter(personSettings.isScopedMatch)).toEqual([]) + expect( + router.state.matches + .filter(isScopedMatch) + .map((match) => match.localRouteId), + ).toEqual(['@route-modules/settings:', '@route-modules/settings:/profile']) + + // The server load needs the canonical search value supplied by this route. + router.history.push('/shop/products/1?tab=specs') + await router.load() + // Descendant module matches belong to the storefront's installed subtree. + expect( + router.state.matches + .filter(storefront.isScopedMatch) + .map((match) => match.routeId), + ).toEqual([ + '@route-modules/storefront:', + '@route-modules/products:', + '@route-modules/products:/$productId', + ]) + // The host's namespace for the nested include selects the nested module only. + expect( + router.state.matches + .filter(products.isScopedMatch) + .map((match) => match.routeId), + ).toEqual(['@route-modules/products:', '@route-modules/products:/$productId']) + // Account only declares `uses: products`; that dependency is not installed + // beneath account and must not be classified as an account subtree match. + expect(router.state.matches.filter(account.isScopedMatch)).toEqual([]) +}) + +test('application route objects expose the installed graph', async () => { + const router = createApp('/orgs/globex/settings/profile') + await router.load() + const root = router.routesById['@route-modules/settings#orgSettings:'] + const profile = + router.routesById['@route-modules/settings#orgSettings:/profile'] + // `path` is the normalized segment; options.path is the authored mount path. + expect(root.path).toBe('settings') + expect(root.options.path).toBe('/settings') + expect(root.fullPath).toBe('/orgs/$orgId/settings') + expect(profile.parentRoute).toBe(root) + expect(profile.options.getParentRoute?.()).toBe(root) + expect(profile.parentRoute.id).toBe('@route-modules/settings#orgSettings:') + + const layout = router.routesById['@route-modules/products:/_layout'] + const children = Object.values(layout.children ?? {}) + expect(children.map((child) => child.fullPath)).toEqual([ + '/shop/products/deals', + ]) + expect(children[0]?.parentRoute).toBe(layout) +}) diff --git a/e2e/react-router/route-modules/packages/web/tests/scope-options.test.tsx b/e2e/react-router/route-modules/packages/web/tests/scope-options.test.tsx new file mode 100644 index 0000000000..df968f2f62 --- /dev/null +++ b/e2e/react-router/route-modules/packages/web/tests/scope-options.test.tsx @@ -0,0 +1,140 @@ +import * as React from 'react' +import { renderToString } from 'react-dom/server' +import { expect, test } from 'vitest' +import { + RouterContextProvider, + createMemoryHistory, + createRouter, +} from '@tanstack/react-router' +import { routeTree } from '../src/routeTree.gen' +import { orgSettings, personSettings } from '../src/routeScope.gen' +import * as settings from '@route-modules/settings/scope' + +async function createApp() { + const router = createRouter({ + routeTree, + context: { + productsApi: { + getProduct: async (id) => ({ id, name: id, price: 10 as never }), + listProducts: async () => [], + }, + }, + history: createMemoryHistory({ + initialEntries: ['/orgs/7/settings/profile'], + }), + }) + await router.load() + return router +} + +test('scoped consumers reject options from another named installation', async () => { + const router = await createApp() + // JSON is a realistic untyped source; typed conflicts are covered separately. + const foreign = JSON.parse( + JSON.stringify( + personSettings.linkOptions({ + to: '/members', + params: { personId: 'u1' }, + }), + ), + ) + for (const Component of [ + orgSettings.Link, + orgSettings.Navigate, + orgSettings.MatchRoute, + ]) { + expect(() => + renderToString( + + {React.createElement(Component as React.ComponentType, foreign)} + , + ), + ).toThrow(/Cannot use route scope/) + } + expect(() => orgSettings.linkOptions(foreign)).toThrow( + /Cannot use route scope/, + ) + expect(() => orgSettings.redirect(foreign)).toThrow(/Cannot use route scope/) +}) + +test('same-scope options and neutral consumers preserve their destination', async () => { + const router = await createApp() + const home = orgSettings.linkOptions({ + to: '/members', + params: { orgId: '7' }, + }) + expect(router.buildLocation(home).href).toBe('/orgs/7/settings/members') + expect( + renderToString( + + Members + , + ), + ).toContain('href="/orgs/7/settings/members"') +}) + +test('a context-free local receiver preserves its constraint until navigation', async () => { + const router = await createApp() + const local = settings.linkOptions({ to: '/members' }) + const explicit = personSettings.linkOptions({ + to: '/members', + params: { personId: 'u1' }, + }) + const deferred = settings.linkOptions(explicit) + const redirect = settings.redirect(explicit) + function Receiver({ options }: { options: typeof local | typeof deferred }) { + // The generated namespace is the explicit receiving installation. The + // normal hook supplies its router view; no private origin is fabricated. + const scopedRouter = orgSettings.useRouter() + return {scopedRouter.buildLocation(options).href} + } + function renderOptions(options: typeof local | typeof deferred) { + return renderToString( + + + , + ) + } + expect(renderOptions(local)).toContain('/orgs/7/settings/members') + expect(() => renderOptions(deferred)).toThrow(/Cannot use route scope/) + // The redirect's public options keep the same unresolved receiving contract. + expect(() => renderOptions(redirect.options)).toThrow( + /Cannot use route scope/, + ) +}) + +test('an explicit receiving scope resolves a deferred local constraint', async () => { + const router = await createApp() + const options = settings.linkOptions( + orgSettings.linkOptions({ to: '/members', params: { orgId: '7' } }), + ) + function Receiver() { + const href = orgSettings.useRouter().buildLocation(options).href + return {href} + } + expect( + renderToString( + + + , + ), + ).toContain('/orgs/7/settings/members') +}) + +test('stamped mask options cannot silently retarget a sibling installation', async () => { + const router = await createApp() + const mask = JSON.parse( + JSON.stringify( + personSettings.linkOptions({ + to: '/members', + params: { personId: 'u1' }, + }), + ), + ) + const options = orgSettings.linkOptions({ + to: '/members', + params: { orgId: '7' }, + mask, + }) + expect(() => router.buildLocation(options)).toThrow(/Cannot use route scope/) +}) diff --git a/e2e/react-router/route-modules/packages/web/tsconfig.contracts.json b/e2e/react-router/route-modules/packages/web/tsconfig.contracts.json new file mode 100644 index 0000000000..c783b45e43 --- /dev/null +++ b/e2e/react-router/route-modules/packages/web/tsconfig.contracts.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "include": ["src", "type-tests"], + "compilerOptions": { + "skipLibCheck": false + } +} diff --git a/e2e/react-router/route-modules/packages/web/tsconfig.json b/e2e/react-router/route-modules/packages/web/tsconfig.json new file mode 100644 index 0000000000..44dff33802 --- /dev/null +++ b/e2e/react-router/route-modules/packages/web/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "skipLibCheck": true, + "noEmit": true, + "types": ["vite/client"] + }, + "include": ["src"] +} diff --git a/e2e/react-router/route-modules/packages/web/tsr.config.json b/e2e/react-router/route-modules/packages/web/tsr.config.json new file mode 100644 index 0000000000..0b6ae92d38 --- /dev/null +++ b/e2e/react-router/route-modules/packages/web/tsr.config.json @@ -0,0 +1,36 @@ +{ + "routesDirectory": "./src/routes", + "generatedRouteTree": "./src/routeTree.gen.ts", + "routeModules": { + "includes": [ + { "module": "@route-modules/storefront", "at": "/shop" }, + { + "module": "@route-modules/account", + "parent": "/_authenticated", + "at": "/account" + }, + { + "module": "@route-modules/team", + "parent": "/orgs/$orgId", + "at": "/team" + }, + { + "module": "@route-modules/billing", + "parent": "/orgs/$orgId", + "at": "/billing" + }, + { + "module": "@route-modules/settings", + "parent": "/orgs/$orgId", + "at": "/settings", + "as": "orgSettings" + }, + { + "module": "@route-modules/settings", + "parent": "/people/$personId", + "at": "/settings", + "as": "personSettings" + } + ] + } +} diff --git a/e2e/react-router/route-modules/packages/web/type-tests/core-contracts.tsx b/e2e/react-router/route-modules/packages/web/type-tests/core-contracts.tsx new file mode 100644 index 0000000000..4f12bdbdd4 --- /dev/null +++ b/e2e/react-router/route-modules/packages/web/type-tests/core-contracts.tsx @@ -0,0 +1,211 @@ +import { describe, expectTypeOf, test } from 'vitest' +import type { routeTree } from '../src/routeTree.gen' +import type { createAppRouter } from '../src/router' +import { routeModule as productsRouteModule } from '@route-modules/products/route-module' +import { + useMatch as useProductMatch, + useRouter as useProductRouter, + useRouterState as useProductRouterState, + useLocation as useProductLocation, + useSearch as useProductSearch, + isScopedMatch as isProductMatch, +} from '@route-modules/products/scope' +import type { + Router as ProductsRouter, + OwnRoutesById, +} from '@route-modules/products/route-types' +import type { Product } from '@route-modules/products/api' +import type { + AnyRouteMatch, + AnyRoute, + ForeignRouteMatch, + InstallationRoutesById, + MountedRoutesById, + MakeRouteMatch, + MakeRouteMatchUnion, +} from '@tanstack/react-router' + +declare const ProductRoute: OwnRoutesById['@route-modules/products:/$productId'] +declare const foreignMatch: ForeignRouteMatch +declare const routerMatch: AnyRouteMatch +declare const mountedProduct: ReturnType< + typeof createAppRouter +>['routesById']['@route-modules/products:/$productId'] + +const applicationRoute: AnyRoute = mountedProduct +void applicationRoute + +describe('installed route identity contracts', () => { + test('installation map values agree with their keys', () => { + type Installed = InstallationRoutesById< + { '@route-modules/products:/$productId': typeof ProductRoute }, + '@route-modules/products', + 'shopProducts' + > + type Product = Installed['@route-modules/products#shopProducts:/$productId'] + + expectTypeOf< + Product['id'] + >().toEqualTypeOf<'@route-modules/products#shopProducts:/$productId'>() + expectTypeOf< + Product['types']['id'] + >().toEqualTypeOf<'@route-modules/products#shopProducts:/$productId'>() + expectTypeOf( + ProductRoute.id, + ).toEqualTypeOf<'@route-modules/products:/$productId'>() + type Mounted = + MountedRoutesById['@route-modules/products#shopProducts:/$productId'] + expectTypeOf().toEqualTypeOf() + expectTypeOf().toEqualTypeOf() + expectTypeOf().toEqualTypeOf() + expectTypeOf(ProductRoute.fullPath).toEqualTypeOf<'/$productId'>() + }) + + test('known module matches have an exact required local identity', () => { + type ProductMatch = MakeRouteMatch< + typeof productsRouteModule, + '@route-modules/products:/$productId' + > + expectTypeOf< + ProductMatch['localRouteId'] + >().toEqualTypeOf<'@route-modules/products:/$productId'>() + expectTypeOf().toEqualTypeOf< + string | undefined + >() + }) + + test('application records preserve ordinary path precision and mixed optional identity', () => { + type Tree = typeof routeTree + type Host = MakeRouteMatch + expectTypeOf().toEqualTypeOf<'/orgs/$orgId'>() + type Mixed = MakeRouteMatch< + Tree, + '/orgs/$orgId' | '@route-modules/settings#orgSettings:/profile' + > + expectTypeOf().toEqualTypeOf() + type Product = MakeRouteMatch< + Tree, + '@route-modules/settings#orgSettings:/profile' + > + expectTypeOf< + Product['routeId'] + >().toEqualTypeOf<'@route-modules/settings#orgSettings:/profile'>() + expectTypeOf().toEqualTypeOf() + }) + + test('module hooks describe final installation identity honestly', () => { + const match = useProductMatch({ + from: '@route-modules/products:/$productId', + }) + expectTypeOf(match.fullPath).toEqualTypeOf() + expectTypeOf(match.routeId).toEqualTypeOf< + | '@route-modules/products:/$productId' + | `@route-modules/products#${string}:/$productId` + >() + expectTypeOf( + match.localRouteId, + ).toEqualTypeOf<'@route-modules/products:/$productId'>() + }) + + test('a full scoped match chain includes unknown host data', () => { + type Match = MakeRouteMatchUnion + expectTypeOf().toBeUnknown() + expectTypeOf().toBeUnknown() + expectTypeOf(useProductRouterState().matches[0]!.context).toBeUnknown() + expectTypeOf(useProductLocation().search).toEqualTypeOf< + Record + >() + expectTypeOf(useProductRouter().state.location.search).toEqualTypeOf< + Record + >() + expectTypeOf( + useProductSearch({ from: '@route-modules/products:/$productId' }).tab, + ).toEqualTypeOf<'specs' | 'reviews'>() + expectTypeOf(useProductRouter().state.matches[0]!.loaderData).toBeUnknown() + useProductRouterState({ + select: (state) => { + expectTypeOf(state.matches[0]!.context).toBeUnknown() + return state.matches.length + }, + }) + }) + + test('scope membership narrows complete router matches', () => { + isProductMatch(routerMatch) + isProductMatch(foreignMatch) + for (const match of useProductRouterState().matches) { + if ( + isProductMatch(match) && + match.localRouteId === '@route-modules/products:/$productId' + ) { + expectTypeOf(match.loaderData).toEqualTypeOf() + } + } + + // @ts-expect-error Scope membership cannot supply absent match data. + isProductMatch({ + routeId: '@route-modules/products:/$productId', + localRouteId: '@route-modules/products:/$productId', + }) + }) + + test('loose match selectors retain unknown foreign route data', () => { + useProductMatch({ + strict: false, + select: (match) => { + expectTypeOf(match.loaderData).toBeUnknown() + expectTypeOf(match.context).toBeUnknown() + return match.routeId + }, + }) + }) + + test('raw scoped router maps do not promise module-local aliases', () => { + const router = useProductRouter() + expectTypeOf( + router.routesById['@route-modules/products:/$productId'], + ).toEqualTypeOf() + expectTypeOf(router.routesByPath['/$productId']).toEqualTypeOf< + AnyRoute | undefined + >() + }) +}) + +test('application route records expose mounted paths and raw linked routes honestly', () => { + type Routes = ReturnType['routesById'] + type Root = Routes['@route-modules/settings#orgSettings:'] + type Profile = Routes['@route-modules/settings#orgSettings:/profile'] + // These are values read from the real generated installation at runtime. + // They must be assignable to the public route object's declared fields. + expectTypeOf<'settings'>().toMatchTypeOf() + expectTypeOf<'settings'>().toMatchTypeOf() + expectTypeOf<'/settings'>().toMatchTypeOf< + NonNullable + >() + expectTypeOf<'@route-modules/settings#orgSettings:'>().toMatchTypeOf< + Profile['parentRoute']['id'] + >() + expectTypeOf<'@route-modules/settings#orgSettings:'>().toMatchTypeOf< + Profile['types']['parentRoute']['id'] + >() + type ParentFromOptions = ReturnType< + NonNullable + > + expectTypeOf<'@route-modules/settings#orgSettings:'>().toMatchTypeOf< + ParentFromOptions['id'] + >() + + type Layout = Routes['@route-modules/products:/_layout'] + type Children = NonNullable + type Child = + Children extends ReadonlyArray ? Item : Children[keyof Children] + expectTypeOf<'/shop/products/deals'>().toMatchTypeOf() + + // Precision that the application can prove remains intact. + expectTypeOf< + Profile['id'] + >().toEqualTypeOf<'@route-modules/settings#orgSettings:/profile'>() + expectTypeOf< + Routes['/orgs/$orgId']['fullPath'] + >().toEqualTypeOf<'/orgs/$orgId'>() +}) diff --git a/e2e/react-router/route-modules/packages/web/type-tests/module-apis.tsx b/e2e/react-router/route-modules/packages/web/type-tests/module-apis.tsx new file mode 100644 index 0000000000..c25a115af5 --- /dev/null +++ b/e2e/react-router/route-modules/packages/web/type-tests/module-apis.tsx @@ -0,0 +1,207 @@ +import * as React from 'react' +import { describe, expectTypeOf, test } from 'vitest' +import { Link, useMatch } from '@tanstack/react-router' +import { + Link as ProductsLink, + getRouteApi as productsGetRouteApi, + linkOptions as productsLinkOptions, + redirect as productsRedirect, + useLoaderData as productsUseLoaderData, + useNavigate as productsUseNavigate, + useRouter as productsUseRouter, +} from '@route-modules/products/scope' +import { + Link as AccountLink, + getRouteApi as accountGetRouteApi, + products, +} from '@route-modules/account/scope' +import * as localTeam from '@route-modules/team/scope' +import { team as hostedTeam } from '../src/routeScope.gen' +import type { createAppRouter } from '../src/router' +import type { Price, Product, ProductsApi } from '@route-modules/products/api' +import type { + Router as ProductsRouter, + OwnRoutesById, +} from '@route-modules/products/route-types' +import type { ScopedRouterView } from '@tanstack/react-router' + +declare const ProductRoute: OwnRoutesById['@route-modules/products:/$productId'] +declare const ProductsRootRoute: OwnRoutesById['@route-modules/products:'] + +describe('module route types', () => { + test('ids are qualified, full paths are module-local', () => { + expectTypeOf( + ProductRoute.id, + ).toEqualTypeOf<'@route-modules/products:/$productId'>() + expectTypeOf(ProductRoute.fullPath).toEqualTypeOf<'/$productId'>() + expectTypeOf( + ProductsRootRoute.id, + ).toEqualTypeOf<'@route-modules/products:'>() + }) + + test('route-bound hooks resolve through the module scope', () => { + const product = ProductRoute.useLoaderData() + expectTypeOf(product).not.toBeAny() + expectTypeOf(product).toEqualTypeOf() + expectTypeOf(product.price).toEqualTypeOf() + + expectTypeOf(ProductRoute.useParams()).toEqualTypeOf<{ + productId: string + }>() + expectTypeOf(ProductRoute.useSearch()).toEqualTypeOf<{ + tab: 'specs' | 'reviews' + }>() + expectTypeOf(ProductRoute.useRouteContext()).toEqualTypeOf<{ + productsApi: ProductsApi + }>() + }) + + test('the module root requires its router context', () => { + expectTypeOf(ProductsRootRoute.types.routerContext).toEqualTypeOf<{ + productsApi: ProductsApi + }>() + }) +}) + +describe('scoped path-based APIs', () => { + test('Link takes module-local paths only', () => { + ; + ; + ; + // @ts-expect-error unknown module-local path + ; + // @ts-expect-error final application paths are not module-local paths + ; + // @ts-expect-error missing params + ; + // @ts-expect-error required search input is missing + ; + ; + }) + + test('useNavigate, redirect and linkOptions use the module router', () => { + const navigate = productsUseNavigate() + navigate({ to: '/$productId', params: { productId: '1' } }) + // @ts-expect-error unknown module-local path + navigate({ to: '/nope' }) + + productsRedirect({ to: '/compare', search: { ids: [] } }) + // @ts-expect-error required search input is missing + productsRedirect({ to: '/compare' }) + + productsLinkOptions({ to: '/$productId', params: { productId: '1' } }) + // @ts-expect-error unknown module-local path + productsLinkOptions({ to: '/nope' }) + }) + + test('the scoped router view navigates in module coordinates', () => { + const router = productsUseRouter() + expectTypeOf(router).toEqualTypeOf>() + router.navigate({ to: '/compare', search: { ids: ['1'] } }) + // @ts-expect-error unknown module-local path + router.navigate({ to: '/nope' }) + }) + + test('Route.Link and Route.useNavigate are module-local', () => { + ; + ; + // @ts-expect-error unknown module-local path + ; + const navigate = ProductRoute.useNavigate() + navigate({ to: '/compare', search: { ids: [] } }) + // @ts-expect-error unknown module-local path + navigate({ to: '/nope' }) + }) +}) + +describe('scoped id-based APIs', () => { + test('getRouteApi and hooks take qualified ids', () => { + const product = productsGetRouteApi( + '@route-modules/products:/$productId', + ).useLoaderData() + expectTypeOf(product).toEqualTypeOf() + expectTypeOf( + productsUseLoaderData({ from: '@route-modules/products:/$productId' }), + ).toEqualTypeOf() + // @ts-expect-error unknown qualified id + productsGetRouteApi('@route-modules/products:/nope') + // @ts-expect-error module-local paths are not route ids + productsGetRouteApi('/$productId') + }) +}) + +describe('a module that uses another module', () => { + test('the namespace links into the used module', () => { + ; + // @ts-expect-error account paths are not products paths + ; + ; + // @ts-expect-error products paths are not account paths + ; + }) + + test('both modules own "/" without colliding', () => { + ; + ; + }) + + test('used module routes are visible by qualified id', () => { + expectTypeOf( + accountGetRouteApi('@route-modules/products:/$productId').useLoaderData(), + ).toEqualTypeOf() + expectTypeOf( + accountGetRouteApi( + '@route-modules/account:/orders/$orderId', + ).useLoaderData(), + ).toEqualTypeOf<{ orderId: string; productId: string }>() + }) +}) + +describe('a module mounted under path params', () => { + test('the actual generated host namespace takes host and module params', () => { + ; + ; + // @ts-expect-error the host parameter is missing + ; + // @ts-expect-error a route without local params still needs host params + ; + hostedTeam.linkOptions({ to: '/', params: { orgId: 'acme' } }) + }) + + test('the published module-local API does not require host params', () => { + ; + ; + }) +}) + +describe('the application', () => { + type AppRouter = ReturnType + + test('addresses its own routes by path and module routes by id', () => { + ; + to="/orgs/$orgId" + params={{ orgId: 'acme' }} + /> + ; + // @ts-expect-error module routes are not addressed by final path + to="/shop/products/$productId" + /> + expectTypeOf( + useMatch({ + from: '@route-modules/products:/$productId', + }).loaderData, + ).toEqualTypeOf() + }) +}) diff --git a/e2e/react-router/route-modules/packages/web/type-tests/scope-contracts.tsx b/e2e/react-router/route-modules/packages/web/type-tests/scope-contracts.tsx new file mode 100644 index 0000000000..7ce5a914ef --- /dev/null +++ b/e2e/react-router/route-modules/packages/web/type-tests/scope-contracts.tsx @@ -0,0 +1,96 @@ +import * as React from 'react' +import { expectTypeOf, test } from 'vitest' +import { orgSettings, personSettings } from '../src/routeScope.gen' +import * as settings from '@route-modules/settings/scope' + +test('reusable options preserve their installation through spreads and arrays', () => { + const user = personSettings.linkOptions({ + to: '/members', + params: () => ({ personId: 'u1', orgId: '7' }), + }) + expectTypeOf( + user._module, + ).toEqualTypeOf<'@route-modules/settings#personSettings'>() + const same = + const { _module, ...neutral } = user + const compatiblePathsAndParams = + void compatiblePathsAndParams + void _module + // @ts-expect-error An explicit sibling installation is a conflicting scope. + const different = + // @ts-expect-error Rewrapping must not erase the conflicting scope. + orgSettings.linkOptions({ ...user }) + // @ts-expect-error Arrays preserve each entry's destination scope. + orgSettings.linkOptions([user]) + // @ts-expect-error Redirects enforce the same receiving-scope contract. + orgSettings.redirect(user) + orgSettings.linkOptions({ + to: '/members', + params: { orgId: '7' }, + // @ts-expect-error A mask cannot silently retarget another installation's options. + mask: user, + }) + // @ts-expect-error Hook defaults must retain and check a reusable scope stamp. + orgSettings.useNavigate({ ...user, from: '/profile' }) + // @ts-expect-error The callback checks the same destination stamp. + orgSettings.useNavigate()(user) + void same + void different +}) + +test('module-typed helper targets only known route IDs', () => { + settings.notFound({ routeId: '@route-modules/settings:' }) + settings.notFound() + // @ts-expect-error This route is not declared by the module. + settings.notFound({ routeId: '@route-modules/settings:/absent' }) +}) + +test('blocker locations describe the entire application and raw URL values', () => { + settings.useBlocker({ + shouldBlockFn: ({ current, next }) => { + expectTypeOf(current.routeId).toEqualTypeOf() + expectTypeOf(next.fullPath).toEqualTypeOf() + expectTypeOf(next.params).toEqualTypeOf< + Record + >() + expectTypeOf(next.search).toEqualTypeOf>() + return false + }, + }) +}) + +test('match selectors expose foreign data and the generated guard restores known data', () => { + settings.useMatch({ + strict: false, + select: (match) => { + expectTypeOf(match.context).toBeUnknown() + expectTypeOf(match.loaderData).toBeUnknown() + return match.routeId + }, + }) + settings.useMatches({ + select: (matches) => { + expectTypeOf(matches[0]!.context).toBeUnknown() + for (const match of matches) { + if ( + settings.isScopedMatch(match) && + match.localRouteId === '@route-modules/settings:/members' + ) { + expectTypeOf(match.loaderData).toEqualTypeOf< + { label: 'members' } | undefined + >() + expectTypeOf(match.fullPath).toEqualTypeOf() + } + } + return matches.length + }, + }) +}) + +test('MatchRoute accepts only the scope paths in JSX', () => { + const own = + // @ts-expect-error This path is not a module route. + const foreign = + void own + void foreign +}) diff --git a/e2e/react-router/route-modules/packages/web/type-tests/validation-aliases.tsx b/e2e/react-router/route-modules/packages/web/type-tests/validation-aliases.tsx new file mode 100644 index 0000000000..34bc1dec8d --- /dev/null +++ b/e2e/react-router/route-modules/packages/web/type-tests/validation-aliases.tsx @@ -0,0 +1,110 @@ +import { expectTypeOf, test } from 'vitest' +import type { orgSettings } from '../src/routeScope.gen' + +test('every generated validation alias preserves its namespace contract', () => { + type Options = { to: '/profile'; params: { orgId: '7' } } + const options: Options = { to: '/profile', params: { orgId: '7' } } + const link: orgSettings.ValidateLinkOptions = options + const links: orgSettings.ValidateLinkOptionsArray = [ + options, + ] + const navigate: orgSettings.ValidateNavigateOptions = options + const navigations: orgSettings.ValidateNavigateOptionsArray< + readonly [Options] + > = [options] + const redirect: orgSettings.ValidateRedirectOptions = options + const redirects: orgSettings.ValidateRedirectOptionsArray< + readonly [Options] + > = [options] + expectTypeOf().toMatchTypeOf() + expectTypeOf().toMatchTypeOf() + expectTypeOf().toMatchTypeOf() + expectTypeOf().toMatchTypeOf() + expectTypeOf().toMatchTypeOf() + expectTypeOf().toMatchTypeOf() + + const from: orgSettings.ValidateFromPath<'/profile'> = '/profile' + const to: orgSettings.ValidateToPath<'/profile'> = '/profile' + const search: orgSettings.ValidateSearch<'/search'> = { + search: { query: 'hello' }, + } + const params: orgSettings.ValidateParams<'/profile'> = { + params: { orgId: '7' }, + } + const id: orgSettings.ValidateId<'@route-modules/settings:/profile'> = + '@route-modules/settings:/profile' + const useSearch: orgSettings.ValidateUseSearchOptions<{ + from: '@route-modules/settings:/profile' + }> = { from: '@route-modules/settings:/profile' } + const useParams: orgSettings.ValidateUseParamsOptions<{ + from: '@route-modules/settings:/profile' + }> = { from: '@route-modules/settings:/profile' } + void [from, to, search, params, id, useSearch, useParams] + + const foreignPath = { + to: '/orgs/$orgId', + params: { orgId: '7' }, + } as const + const foreignPaths = [foreignPath] as const + const foreignOrigin = { from: '/orgs/$orgId' } as const + const wrongSearch = { search: { query: 42 } } + const wrongParams = { params: { userId: 'u1' } } + + // @ts-expect-error The validation alias is bound to this module's paths. + const invalidLink: orgSettings.ValidateLinkOptions = + foreignPath + // @ts-expect-error Tuple entries retain the generated scope. + const invalidLinks: orgSettings.ValidateLinkOptionsArray< + typeof foreignPaths + > = foreignPaths + // @ts-expect-error Navigation wrappers cannot escape the module paths. + const invalidNavigate: orgSettings.ValidateNavigateOptions< + typeof foreignPath + > = foreignPath + // @ts-expect-error Every navigation array entry is checked. + const invalidNavigations: orgSettings.ValidateNavigateOptionsArray< + typeof foreignPaths + > = foreignPaths + // @ts-expect-error Redirect wrappers retain module path validation. + const invalidRedirect: orgSettings.ValidateRedirectOptions< + typeof foreignPath + > = foreignPath + // @ts-expect-error Every redirect array entry is checked. + const invalidRedirects: orgSettings.ValidateRedirectOptionsArray< + typeof foreignPaths + > = foreignPaths + // @ts-expect-error A route origin must be a path in the module. + const invalidFrom: orgSettings.ValidateFromPath<'/profile'> = '/orgs/$orgId' + // @ts-expect-error A destination must be a path in the module. + const invalidTo: orgSettings.ValidateToPath<'/profile'> = '/orgs/$orgId' + // @ts-expect-error Search validation follows the generated route schema. + const invalidSearch: orgSettings.ValidateSearch<'/search'> = wrongSearch + // @ts-expect-error The named installation requires its own host parameter. + const invalidParams: orgSettings.ValidateParams<'/profile'> = wrongParams + // @ts-expect-error A foreign route ID is not a module route. + const invalidId: orgSettings.ValidateId<'@route-modules/settings:/profile'> = + '/orgs/$orgId' + // @ts-expect-error Search selectors must name a route in this module. + const invalidUseSearch: orgSettings.ValidateUseSearchOptions< + typeof foreignOrigin + > = foreignOrigin + // @ts-expect-error Parameter selectors must name a route in this module. + const invalidUseParams: orgSettings.ValidateUseParamsOptions< + typeof foreignOrigin + > = foreignOrigin + void [ + invalidLink, + invalidLinks, + invalidNavigate, + invalidNavigations, + invalidRedirect, + invalidRedirects, + invalidFrom, + invalidTo, + invalidSearch, + invalidParams, + invalidId, + invalidUseSearch, + invalidUseParams, + ] +}) diff --git a/e2e/react-router/route-modules/packages/web/vite.config.ts b/e2e/react-router/route-modules/packages/web/vite.config.ts new file mode 100644 index 0000000000..02d676f946 --- /dev/null +++ b/e2e/react-router/route-modules/packages/web/vite.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import { tanstackRouter } from '@tanstack/router-plugin/vite' + +// The router plugin reads `tsr.config.json`, including the route modules this +// application mounts. +export default defineConfig({ + plugins: [ + tanstackRouter({ target: 'react', autoCodeSplitting: true }), + react(), + ], +}) diff --git a/e2e/react-router/route-modules/playwright.config.ts b/e2e/react-router/route-modules/playwright.config.ts new file mode 100644 index 0000000000..7c30ba6f79 --- /dev/null +++ b/e2e/react-router/route-modules/playwright.config.ts @@ -0,0 +1,29 @@ +import { defineConfig, devices } from '@playwright/test' +import { appServerReady } from '@tanstack/router-e2e-utils' + +const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const baseURL = `http://localhost:${PORT}` +// Publish the route modules, then build and serve the application that mounts +// them. Only the application is bundled; modules are compiled from source. +const command = `node scripts/prepare.mjs && pnpm --filter @route-modules/web build && pnpm --filter @route-modules/web exec vite preview --host 0.0.0.0 --port ${PORT}` + +export default defineConfig({ + testDir: './e2e', + workers: 1, + reporter: [['line']], + use: { + baseURL, + }, + webServer: { + command, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/react-router/route-modules/playwright.dev.config.ts b/e2e/react-router/route-modules/playwright.dev.config.ts new file mode 100644 index 0000000000..a244db6ea7 --- /dev/null +++ b/e2e/react-router/route-modules/playwright.dev.config.ts @@ -0,0 +1,29 @@ +import { defineConfig, devices } from '@playwright/test' +import { appServerReady } from '@tanstack/router-e2e-utils' + +const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const baseURL = `http://localhost:${PORT}` +// Development: the application's dev server compiles module route files from +// their packages, code-splits them and hot-updates them. +const command = `node scripts/prepare.mjs && pnpm --filter @route-modules/web exec vite --host 0.0.0.0 --port ${PORT}` + +export default defineConfig({ + testDir: './e2e-dev', + workers: 1, + reporter: [['line']], + use: { + baseURL, + }, + webServer: { + command, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/react-router/route-modules/scripts/prepare.mjs b/e2e/react-router/route-modules/scripts/prepare.mjs new file mode 100644 index 0000000000..20d431c48c --- /dev/null +++ b/e2e/react-router/route-modules/scripts/prepare.mjs @@ -0,0 +1,49 @@ +// Generates routes and builds declarations in dependency order using the +// fixture packages' ordinary TypeScript build. +// +// The modules list `@tanstack/router-core` as a dev dependency only because +// the fixture links `@tanstack/react-router` from the workspace: TypeScript +// names the types of a linked package's dependencies by their own package +// name. Installed from a registry, the declarations name them through +// `@tanstack/react-router`, the only router package modules need. +import { spawnSync } from 'node:child_process' +import { rmSync } from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { Generator, getConfig } from '@tanstack/router-generator' + +const packages = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../packages', +) + +const tsc = path.resolve( + packages, + '../../../../node_modules/.bin', + process.platform === 'win32' ? 'tsc.cmd' : 'tsc', +) + +for (const name of [ + 'products', + 'storefront', + 'account', + 'team', + 'settings', + 'billing', +]) { + const root = path.join(packages, name) + const config = getConfig({ disableLogging: true }, root) + await new Generator({ config, root }).run() + rmSync(path.join(root, '.tanstack/types'), { recursive: true, force: true }) + const result = spawnSync( + tsc, + ['-p', 'tsconfig.route-types.json', '--pretty', 'false'], + { cwd: root, stdio: 'inherit', shell: process.platform === 'win32' }, + ) + if (result.error) { + throw result.error + } + if (result.status !== 0) { + process.exit(result.status ?? 1) + } +} diff --git a/e2e/react-router/route-modules/tests/generated-api-bundles.test.ts b/e2e/react-router/route-modules/tests/generated-api-bundles.test.ts new file mode 100644 index 0000000000..2c451cea8d --- /dev/null +++ b/e2e/react-router/route-modules/tests/generated-api-bundles.test.ts @@ -0,0 +1,446 @@ +import fs from 'node:fs/promises' +import os from 'node:os' +import path from 'node:path' +import { realpathSync } from 'node:fs' +import { spawnSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' +import { brotliCompressSync, gzipSync } from 'node:zlib' +import { afterEach, expect, test } from 'vitest' +import { Generator, getConfig } from '@tanstack/router-generator' +import { build } from 'vite' +import solid from 'vite-plugin-solid' + +type Framework = 'react' | 'solid' | 'vue' +const repository = fileURLToPath(new URL('../../../../', import.meta.url)) +const workspaces: Array = [] +const neutralEntry = `globalThis.__routeModuleBundleProbe = 'retained'` + +afterEach(async () => { + for (const workspace of workspaces.splice(0)) { + await fs.rm(workspace, { recursive: true, force: true }) + } +}) + +async function write(file: string, source: string) { + await fs.mkdir(path.dirname(file), { recursive: true }) + await fs.writeFile(file, source) +} + +async function link(root: string, name: string, target: string) { + const file = path.join(root, 'node_modules', name) + await fs.mkdir(path.dirname(file), { recursive: true }) + await fs.symlink(target, file, 'dir') +} + +async function fixtures(framework: Framework) { + const workspace = realpathSync( + await fs.mkdtemp(path.join(os.tmpdir(), 'route-module-bundles-')), + ) + workspaces.push(workspace) + // Third-party dependencies resolve exactly as in the installed workspace; + // framework imports below still go through their published package exports. + await fs.symlink( + path.join(repository, 'node_modules'), + path.join(workspace, 'node_modules'), + 'dir', + ) + const routerPackage = `@tanstack/${framework}-router` + const startPackage = `@tanstack/${framework}-start` + const dependency = path.join(workspace, 'dependency') + const provider = path.join(workspace, 'provider') + const host = path.join(workspace, 'host') + for (const [root, name, isModule] of [ + [dependency, '@bundle/dependency', true], + [provider, '@bundle/provider', true], + [host, '@bundle/host', false], + ] as const) { + await write( + path.join(root, 'package.json'), + JSON.stringify({ + name, + type: 'module', + dependencies: { + [routerPackage]: '*', + ...(root === provider + ? { [startPackage]: '*', '@bundle/dependency': '*' } + : {}), + ...(root === host + ? { '@bundle/provider': '*', '@bundle/dependency': '*' } + : {}), + }, + exports: { + './route-module': './src/routeModule.gen.ts', + './route-types': './src/routeContract.gen.ts', + }, + ...(isModule + ? { + tanstack: { + router: { + module: + root === provider ? { uses: ['@bundle/dependency'] } : true, + }, + }, + } + : {}), + }), + ) + await link( + root, + routerPackage, + path.join(repository, 'packages', `${framework}-router`), + ) + if (root === provider) { + await link( + root, + startPackage, + path.join(repository, 'packages', `${framework}-start`), + ) + } + await write( + path.join(root, 'src/routes/__root.tsx'), + isModule + ? `import { createModuleRoot } from '../routeScope.gen' +${root === provider ? "export type {} from '../requirements'" : ''} +export const Route = createModuleRoot()({})` + : `import { createRootRoute } from '${routerPackage}' +export const Route = createRootRoute()`, + ) + if (isModule) { + await write( + path.join(root, 'src/routes/page.tsx'), + `import { createFileRoute } from '../routeScope.gen' +export const Route = createFileRoute('${name}:/page')({})`, + ) + } + } + await link(provider, '@bundle/dependency', dependency) + await link(host, '@bundle/provider', provider) + await link(host, '@bundle/dependency', dependency) + await write( + path.join(provider, 'src/requirements.ts'), + `export type { StartModuleRequirements } from '${startPackage}' +declare module '${startPackage}' { + interface StartModuleRequirements { + '@bundle/provider': { requestContext: { requiredByBundleFixture: string } } + } +}`, + ) + for (const root of [dependency, provider, host]) { + const config = getConfig( + { + target: framework, + disableLogging: true, + routesDirectory: './src/routes', + generatedRouteTree: './src/routeTree.gen.ts', + ...(root === host + ? { + routeModules: { + includes: [ + { module: '@bundle/provider', at: '/provider' }, + { module: '@bundle/dependency', at: '/dependency' }, + ], + }, + } + : {}), + }, + root, + ) + await new Generator({ root, config }).run() + } + return { workspace, provider, host, routerPackage, startPackage } +} + +interface Bundle { + source: string + code: string + moduleIds: Array + raw: number + gzip: number + brotli: number +} + +async function bundle( + framework: Framework, + root: string, + name: string, + entry: string, +): Promise { + const directory = path.join(root, 'bundle-cases', name) + const input = path.join(directory, 'index.html') + await write(path.join(directory, 'entry.ts'), entry) + await write( + input, + '', + ) + const output: Array = [] + const moduleIds = new Set() + for (const minify of [false, true]) { + const result = await build({ + root: directory, + configFile: false, + mode: 'production', + plugins: framework === 'solid' ? [solid({ dev: false })] : [], + resolve: { + conditions: [ + ...(framework === 'solid' ? ['solid'] : []), + 'module', + 'browser', + 'production', + ], + }, + logLevel: 'silent', + define: { 'process.env.NODE_ENV': JSON.stringify('production') }, + build: { + write: false, + minify, + sourcemap: false, + rolldownOptions: { input }, + }, + }) + if (!('output' in result)) { + throw new Error('Expected a single application bundle') + } + for (const chunk of result.output) { + if (chunk.type === 'chunk') { + for (const id of Object.keys(chunk.modules)) { + moduleIds.add(id.replaceAll('\\', '/')) + } + } + } + output.push( + result.output + .filter((file) => file.type === 'chunk') + .map((file) => file.code) + .join('\n'), + ) + } + const code = output[1]! + return { + source: output[0]!, + code, + moduleIds: [...moduleIds], + raw: Buffer.byteLength(code), + gzip: gzipSync(code).byteLength, + brotli: brotliCompressSync(code).byteLength, + } +} + +const scopedApis = [ + 'Link', + 'CreateLink', + 'LinkOptions', + 'Navigate', + 'UseNavigate', + 'Redirect', + 'MatchRoute', + 'UseMatchRoute', + 'UseRouter', + 'GetRouteApi', + 'UseMatch', + 'UseMatches', + 'UseParentMatches', + 'UseChildMatches', + 'UseLoaderData', + 'UseLoaderDeps', + 'UseSearch', + 'UseParams', + 'UseRouteContext', + 'UseLocation', + 'UseRouterState', + 'UseLinkProps', + 'UseBlocker', + 'NotFound', +] + +function expectIndependentApi(result: Bundle, retained?: string) { + for (const api of scopedApis) { + if (api !== retained) { + expect(result.source).not.toMatch( + new RegExp(`\\bfunction\\s+bindRouteScope${api}\\b`), + ) + } + } +} + +function sizes(bundle: Bundle) { + return { raw: bundle.raw, gzip: bundle.gzip, brotli: bundle.brotli } +} + +test.each(['react', 'solid', 'vue'] as const)( + '%s generated APIs and static namespaces discard unused initializers', + async (framework) => { + const { provider, host, routerPackage, startPackage } = + await fixtures(framework) + const own = JSON.stringify(path.join(provider, 'src/routeScope.gen.ts')) + const namespaces = JSON.stringify(path.join(host, 'src/routeScope.gen.ts')) + const results: Record> = {} + const measure = async (name: string, entry: string) => { + const result = await bundle(framework, provider, name, entry) + results[name] = sizes(result) + return result + } + const neutral = await measure('neutral', neutralEntry) + for (const [name, entry] of [ + ['unused-own-scope', `import ${own}; ${neutralEntry}`], + ['unused-namespaces', `import ${namespaces}; ${neutralEntry}`], + [ + 'type-only-validator', + `import type { ValidateLinkOptions } from ${own}; ${neutralEntry}`, + ], + [ + 'type-only-requirements', + `import ${JSON.stringify(path.join(provider, 'src/requirements.ts'))}; ${neutralEntry}`, + ], + ]) { + const result = await measure(name!, entry!) + expect(result.code).toBe(neutral.code) + } + + // Import the direct API first in both cases to stabilize bundler naming. + // The second reference proves the generated alias adds no runtime wrapper. + const directFactory = await measure( + 'framework-file-factory', + `import { createFileRoute } from '${routerPackage}'; globalThis.__routeModuleBundleProbe = [createFileRoute, createFileRoute]`, + ) + const scopedFactory = await measure( + 'generated-file-factory', + `import { createFileRoute } from '${routerPackage}'; import { createFileRoute as scoped } from ${own}; globalThis.__routeModuleBundleProbe = [createFileRoute, scoped]`, + ) + expectIndependentApi(scopedFactory) + expect(scopedFactory.source).not.toContain('@bundle/provider') + expect(sizes(scopedFactory)).toEqual(sizes(directFactory)) + const moduleRootFactory = await measure( + 'generated-module-root', + `import { createModuleRoot } from ${own}; globalThis.__routeModuleBundleProbe = createModuleRoot`, + ) + expectIndependentApi(moduleRootFactory) + expect(moduleRootFactory.source).not.toMatch( + /\bfunction\s+createFileRoute\b/, + ) + + const ownOptions = await measure( + 'own-link-options', + `import { linkOptions } from ${own}; globalThis.__routeModuleBundleProbe = linkOptions({ to: '/page' })`, + ) + const namespaceOptions = await measure( + 'namespace-link-options', + `import { provider } from ${namespaces}; globalThis.__routeModuleBundleProbe = provider.linkOptions({ to: '/page' })`, + ) + expectIndependentApi(ownOptions, 'LinkOptions') + expectIndependentApi(namespaceOptions, 'LinkOptions') + expect(sizes(namespaceOptions)).toEqual(sizes(ownOptions)) + + for (const [api, suffix] of [ + ['Link', 'Link'], + ['Navigate', 'Navigate'], + ['getRouteApi', 'GetRouteApi'], + ['useRouter', 'UseRouter'], + ['useLinkProps', 'UseLinkProps'], + ['useBlocker', 'UseBlocker'], + ['notFound', 'NotFound'], + ]) { + const result = await measure( + api!, + `import { ${api} } from ${own}; globalThis.__routeModuleBundleProbe = ${api}`, + ) + expectIndependentApi(result, suffix) + if (framework === 'solid' && api === 'Link') { + // Real Solid applications select source exports and compile their JSX. + expect(result.moduleIds).toContain( + path + .join( + repository, + 'packages/solid-router/dist/source/routeModule.jsx', + ) + .replaceAll('\\', '/'), + ) + } + const namespace = await measure( + `namespace-${api}`, + `import { provider } from ${namespaces}; globalThis.__routeModuleBundleProbe = provider.${api}`, + ) + expectIndependentApi(namespace, suffix) + expect(sizes(namespace)).toEqual(sizes(result)) + } + for (const api of ['createServerFn', 'createMiddleware']) { + const direct = await measure( + `framework-${api}`, + `import { ${api} } from '${startPackage}'; globalThis.__routeModuleBundleProbe = [${api}, ${api}]`, + ) + const generated = await measure( + `generated-${api}`, + `import { ${api} } from '${startPackage}'; import { ${api} as scoped } from ${own}; globalThis.__routeModuleBundleProbe = [${api}, scoped]`, + ) + expectIndependentApi(generated) + expect(sizes(generated)).toEqual(sizes(direct)) + } + const fragmentFactory = await measure( + 'createStartModule', + `import { createStartModule } from ${own}; globalThis.__routeModuleBundleProbe = createStartModule`, + ) + expectIndependentApi(fragmentFactory) + expect(fragmentFactory.source).not.toContain('requiredByBundleFixture') + + // Keep real production-byte evidence in the test log for before/after + // comparison; assertion builds include all runtime dependencies, no externals. + console.info(JSON.stringify({ generatedApiBundles: framework, results })) + }, +) + +test.each(['react', 'solid', 'vue'] as const)( + '%s requirements augmentation emits declarations without runtime imports', + async (framework) => { + const { provider } = await fixtures(framework) + await write( + path.join(provider, 'tsconfig.requirements.json'), + JSON.stringify({ + compilerOptions: { + target: 'ES2022', + module: 'ESNext', + moduleResolution: 'Bundler', + strict: true, + skipLibCheck: false, + declaration: true, + rootDir: './src', + outDir: './emitted-requirements', + types: ['node'], + }, + files: ['src/requirements.ts'], + }), + ) + const result = spawnSync( + process.execPath, + [ + path.join(repository, 'node_modules/typescript59/lib/tsc.js'), + '--pretty', + 'false', + '-p', + path.join(provider, 'tsconfig.requirements.json'), + ], + { encoding: 'utf8' }, + ) + if (result.error) { + throw result.error + } + expect({ + status: result.status, + diagnostics: result.stdout + result.stderr, + }).toEqual({ status: 0, diagnostics: '' }) + expect( + ( + await fs.readFile( + path.join(provider, 'emitted-requirements/requirements.js'), + 'utf8', + ) + ).trim(), + ).toBe('export {};') + const declaration = await fs.readFile( + path.join(provider, 'emitted-requirements/requirements.d.ts'), + 'utf8', + ) + expect(declaration).toContain( + `declare module '@tanstack/${framework}-start'`, + ) + expect(declaration).toContain('requiredByBundleFixture') + }, +) diff --git a/e2e/react-router/route-modules/tests/generated-scope-cache.test.ts b/e2e/react-router/route-modules/tests/generated-scope-cache.test.ts new file mode 100644 index 0000000000..91244879b2 --- /dev/null +++ b/e2e/react-router/route-modules/tests/generated-scope-cache.test.ts @@ -0,0 +1,114 @@ +import { execFileSync } from 'node:child_process' +import { symlinkSync } from 'node:fs' +import { pathToFileURL } from 'node:url' +import { expect, test } from 'vitest' +import { build } from 'vite' +import { Workspace } from './workspace' + +test('a generated package named constructor gets a working scoped router', async () => { + const ws = new Workspace(['settings', 'web']) + try { + // A valid unscoped package name must work even when it is also a property + // of Object.prototype. Generate the provider and host exactly as packages do. + ws.edit('settings', 'package.json', (source) => { + const pkg = JSON.parse(source) + pkg.name = 'constructor' + return JSON.stringify(pkg) + }) + ws.remove('settings', 'src') + ws.write( + 'settings', + 'src/routes/__root.tsx', + `import { createModuleRoot } from '../routeScope.gen' +export const Route = createModuleRoot()({}) +`, + ) + ws.write( + 'settings', + 'src/routes/profile.tsx', + `import { createFileRoute } from '../routeScope.gen' +export const Route = createFileRoute('constructor:/profile')({}) +`, + ) + + ws.edit('web', 'package.json', (source) => { + const pkg = JSON.parse(source) + for (const dependency of Object.keys(pkg.dependencies)) { + if (dependency.startsWith('@route-modules/')) { + delete pkg.dependencies[dependency] + } + } + pkg.dependencies.constructor = 'workspace:*' + return JSON.stringify(pkg) + }) + symlinkSync( + ws.pkg('settings'), + ws.file('web', 'node_modules/constructor'), + 'dir', + ) + ws.remove('web', 'src') + ws.write( + 'web', + 'tsr.config.json', + JSON.stringify({ + routeModules: { + includes: [{ module: 'constructor', at: '/settings' }], + }, + }), + ) + ws.write( + 'web', + 'src/routes/__root.tsx', + `import { createRootRoute } from '@tanstack/react-router' +export const Route = createRootRoute() +`, + ) + ws.write( + 'web', + 'src/probe.tsx', + `import * as React from 'react' +import { renderToString } from 'react-dom/server' +import { RouterContextProvider, createMemoryHistory, createRouter } from '@tanstack/react-router' +import { useRouter } from 'constructor/scope' +import { routeTree } from './routeTree.gen' + +export async function render() { + const router = createRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/settings/profile'] }), + isServer: true, + }) + await router.load() + function Observer() { + return {useRouter().buildLocation({ to: '/profile' }).href} + } + return renderToString() +} +`, + ) + await ws.buildGraph(['settings', 'web'], ['settings']) + await build({ + root: ws.pkg('web'), + configFile: false, + logLevel: 'silent', + ssr: { noExternal: ['constructor'] }, + build: { + ssr: ws.file('web', 'src/probe.tsx'), + outDir: ws.file('web', 'dist'), + rolldownOptions: { output: { entryFileNames: 'probe.mjs' } }, + }, + }) + const output = execFileSync( + process.execPath, + [ + '--input-type=module', + '--eval', + `import { render } from ${JSON.stringify(pathToFileURL(ws.file('web', 'dist/probe.mjs')).href)}; console.log(JSON.stringify(await render()));`, + ], + { cwd: ws.pkg('web'), encoding: 'utf8' }, + ) + expect(JSON.parse(output)).toBe('/settings/profile') + } finally { + ws.dispose() + } +}) diff --git a/e2e/react-router/route-modules/tests/host-context-contracts.test.ts b/e2e/react-router/route-modules/tests/host-context-contracts.test.ts new file mode 100644 index 0000000000..bcf02dd04c --- /dev/null +++ b/e2e/react-router/route-modules/tests/host-context-contracts.test.ts @@ -0,0 +1,52 @@ +import { afterEach, expect, test } from 'vitest' +import { Workspace, errorsIn } from './workspace' + +let workspace: Workspace | undefined + +afterEach(() => { + workspace?.dispose() + workspace = undefined +}) + +test('generated mounts reject incompatible context and required host search', async () => { + const ws = (workspace = new Workspace()) + const modules = [ + 'products', + 'storefront', + 'account', + 'team', + 'settings', + 'billing', + ] + await ws.buildGraph([...modules, 'web'], modules) + const originalAuthentication = ws.read('web', 'src/routes/_authenticated.tsx') + ws.edit('web', 'src/routes/_authenticated.tsx', (source) => { + expect(source).toContain("user: { id: 'u-1' }") + return source.replace("user: { id: 'u-1' }", "user: 'invalid-context'") + }) + const incompatible = await ws.check('web') + expect(incompatible.ok).toBe(false) + expect( + errorsIn(incompatible.diagnostics, 'src/routeTree.gen.ts').join('\n'), + ).toMatch(/compatible types/) + + ws.write('web', 'src/routes/_authenticated.tsx', originalAuthentication) + const originalOrganization = ws.read('web', 'src/routes/orgs.$orgId.tsx') + ws.edit('web', 'src/routes/orgs.$orgId.tsx', (source) => { + expect(source).toContain(' beforeLoad:') + return source.replace( + ' beforeLoad:', + ' validateSearch: (search: { region: string }) => search,\n beforeLoad:', + ) + }) + const requiredSearch = await ws.check('web') + expect(requiredSearch.ok).toBe(false) + expect( + errorsIn(requiredSearch.diagnostics, 'src/routeTree.gen.ts').join('\n'), + ).toMatch(/requires search params/) + + ws.write('web', 'src/routes/orgs.$orgId.tsx', originalOrganization) + const valid = await ws.check('web') + expect(valid.diagnostics).toEqual([]) + expect(valid.ok).toBe(true) +}) diff --git a/e2e/react-router/route-modules/tests/host-parameter-contracts.test.ts b/e2e/react-router/route-modules/tests/host-parameter-contracts.test.ts new file mode 100644 index 0000000000..416c018105 --- /dev/null +++ b/e2e/react-router/route-modules/tests/host-parameter-contracts.test.ts @@ -0,0 +1,73 @@ +import { afterEach, expect, test } from 'vitest' +import { Workspace, errorsIn } from './workspace' + +let workspace: Workspace | undefined + +afterEach(() => { + workspace?.dispose() + workspace = undefined +}) + +test('generated mounts reject a parsed host key overwritten by module descendants', async () => { + const ws = (workspace = new Workspace()) + ws.write( + 'settings', + 'src/routes/members.$memberId.tsx', + `import { createFileRoute } from '../routeScope.gen' +export const Route = createFileRoute('@route-modules/settings:/members/$memberId')({ + loader: ({ params }) => ({ member: params.memberId }), +}) +`, + ) + ws.edit('web', 'src/routes/orgs.$orgId.tsx', (source) => { + expect(source).toContain(' beforeLoad:') + return source.replace( + ' beforeLoad:', + ` params: { + parse: ({ orgId }) => ({ orgId, memberId: 'host-member' }), + stringify: ({ orgId }) => ({ orgId }), + }, + beforeLoad:`, + ) + }) + const modules = [ + 'products', + 'storefront', + 'account', + 'team', + 'settings', + 'billing', + ] + await ws.buildGraph([...modules, 'web'], modules) + const collision = await ws.check('web') + expect(collision.ok).toBe(false) + expect( + errorsIn(collision.diagnostics, 'src/routeTree.gen.ts').join('\n'), + ).toMatch(/memberId/) + + // A distinct parsed host key is valid. Type changes need only the normal + // consumer recheck; the route topology and generated mount are unchanged. + ws.edit('web', 'src/routes/orgs.$orgId.tsx', (source) => + source.replace( + "memberId: 'host-member'", + "organizationMemberId: 'host-member'", + ), + ) + for (const file of ['src/routes/__root.tsx', 'src/routes/index.tsx']) { + ws.edit('web', file, (source) => + source.replaceAll( + /(params=\{\{ orgId: '[^']+') \}\}/g, + "$1, organizationMemberId: 'host-member' }}", + ), + ) + } + ws.edit('web', 'src/profile-links.tsx', (source) => + source.replace( + "params: { orgId: '7' }", + "params: { orgId: '7', organizationMemberId: 'host-member' }", + ), + ) + const valid = await ws.check('web') + expect(valid.diagnostics).toEqual([]) + expect(valid.ok).toBe(true) +}) diff --git a/e2e/react-router/route-modules/tests/route-modules.test.ts b/e2e/react-router/route-modules/tests/route-modules.test.ts new file mode 100644 index 0000000000..09397d91d4 --- /dev/null +++ b/e2e/react-router/route-modules/tests/route-modules.test.ts @@ -0,0 +1,511 @@ +import path from 'node:path' +import { afterEach, beforeEach, describe, expect, test } from 'vitest' +import { Workspace, errorsIn } from './workspace' + +/** + * The fixture is a diamond: + * + * web ──► storefront ──► products (storefront mounts products) + * └────► account ─────► products (account only links to products) + * + * and modules web mounts below `/orgs/$orgId`, one of them twice: + * + * web ──► team + * ├────► settings (also below `/people/$personId`) + * └────► billing ─────► team (billing only links to team + * └───► settings and to the settings of its org) + * + * Every test copies the packages into a temporary workspace and drives the + * route generation through public APIs, followed by ordinary TypeScript + * declaration builds and source checks. JavaScript is never built. + */ +const order = [ + 'products', + 'storefront', + 'account', + 'team', + 'settings', + 'billing', + 'web', +] +const modules = [ + 'products', + 'storefront', + 'account', + 'team', + 'settings', + 'billing', +] + +let ws: Workspace + +beforeEach(() => { + ws = new Workspace() +}) + +afterEach(() => { + ws.dispose() +}) + +async function expectChecksPass(...names: Array) { + for (const name of names) { + const result = await ws.check(name) + expect(result.diagnostics, `check of ${name}`).toEqual([]) + expect(result.ok).toBe(true) + } +} + +const renamedProductRoute = `import { createFileRoute } from '../routeScope.gen' +import { productSearchSchema } from '../schemas' + +export const Route = createFileRoute('@route-modules/products:/$sku')({ + validateSearch: productSearchSchema, + loader: ({ params, context }) => context.productsApi.getProduct(params.sku), + component: ProductPage, +}) + +function ProductPage() { + const product = Route.useLoaderData() + return

{product.name}

+} +` + +const brandsRoute = `import { createFileRoute } from '../routeScope.gen' + +export const Route = createFileRoute('@route-modules/products:/brands')({ + component: () =>

Brands

, +}) +` + +describe('clean checkout', () => { + test('generates, emits and checks the diamond from nothing', async () => { + for (const name of order) { + expect(ws.exists(name, 'src/routeTree.gen.ts')).toBe(false) + expect(ws.exists(name, '.tanstack')).toBe(false) + } + + await ws.buildGraph(order, modules) + await expectChecksPass(...order) + + expect(ws.log.some((entry) => entry.operation === 'build')).toBe(false) + for (const name of order) { + expect(ws.exists(name, 'dist')).toBe(false) + } + }) + + test('a module checks standalone, without any application', async () => { + const standalone = new Workspace(['products', 'account']) + try { + await standalone.buildGraph( + ['products', 'account'], + ['products', 'account'], + ) + const result = await standalone.check('account') + expect(result.diagnostics).toEqual([]) + } finally { + standalone.dispose() + } + }) + + test.each([ + { name: 'default', header: undefined }, + { name: 'custom', header: ['// Package license header'] }, + { name: 'empty', header: [] }, + ])( + 'emits portable client-view declarations with a $name header', + async ({ header }) => { + for (const name of ['products', 'storefront']) { + if (header !== undefined) { + ws.write( + name, + 'tsr.config.json', + JSON.stringify({ routeTreeFileHeader: header }), + ) + } + await ws.generate(name) + // Both packages use an ordinary src-inclusive declaration build. The + // storefront's client view also references a mounted module's tree. + const emitted = await ws.emitTypes(name) + expect(emitted.diagnostics, `declarations of ${name}`).toEqual([]) + expect(emitted.ok).toBe(true) + expect( + ws.exists(name, '.tanstack/types/src/routeTree.gen.client.d.ts'), + ).toBe(true) + } + await expectChecksPass('products', 'storefront') + }, + ) +}) + +describe('published declaration updates', () => { + test('a provider param rename reaches consumers through unchanged intermediate declarations', async () => { + await ws.buildGraph(order, modules) + const storefrontDeclarations = ws.snapshot('storefront', '.tanstack/types') + const storefrontSources = ws.snapshot('storefront', 'src') + const logBefore = ws.log.length + + // Rename the product route param: products updates its own links, + // regenerates and re-emits. + ws.remove('products', 'src/routes/$productId.tsx') + ws.write('products', 'src/routes/$sku.tsx', renamedProductRoute) + ws.edit('products', 'src/routes/index.tsx', (source) => + source + .replace('to="/$productId"', 'to="/$sku"') + .replace('{ productId: product.id }', '{ sku: product.id }'), + ) + ws.edit('products', 'src/routes/legacy.tsx', (source) => + source + .replace("to: '/$productId'", "to: '/$sku'") + .replace("productId: '42'", "sku: '42'"), + ) + await ws.generate('products') + expect((await ws.emitTypes('products')).ok).toBe(true) + + // Consumers only recheck their source. + const account = await ws.check('account') + expect(account.ok).toBe(false) + expect(errorsIn(account.diagnostics, 'src/routes/index.tsx')).not.toEqual( + [], + ) + expect( + errorsIn(account.diagnostics, 'src/routes/orders.$orderId.tsx'), + ).not.toEqual([]) + + // The application reaches products only through storefront's contract, + // whose declarations were neither regenerated nor re-emitted. + const web = await ws.check('web') + expect(web.ok).toBe(false) + expect( + errorsIn(web.diagnostics, 'src/routes/index.tsx').join('\n'), + ).toMatch(/productId|\$productId/) + expect(ws.snapshot('storefront', '.tanstack/types')).toEqual( + storefrontDeclarations, + ) + expect(ws.snapshot('storefront', 'src')).toEqual(storefrontSources) + expect( + ws.log + .slice(logBefore) + .filter((entry) => entry.pkg !== 'products') + .map((entry) => entry.operation), + ).toEqual(['check', 'check']) + + // Updating the consumer links makes the graph valid again. + ws.edit('account', 'src/routes/index.tsx', (source) => + source + .replace('to="/$productId"', 'to="/$sku"') + .replace("{ productId: 'last-viewed' }", "{ sku: 'last-viewed' }"), + ) + ws.edit('account', 'src/routes/orders.$orderId.tsx', (source) => + source + .replace( + "'@route-modules/products:/$productId'", + "'@route-modules/products:/$sku'", + ) + .replace("to: '/$productId'", "to: '/$sku'") + .replace('{ productId: order.productId }', '{ sku: order.productId }'), + ) + ws.edit('storefront', 'src/routes/index.tsx', (source) => + source + .replace('to="/$productId"', 'to="/$sku"') + .replace("{ productId: 'featured' }", "{ sku: 'featured' }"), + ) + ws.edit('web', 'src/routes/index.tsx', (source) => + source + .replace( + "'@route-modules/products:/$productId'", + "'@route-modules/products:/$sku'", + ) + .replace('to="/$productId"', 'to="/$sku"') + .replace("{ productId: 'home-pick' }", "{ sku: 'home-pick' }"), + ) + await expectChecksPass('account', 'storefront', 'web') + }) + + test('route generation does not depend on declaration emits', async () => { + // Task runners cache generation by its inputs: emitting must not change + // what the next generation writes. + await ws.generate('products') + const manifest = ws.read('products', '.tanstack/route-module.json') + expect((await ws.emitTypes('products')).ok).toBe(true) + await ws.generate('products') + expect(ws.read('products', '.tanstack/route-module.json')).toBe(manifest) + }) + + test('a schema-only edit refreshes types without changing the topology', async () => { + await ws.buildGraph(order, modules) + const routeTree = ws.read('products', 'src/routeTree.gen.ts') + const { topologyToken } = ws.manifest('products') + + // `tab` becomes a required search param; products updates its own link. + ws.edit('products', 'src/schemas.ts', (source) => + source.replace(".default('specs')", ''), + ) + ws.edit('products', 'src/routes/index.tsx', (source) => + source.replace( + 'params={{ productId: product.id }}', + "params={{ productId: product.id }}\n search={{ tab: 'specs' }}", + ), + ) + await ws.generate('products') + expect(ws.read('products', 'src/routeTree.gen.ts')).toBe(routeTree) + expect(ws.manifest('products').topologyToken).toBe(topologyToken) + expect((await ws.emitTypes('products')).ok).toBe(true) + + // Navigations without `tab` now fail; the account link passes `tab`. + const web = await ws.check('web') + expect(errorsIn(web.diagnostics, 'src/routes/index.tsx')).not.toEqual([]) + const storefront = await ws.check('storefront') + expect( + errorsIn(storefront.diagnostics, 'src/routes/index.tsx'), + ).not.toEqual([]) + const account = await ws.check('account') + expect(errorsIn(account.diagnostics, 'src/routes/index.tsx')).toEqual([]) + expect( + errorsIn(account.diagnostics, 'src/routes/orders.$orderId.tsx').join( + '\n', + ), + ).toMatch(/search/) + }) + + test('a deleted provider route fails the obsolete consumer link', async () => { + await ws.buildGraph(order, modules) + + ws.remove('products', 'src/routes/compare.tsx') + await ws.generate('products') + expect( + ws.manifest('products').routes.map((route) => route.id), + ).not.toContain('@route-modules/products:/compare') + expect((await ws.emitTypes('products')).ok).toBe(true) + expect( + ws.exists('products', '.tanstack/types/src/routes/compare.d.ts'), + ).toBe(false) + + const storefront = await ws.check('storefront') + expect(storefront.ok).toBe(false) + expect( + errorsIn(storefront.diagnostics, 'src/routes/index.tsx').join('\n'), + ).toMatch(/compare/) + }) + + test('a new provider route becomes visible to consumers', async () => { + await ws.buildGraph(order, modules) + ws.edit('web', 'src/routes/index.tsx', (source) => + source.replace( + '', + 'Brands\n ', + ), + ) + expect((await ws.check('web')).ok).toBe(false) + + ws.write('products', 'src/routes/brands.tsx', brandsRoute) + await ws.generate('products') + expect((await ws.emitTypes('products')).ok).toBe(true) + await expectChecksPass('web') + }) +}) + +describe('the declaration boundary', () => { + test('consumers load provider declarations, never provider sources', async () => { + await ws.buildGraph(order, modules) + const files = ws.listProgramFiles('account') + expect( + files.some((file) => file.includes('/products/.tanstack/types/')), + ).toBe(true) + expect(files.some((file) => file.includes('/products/src/'))).toBe(false) + }) + + test('consumers check against declarations only, without library skipping', async () => { + await ws.buildGraph(order, modules) + ws.remove('products', 'src') + ws.edit('account', 'tsconfig.json', (source) => + source.replace('"skipLibCheck": true', '"skipLibCheck": false'), + ) + await expectChecksPass('account') + + // A missing declaration fails instead of falling back to sources. + ws.remove('products', '.tanstack/types/src/api.d.ts') + const result = await ws.check('account') + expect(result.ok).toBe(false) + expect(result.diagnostics.join('\n')).toMatch(/\.\/api/) + }) + + test('module types stay precise across the boundary', async () => { + await ws.buildGraph(order, modules) + ws.write( + 'account', + 'src/type-assertions.tsx', + `import { Route as AccountIndexRoute } from './routes/index' +import { getRouteApi, products } from './routeScope.gen' +import type { Price, Product } from '@route-modules/products/api' + +type Equal = + (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 + ? true + : false +type IsAny = 0 extends 1 & T ? true : false + +const productApi = getRouteApi('@route-modules/products:/$productId') + +export function useAssertions() { + const product = productApi.useLoaderData() + const loaderData: Equal = true + const notAny: IsAny = false + const brand: Equal = true + + // Validated search output: \`tab\` has a default, so it is always set. + const search = productApi.useSearch() + const output: Equal = true + + // Context the module root requires from its host. + const context = AccountIndexRoute.useRouteContext() + const user: Equal = true + + return [loaderData, notAny, brand, output, user] +} + +export const links = ( + <> + {/* Navigation input: \`tab\` is optional. */} + + + {/* @ts-expect-error a required search input is missing */} + + + {/* Nested routing survives the boundary. */} + + + + + {/* @ts-expect-error pathless layout segments are not part of paths */} + + {/* @ts-expect-error unknown module-local path */} + + +) +`, + ) + await expectChecksPass('account') + }) + + test('declaration maps lead to the module sources from any output directory', async () => { + ws.edit('products', 'tsconfig.route-types.json', (source) => + source.replace('".tanstack/types"', '"route-types"'), + ) + ws.edit('products', 'package.json', (source) => + source.replaceAll('./.tanstack/types/', './route-types/'), + ) + await ws.buildGraph(order, modules) + await expectChecksPass('account') + + const map = 'route-types/src/routes/$productId.d.ts.map' + const { sources } = JSON.parse(ws.read('products', map)) + expect(sources).toHaveLength(1) + expect( + path.resolve(path.dirname(ws.file('products', map)), sources[0]), + ).toBe(ws.file('products', 'src/routes/$productId.tsx')) + }) +}) + +describe('composition', () => { + test('a missing provider fails the application generation', async () => { + await ws.buildGraph(modules, modules) + ws.edit('web', 'tsr.config.json', (source) => + source.replace( + '{ "module": "@route-modules/storefront", "at": "/shop" },', + '', + ), + ) + await expect(ws.generate('web')).rejects.toThrow( + /uses routes of "@route-modules\/products", which is not installed/, + ) + }) + + test('a host route without the required context fails the check', async () => { + await ws.buildGraph(modules, modules) + // Mount account at the root, which provides no `user`. + ws.edit('web', 'tsr.config.json', (source) => + source.replace('"parent": "/_authenticated",', ''), + ) + ws.remove('web', 'src/routes/_authenticated.tsx') + await ws.generate('web') + const result = await ws.check('web') + expect(result.ok).toBe(false) + expect( + errorsIn(result.diagnostics, 'src/routeTree.gen.ts').join('\n'), + ).toMatch(/requires router context 'user'/) + }) + + test('mounting a module twice is rejected', async () => { + await ws.buildGraph(modules, modules) + ws.edit('web', 'tsr.config.json', (source) => + source.replace( + '"includes": [', + '"includes": [\n { "module": "@route-modules/products", "at": "/p" },', + ), + ) + await expect(ws.generate('web')).rejects.toThrow(/installed twice/) + }) + + test('a mount path with path params is rejected', async () => { + await ws.buildGraph(modules, modules) + ws.edit('web', 'tsr.config.json', (source) => + source.replace('"at": "/shop"', '"at": "/$tenant"'), + ) + await expect(ws.generate('web')).rejects.toThrow(/static path/) + }) + + test('two applications compose the same modules independently', async () => { + ws.addPackage('admin', 'web') + ws.edit('admin', 'package.json', (source) => + source.replace('@route-modules/web', '@route-modules/admin'), + ) + ws.edit('admin', 'tsr.config.json', (source) => + source.replace('"at": "/shop"', '"at": "/store"'), + ) + await ws.buildGraph([...order, 'admin'], modules) + await expectChecksPass('web', 'admin') + + const productsDeclarations = Object.keys( + ws.snapshot('products', '.tanstack/types'), + ) + .map((file) => ws.read('products', `.tanstack/types/${file}`)) + .join('\n') + expect(productsDeclarations).not.toMatch(/@route-modules\/(web|admin)/) + expect(productsDeclarations).not.toMatch(/interface Register\b/) + }) +}) + +describe('mounting under path params', () => { + test('the application passes the path params above a module it mounts', async () => { + await ws.buildGraph(order, modules) + ws.edit('web', 'src/routes/index.tsx', (source) => + source.replace(" params={{ orgId: 'acme' }}", ''), + ) + + const web = await ws.check('web') + // `/` has no params of its own: the host params make them required. + expect( + errorsIn(web.diagnostics, 'src/routes/index.tsx').join('\n'), + ).toMatch(/'params' is missing.*@route-modules\/team/) + }) + + test('a module that links into a module under path params is mounted below them', async () => { + await ws.buildGraph(order, modules) + ws.edit('web', 'tsr.config.json', (source) => + source.replace( + `"module": "@route-modules/billing", + "parent": "/orgs/$orgId",`, + '"module": "@route-modules/billing",', + ), + ) + + await expect(ws.generate('web')).rejects.toThrow( + '"@route-modules/billing" links into "@route-modules/team", which is mounted below "/orgs/$orgId", but "@route-modules/billing" is mounted at "/billing"', + ) + }) +}) diff --git a/e2e/react-router/route-modules/tests/workspace.ts b/e2e/react-router/route-modules/tests/workspace.ts new file mode 100644 index 0000000000..32783d63f7 --- /dev/null +++ b/e2e/react-router/route-modules/tests/workspace.ts @@ -0,0 +1,287 @@ +import path from 'node:path' +import os from 'node:os' +import crypto from 'node:crypto' +import { spawnSync } from 'node:child_process' +import { + existsSync, + mkdirSync, + readFileSync, + readdirSync, + realpathSync, + rmSync, + statSync, + symlinkSync, + writeFileSync, +} from 'node:fs' +import { cpSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { + Generator, + getConfig, + readRouteModuleManifest, +} from '@tanstack/router-generator' +import type { RouteModuleManifest } from '@tanstack/router-generator' + +const here = path.dirname(fileURLToPath(import.meta.url)) +const fixtureRoot = path.resolve(here, '../packages') +const repoRoot = path.resolve(here, '../../../..') +/** The repository's TypeScript compiler (`tsc` of `@typescript/native`). */ +export const tsc = path.join(repoRoot, 'node_modules', '.bin', 'tsc') + +const workspaceScope = '@route-modules/' +const generatedFile = /\.gen(?:\.[^.]+)?\.tsx?$/ + +export type Operation = 'generate' | 'emit-types' | 'check' | 'build' + +export interface LoggedOperation { + operation: Operation + pkg: string + ok: boolean +} + +function listDependencies(nodeModules: string): Array { + if (!existsSync(nodeModules)) { + return [] + } + const entries: Array = [] + for (const entry of readdirSync(nodeModules)) { + if (entry.startsWith('.')) { + continue + } + if (entry.startsWith('@')) { + for (const scoped of readdirSync(path.join(nodeModules, entry))) { + entries.push(`${entry}/${scoped}`) + } + } else { + entries.push(entry) + } + } + return entries +} + +/** + * A copy of the fixture packages in a temporary directory. Workspace route + * modules are linked to their copies; every other dependency is linked to the + * package the repository installed, so the copy resolves like the original. + * Nothing generated or built is copied: every test starts from a clean + * checkout. + */ +export class Workspace { + readonly root: string + readonly log: Array = [] + + constructor( + packages: Array = [ + 'products', + 'storefront', + 'account', + 'team', + 'settings', + 'billing', + 'web', + ], + ) { + this.root = realpathSync( + require_mkdtemp(path.join(os.tmpdir(), 'tsr-route-modules-')), + ) + for (const name of packages) { + this.addPackage(name, name) + } + } + + /** Copies fixture package `source` as `name` into the workspace. */ + addPackage(name: string, source: string) { + const from = path.join(fixtureRoot, source) + const to = this.pkg(name) + cpSync(from, to, { + recursive: true, + filter: (file) => + !file.includes(`${path.sep}node_modules`) && + !file.includes(`${path.sep}.tanstack`) && + !file.includes(`${path.sep}dist`) && + !generatedFile.test(file), + }) + for (const dependency of listDependencies( + path.join(from, 'node_modules'), + )) { + const link = path.join(to, 'node_modules', dependency) + mkdirSync(path.dirname(link), { recursive: true }) + const target = dependency.startsWith(workspaceScope) + ? this.pkg(dependency.slice(workspaceScope.length)) + : realpathSync(path.join(from, 'node_modules', dependency)) + symlinkSync(target, link, 'dir') + } + } + + pkg(name: string) { + return path.join(this.root, name) + } + + file(name: string, file: string) { + return path.join(this.pkg(name), file) + } + + read(name: string, file: string) { + return readFileSync(this.file(name, file), 'utf8') + } + + write(name: string, file: string, content: string) { + mkdirSync(path.dirname(this.file(name, file)), { recursive: true }) + writeFileSync(this.file(name, file), content) + } + + edit(name: string, file: string, edit: (content: string) => string) { + const before = this.read(name, file) + const after = edit(before) + if (after === before) { + throw new Error(`The edit of ${name}/${file} changed nothing`) + } + this.write(name, file, after) + } + + remove(name: string, file: string) { + rmSync(this.file(name, file), { recursive: true, force: true }) + } + + exists(name: string, file: string) { + return existsSync(this.file(name, file)) + } + + /** Pass A: route generation of one package. */ + async generate(name: string) { + const packageRoot = this.pkg(name) + const config = getConfig( + { disableLogging: true, tmpDir: path.join(this.root, '.tmp') }, + packageRoot, + ) + try { + await new Generator({ config, root: packageRoot }).run() + this.log.push({ operation: 'generate', pkg: name, ok: true }) + } catch (error) { + this.log.push({ operation: 'generate', pkg: name, ok: false }) + throw error + } + } + + /** The fixture package's ordinary clean TypeScript declaration build. */ + async emitTypes(name: string) { + const project = JSON.parse(this.read(name, 'tsconfig.route-types.json')) + this.remove( + name, + project.compilerOptions.declarationDir ?? project.compilerOptions.outDir, + ) + const result = this.compile(name, ['-p', 'tsconfig.route-types.json']) + this.log.push({ operation: 'emit-types', pkg: name, ok: result.ok }) + return result + } + + /** Source check of one package against current module declarations. */ + async check(name: string) { + const result = this.compile(name, ['-p', 'tsconfig.json', '--noEmit']) + this.log.push({ operation: 'check', pkg: name, ok: result.ok }) + return result + } + + /** Generates, emits and checks every package in dependency order. */ + async buildGraph(order: Array, modules: Array) { + for (const name of order) { + await this.generate(name) + if (modules.includes(name)) { + const emitted = await this.emitTypes(name) + if (!emitted.ok) { + throw new Error(emitted.diagnostics.join('\n')) + } + } + } + } + + manifest(name: string): RouteModuleManifest { + return readRouteModuleManifest(this.pkg(name))! + } + + private compile(name: string, args: Array) { + const result = spawnSync(tsc, [...args, '--pretty', 'false'], { + cwd: this.pkg(name), + encoding: 'utf8', + }) + return { + ok: result.status === 0, + diagnostics: result.error + ? [result.error.message] + : `${result.stdout ?? ''}${result.stderr ?? ''}` + .split(/\r?\n/) + .filter((line) => line.trim() !== ''), + } + } + + /** Content hash and modification time of every file below `dir`. */ + snapshot(name: string, dir: string): Record { + const base = this.file(name, dir) + const result: Record = {} + const walk = (current: string) => { + for (const entry of readdirSync(current)) { + const full = path.join(current, entry) + const stat = statSync(full) + if (stat.isDirectory()) { + walk(full) + } else { + result[path.relative(base, full)] = `${crypto + .createHash('sha256') + .update(readFileSync(full)) + .digest('hex') + .slice(0, 12)}@${stat.mtimeMs}` + } + } + } + if (existsSync(base)) { + walk(base) + } + return result + } + + /** The files a package's type check loads (`tsc --listFilesOnly`). */ + listProgramFiles(name: string): Array { + const result = spawnSync(tsc, ['-p', 'tsconfig.json', '--listFilesOnly'], { + cwd: this.pkg(name), + encoding: 'utf8', + }) + return result.stdout.split(/\r?\n/).filter(Boolean) + } + + dispose() { + rmSync(this.root, { recursive: true, force: true }) + } +} + +function require_mkdtemp(prefix: string) { + // `fs.mkdtempSync` without importing the whole promises API. + const dir = `${prefix}${crypto.randomBytes(4).toString('hex')}` + mkdirSync(dir, { recursive: true }) + return dir +} + +/** + * The diagnostics of a failed check that point into `file`, each with its + * indented continuation lines (where elaborated messages appear). + */ +export function errorsIn(diagnostics: Array, file: string) { + const errors: Array = [] + let current: string | undefined + for (const line of diagnostics) { + if (/^\s/.test(line)) { + if (current !== undefined) { + current += `\n${line}` + } + continue + } + if (current !== undefined) { + errors.push(current) + } + current = + line.startsWith(file) || line.includes(`/${file}(`) ? line : undefined + } + if (current !== undefined) { + errors.push(current) + } + return errors +} diff --git a/e2e/react-router/route-modules/tsconfig.json b/e2e/react-router/route-modules/tsconfig.json new file mode 100644 index 0000000000..341902faed --- /dev/null +++ b/e2e/react-router/route-modules/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "strict": true, + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "skipLibCheck": true, + "noEmit": true, + "types": ["node"] + }, + "include": [ + "tests", + "e2e", + "e2e-dev", + "scripts", + "vitest.config.ts", + "playwright.config.ts", + "playwright.dev.config.ts" + ] +} diff --git a/e2e/react-router/route-modules/vitest.config.ts b/e2e/react-router/route-modules/vitest.config.ts new file mode 100644 index 0000000000..b8e3ec784a --- /dev/null +++ b/e2e/react-router/route-modules/vitest.config.ts @@ -0,0 +1,11 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + include: ['tests/**/*.test.ts', 'packages/web/tests/**/*.test.tsx'], + // Each test runs the generator and the TypeScript compiler on a workspace. + testTimeout: 120_000, + hookTimeout: 120_000, + fileParallelism: false, + }, +}) diff --git a/e2e/react-start/route-modules/.gitignore b/e2e/react-start/route-modules/.gitignore new file mode 100644 index 0000000000..92efdd2694 --- /dev/null +++ b/e2e/react-start/route-modules/.gitignore @@ -0,0 +1,9 @@ +# Generated by the route generator and TypeScript; the tests generate +# them from a clean copy of the packages. +**/routeTree.gen.ts +**/routeScope.gen.ts +**/routeContract.gen.ts +**/routeModule.gen.ts +**/startModules.gen.ts +**/routeScope.gen.*.ts +**/routeTree.gen.*.ts diff --git a/e2e/react-start/route-modules/e2e-dev/devtools.spec.ts b/e2e/react-start/route-modules/e2e-dev/devtools.spec.ts new file mode 100644 index 0000000000..59ebbb9ecd --- /dev/null +++ b/e2e/react-start/route-modules/e2e-dev/devtools.spec.ts @@ -0,0 +1,50 @@ +import { expect, test } from '@playwright/test' + +test('the router devtools group the routes of mounted modules', async ({ + page, +}) => { + await page.goto('/shop/lamp') + await page.getByTestId('hydrated').waitFor() + await page + .getByRole('button', { name: 'Open TanStack Router Devtools' }) + .click() + + await expect( + page.getByRole('group', { + name: 'Route module @start-route-modules/catalog', + }), + ).toBeVisible() + await expect( + page.getByRole('group', { + name: 'Route module @start-route-modules/notes', + }), + ).toBeVisible() + + await page + .getByRole('button', { + name: 'Open module details for @start-route-modules/catalog', + }) + .first() + .click() + const details = page.getByRole('region', { name: 'Module details' }) + await expect(details).toContainText('Mount path:/shop') + await expect(details).toContainText('Parent module:Application') +}) + +test('the router devtools show each installation of a module installed twice', async ({ + page, +}) => { + await page.goto('/people/ada/settings') + await page.getByTestId('hydrated').waitFor() + await page + .getByRole('button', { name: 'Open TanStack Router Devtools' }) + .click() + + for (const installation of ['orgSettings', 'personSettings']) { + await expect( + page.getByRole('group', { + name: `Route module @start-route-modules/settings#${installation}`, + }), + ).toBeVisible() + } +}) diff --git a/e2e/react-start/route-modules/e2e-dev/hmr.spec.ts b/e2e/react-start/route-modules/e2e-dev/hmr.spec.ts new file mode 100644 index 0000000000..0d4df29277 --- /dev/null +++ b/e2e/react-start/route-modules/e2e-dev/hmr.spec.ts @@ -0,0 +1,169 @@ +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { expect } from '@playwright/test' +import { createHmrFileEditor, test } from '@tanstack/router-e2e-utils' +import { Generator, getConfig } from '@tanstack/router-generator' +import type { Page } from '@playwright/test' + +const catalog = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../packages/catalog', +) + +const editor = createHmrFileEditor({ + rootDir: catalog, + files: { + product: 'src/routes/$productId.tsx', + api: 'src/api.ts', + index: 'src/routes/index.tsx', + }, +}) +const settingsEditor = createHmrFileEditor({ + rootDir: path.resolve(catalog, '../settings'), + files: { + profile: 'src/routes/profile.tsx', + }, +}) + +test.afterEach(async () => { + await editor.restoreFiles() + await settingsEditor.restoreFiles() +}) + +// The server-rendered page shows the product before the browser has loaded +// the route module. Edit only after hydration: an edit before it is served to +// the hydrating browser, which then mismatches the server's HTML instead of +// receiving a hot update. +async function gotoHydrated(page: Page, url: string) { + await page.goto(url) + await page.getByTestId('hydrated').waitFor() +} + +test('editing a module route file hot-updates it in the application', async ({ + page, +}) => { + await gotoHydrated(page, '/shop/lamp') + await expect(page.getByRole('heading', { name: 'Desk lamp' })).toBeVisible() + await page.evaluate(() => { + ;(window as any).__beforeHmr = true + }) + + await editor.replaceText( + 'product', + '

{product.name}

', + '

Updated {product.name}

', + ) + await expect( + page.getByRole('heading', { name: 'Updated Desk lamp' }), + ).toBeVisible() + // A hot update, not a reload: page state survives. + expect(await page.evaluate(() => (window as any).__beforeHmr)).toBe(true) + + // Restore while the page is open. Server rendering reads the file again, + // but the browser gets the client's compiled module until Vite processes + // the change; the hot update shows it has, so the next page load hydrates. + await editor.restoreFiles() + await expect( + page.getByRole('heading', { name: 'Desk lamp', exact: true }), + ).toBeVisible() +}) + +test('a module server function runs its edited implementation', async ({ + page, +}) => { + await gotoHydrated(page, '/shop/lamp') + await expect(page.getByRole('heading', { name: 'Desk lamp' })).toBeVisible() + + await editor.replaceText('api', "name: 'Desk lamp'", "name: 'Reading lamp'") + await expect(async () => { + await page.getByRole('button', { name: 'Refresh' }).click() + await expect( + page.getByRole('heading', { name: 'Reading lamp' }), + ).toBeVisible({ timeout: 1000 }) + }).toPass() + await expect(page.getByTestId('price')).toHaveText('49.00 EUR') +}) + +test('editing a route of a module installed twice hot-updates every installation', async ({ + page, +}) => { + await gotoHydrated(page, '/people/ada/settings/profile') + await expect(page.getByRole('heading', { name: 'Profile' })).toBeVisible() + await page.evaluate(() => { + ;(window as any).__beforeHmr = true + }) + + await settingsEditor.replaceText( + 'profile', + '

Profile

', + '

Updated profile

', + ) + await expect( + page.getByRole('heading', { name: 'Updated profile' }), + ).toBeVisible() + + // The installation of the organizations runs the updated route too. + await page.evaluate(() => + (window as any).__TSR_ROUTER__.navigate({ + to: '/orgs/acme/settings/profile', + }), + ) + await expect(page.getByTestId('profile-kind')).toHaveText('organization') + await expect( + page.getByRole('heading', { name: 'Updated profile' }), + ).toBeVisible() + // Hot updates, not reloads: page state survives. + expect(await page.evaluate(() => (window as any).__beforeHmr)).toBe(true) +}) + +test('provider classification changes refresh the client tree and preserve server endpoints', async ({ + page, + request, +}) => { + await editor.capturePromise + const providerGenerator = new Generator({ + root: catalog, + config: getConfig({ disableLogging: true }, catalog), + }) + const hasCatalogPage = () => + page.evaluate(() => { + const router = (window as any).__TSR_ROUTER__ + return router + ? Object.hasOwn(router.routesById, '@start-route-modules/catalog:/') + : undefined + }) + const expectCatalogPage = (present: boolean) => + expect(async () => { + // Topology publication may reload the document; retry through navigation + // and require an initialized router before checking its route inventory. + expect(await hasCatalogPage()).toBe(present) + }).toPass() + await gotoHydrated(page, '/') + await expectCatalogPage(true) + try { + await editor.rewriteFile( + 'index', + () => `import { createFileRoute } from '../routeScope.gen' +export const Route = createFileRoute('@start-route-modules/catalog:/')({ + server: { handlers: { GET: () => new Response('catalog endpoint') } }, +}) +`, + ) + await providerGenerator.run() + await expectCatalogPage(false) + await expect(async () => { + const response = await request.get('/shop') + expect(response.status()).toBe(200) + expect(await response.text()).toBe('catalog endpoint') + }).toPass() + + await editor.restoreFiles() + await providerGenerator.run() + await expectCatalogPage(true) + await gotoHydrated(page, '/shop') + await expect(page.getByTestId('price-chair')).toHaveText('129.00 EUR') + } finally { + await editor.restoreFiles() + await providerGenerator.run() + } +}) diff --git a/e2e/react-start/route-modules/e2e/app.spec.ts b/e2e/react-start/route-modules/e2e/app.spec.ts new file mode 100644 index 0000000000..4309a6d1ea --- /dev/null +++ b/e2e/react-start/route-modules/e2e/app.spec.ts @@ -0,0 +1,160 @@ +import { expect, test } from '@playwright/test' + +test('the server renders module routes with the context the application provides', async ({ + request, +}) => { + const html = await (await request.get('/shop/lamp')).text() + expect(html).toContain('Desk lamp') + // `shopper` comes from the application's request middleware, the currency + // from the catalog's own pricing middleware. + expect(html).toContain('49.00 EUR') + expect(html).toContain('Shopper: ada') +}) + +test('module data hydrates through the module serialization adapter', async ({ + page, +}) => { + await page.goto('/shop/lamp') + await expect(page.getByTestId('price')).toHaveText('49.00 EUR') + const renderedAt = await page.getByTestId('rendered-at').textContent() + + // The route's loader runs again on the client and calls the module's + // server function; its result goes through the serialization adapter. + await page.getByRole('button', { name: 'Refresh' }).click() + await expect(page.getByTestId('rendered-at')).not.toHaveText(renderedAt!) + await expect(page.getByTestId('price')).toHaveText('49.00 EUR') + await expect(page.getByTestId('shopper')).toHaveText('Shopper: ada') +}) + +test('client navigation loads module routes through their server functions', async ({ + page, +}) => { + await page.goto('/') + await expect(page.getByRole('heading', { name: 'Home' })).toBeVisible() + await page.getByRole('link', { name: 'Catalog' }).click() + await expect(page).toHaveURL('/shop') + await expect(page.getByTestId('price-chair')).toHaveText('129.00 EUR') + + await page.getByRole('link', { name: 'Office chair' }).click() + await expect(page).toHaveURL('/shop/chair') + await expect( + page.getByRole('heading', { name: 'Office chair' }), + ).toBeVisible() + + await page.getByRole('link', { name: 'All products' }).click() + await expect(page).toHaveURL('/shop') +}) + +test('a router-only module renders in the Start application', async ({ + page, +}) => { + await page.goto('/') + await page.getByRole('link', { name: 'Notes' }).click() + await expect(page).toHaveURL('/notes') + await expect(page.getByTestId('notes')).toContainText('Compose route modules') +}) + +test('module routes are code-split from the application bundle', async ({ + page, +}) => { + // Chunk names differ between toolchains: find the product page's code by + // its text in the scripts the browser loads. + const scripts: Array> = [] + page.on('response', (response) => { + if (response.request().resourceType() === 'script') { + scripts.push(response.text()) + } + }) + const loadsProductPage = async () => + (await Promise.all(scripts)).some((script) => + script.includes('Rendered at'), + ) + await page.goto('/') + await expect(page.getByRole('heading', { name: 'Home' })).toBeVisible() + expect(await loadsProductPage()).toBe(false) + + await page.getByRole('link', { name: 'Lamp' }).click() + await expect(page.getByRole('heading', { name: 'Desk lamp' })).toBeVisible() + await expect.poll(loadsProductPage).toBe(true) +}) + +test('the server renders a module mounted under path params', async ({ + request, +}) => { + const html = await (await request.get('/orgs/acme/team')).text() + expect(html).toContain('Team of ACME') + // The module's server function loads the members of the organization in the URL. + expect(html).toContain('grace (acme)') +}) + +test('links into and inside a module mounted under path params', async ({ + page, +}) => { + await page.goto('/') + await page.getByTestId('hydrated').waitFor() + // The application passes the path params above the module. + await page.getByRole('link', { name: 'Acme team' }).click() + await expect(page).toHaveURL('/orgs/acme/team') + await expect( + page.getByRole('heading', { name: 'Team of ACME' }), + ).toBeVisible() + + // Module-local links keep the path params of the current location. + await page.getByRole('link', { name: 'grace (acme)' }).click() + await expect(page).toHaveURL('/orgs/acme/team/members/grace') + await expect( + page.getByRole('heading', { name: 'grace at ACME' }), + ).toBeVisible() + await page.getByRole('link', { name: 'All members' }).click() + await expect(page).toHaveURL('/orgs/acme/team') +}) + +test('the server renders each installation of a module installed twice', async ({ + request, +}) => { + const person = await ( + await request.get('/people/ada/settings/profile') + ).text() + expect(person).toContain('Settings of Ada') + expect(person).toContain('@ada') + const organization = await ( + await request.get('/orgs/acme/settings/profile') + ).text() + expect(organization).toContain('Settings of ACME') + expect(organization).toContain('@acme') +}) + +test('links of a module installed twice stay in their installation', async ({ + page, +}) => { + await page.goto('/') + await page.getByTestId('hydrated').waitFor() + await page.getByRole('link', { name: 'Globex settings' }).click() + await expect(page).toHaveURL('/orgs/globex/settings') + await expect( + page.getByRole('heading', { name: 'Settings of GLOBEX' }), + ).toBeVisible() + // The profile loads through the module's server function. + await page.getByRole('link', { name: 'Profile' }).click() + await expect(page).toHaveURL('/orgs/globex/settings/profile') + await expect(page.getByTestId('profile-kind')).toHaveText('organization') + + await page.goto('/') + await page.getByTestId('hydrated').waitFor() + await page.getByRole('link', { name: "Ada's profile" }).click() + await expect(page).toHaveURL('/people/ada/settings/profile') + await expect(page.getByTestId('profile-kind')).toHaveText('person') + await page.getByRole('link', { name: 'All settings' }).click() + await expect(page).toHaveURL('/people/ada/settings') +}) + +test('a module that uses a module installed twice links to the installation above it', async ({ + page, +}) => { + await page.goto('/orgs/acme/team') + await page.getByTestId('hydrated').waitFor() + const profile = page.getByRole('link', { name: 'Organization profile' }) + await expect(profile).toHaveAttribute('href', '/orgs/acme/settings/profile') + await profile.click() + await expect(page.getByTestId('profile-kind')).toHaveText('organization') +}) diff --git a/e2e/react-start/route-modules/package.json b/e2e/react-start/route-modules/package.json new file mode 100644 index 0000000000..ce088f7363 --- /dev/null +++ b/e2e/react-start/route-modules/package.json @@ -0,0 +1,54 @@ +{ + "name": "tanstack-react-start-e2e-route-modules", + "private": true, + "type": "module", + "scripts": { + "test:e2e": "vitest run && pnpm test:e2e:dev", + "test:e2e:dev": "pnpm test:e2e:dev:vite && pnpm test:e2e:dev:rsbuild", + "test:e2e:dev:vite": "E2E_TOOLCHAIN=vite playwright test --config playwright.dev.config.ts --project=chromium", + "test:e2e:dev:rsbuild": "E2E_TOOLCHAIN=rsbuild playwright test --config playwright.dev.config.ts --project=chromium" + }, + "devDependencies": { + "@playwright/test": "^1.61.0", + "@start-route-modules/web": "workspace:*", + "@tanstack/router-e2e-utils": "workspace:^", + "@tanstack/router-generator": "workspace:^", + "@types/node": "catalog:", + "vitest": "catalog:" + }, + "nx": { + "targets": { + "test:e2e": { + "parallelism": false + }, + "build:vite:ssr": { + "options": { + "command": "node scripts/prepare.mjs && pnpm --filter @start-route-modules/web build:vite" + }, + "outputs": [ + "{projectRoot}/packages/web/dist-vite-ssr" + ] + }, + "build:rsbuild:ssr": { + "options": { + "command": "node scripts/prepare.mjs && pnpm --filter @start-route-modules/web build:rsbuild" + }, + "outputs": [ + "{projectRoot}/packages/web/dist-rsbuild-ssr" + ] + } + }, + "metadata": { + "playwrightModes": [ + { + "toolchain": "vite", + "mode": "ssr" + }, + { + "toolchain": "rsbuild", + "mode": "ssr" + } + ] + } + } +} diff --git a/e2e/react-start/route-modules/packages/catalog/package.json b/e2e/react-start/route-modules/packages/catalog/package.json new file mode 100644 index 0000000000..7f0729e3ce --- /dev/null +++ b/e2e/react-start/route-modules/packages/catalog/package.json @@ -0,0 +1,36 @@ +{ + "name": "@start-route-modules/catalog", + "private": true, + "type": "module", + "tanstack": { + "router": { + "module": true + } + }, + "exports": { + "./route-types": { + "types": "./.tanstack/types/src/routeContract.gen.d.ts" + }, + "./route-module": { + "types": "./.tanstack/types/src/routeModule.gen.d.ts", + "default": "./src/routeModule.gen.ts" + }, + "./package.json": "./package.json" + }, + "scripts": { + "generate": "tsr generate", + "emit-types": "node -e \"require('node:fs').rmSync('.tanstack/types',{recursive:true,force:true})\" && tsc -p tsconfig.route-types.json", + "check": "tsc --noEmit" + }, + "dependencies": { + "@tanstack/react-router": "workspace:^", + "@tanstack/react-start": "workspace:^", + "react": "^19.0.0" + }, + "devDependencies": { + "@tanstack/router-cli": "workspace:^", + "@tanstack/router-core": "workspace:^", + "@tanstack/start-client-core": "workspace:^", + "@types/react": "^19.0.8" + } +} diff --git a/e2e/react-start/route-modules/packages/catalog/src/api.ts b/e2e/react-start/route-modules/packages/catalog/src/api.ts new file mode 100644 index 0000000000..263b078d00 --- /dev/null +++ b/e2e/react-start/route-modules/packages/catalog/src/api.ts @@ -0,0 +1,41 @@ +import { notFound } from '@tanstack/react-router' +import { createServerFn, createMiddleware } from './routeScope.gen' +import { Money } from './money' + +// Module-local: only the catalog's server functions run it. +const pricing = createMiddleware({ type: 'function' }).server( + ({ context, next }) => + next({ context: { currency: context.shopper === 'ada' ? 'EUR' : 'USD' } }), +) + +const products = [ + { id: 'lamp', name: 'Desk lamp', cents: 4900 }, + { id: 'chair', name: 'Office chair', cents: 12900 }, +] + +export const listProducts = createServerFn() + .middleware([pricing]) + .handler(({ context }) => + products.map((product) => ({ + id: product.id, + name: product.name, + price: new Money(product.cents, context.currency), + })), + ) + +export const getProduct = createServerFn() + .middleware([pricing]) + .validator((id: string) => id) + .handler(({ data, context }) => { + const product = products.find((candidate) => candidate.id === data) + if (!product) { + throw notFound() + } + return { + id: product.id, + name: product.name, + price: new Money(product.cents, context.currency), + shopper: context.shopper, + renderedAt: Date.now(), + } + }) diff --git a/e2e/react-start/route-modules/packages/catalog/src/money.ts b/e2e/react-start/route-modules/packages/catalog/src/money.ts new file mode 100644 index 0000000000..fbd146447c --- /dev/null +++ b/e2e/react-start/route-modules/packages/catalog/src/money.ts @@ -0,0 +1,20 @@ +import { createSerializationAdapter } from '@tanstack/react-router' + +/** An amount of money. Server functions and loaders return it as is. */ +export class Money { + constructor( + readonly cents: number, + readonly currency: string, + ) {} + + format() { + return `${(this.cents / 100).toFixed(2)} ${this.currency}` + } +} + +export const moneyAdapter = createSerializationAdapter({ + key: 'catalog-money', + test: (value): value is Money => value instanceof Money, + toSerializable: (money) => ({ cents: money.cents, currency: money.currency }), + fromSerializable: (value) => new Money(value.cents, value.currency), +}) diff --git a/e2e/react-start/route-modules/packages/catalog/src/requirements.ts b/e2e/react-start/route-modules/packages/catalog/src/requirements.ts new file mode 100644 index 0000000000..1c91f7bdf0 --- /dev/null +++ b/e2e/react-start/route-modules/packages/catalog/src/requirements.ts @@ -0,0 +1,7 @@ +export type { StartModuleRequirements } from '@tanstack/react-start' + +declare module '@tanstack/react-start' { + interface StartModuleRequirements { + '@start-route-modules/catalog': { requestContext: { shopper: string } } + } +} diff --git a/e2e/react-start/route-modules/packages/catalog/src/routes/$productId.tsx b/e2e/react-start/route-modules/packages/catalog/src/routes/$productId.tsx new file mode 100644 index 0000000000..34ff20347c --- /dev/null +++ b/e2e/react-start/route-modules/packages/catalog/src/routes/$productId.tsx @@ -0,0 +1,62 @@ +import { useRef } from 'react' +import { createFileRoute, useRouter } from '../routeScope.gen' +import { getProduct } from '../api' + +export const Route = createFileRoute( + '@start-route-modules/catalog:/$productId', +)({ + loader: ({ params }) => getProduct({ data: params.productId }), + component: ProductPage, +}) + +function ProductPage() { + const product = Route.useLoaderData() + const router = useRouter() + const refreshing = Route.useMatch({ + select: (match) => match.isFetching !== false, + }) + // A render after the first one came from a refresh. + const firstRenderedAt = useRef(product.renderedAt).current + return ( +
+

{product.name}

+

+ {product.price.format()} +

+
+

Shopper: {product.shopper}

+

+ Rendered at{' '} + {/* Highlighted once each time a refresh brings a new render. */} + {' '} + UTC +

+
+
+ + All products +
+
+ ) +} diff --git a/e2e/react-start/route-modules/packages/catalog/src/routes/__root.tsx b/e2e/react-start/route-modules/packages/catalog/src/routes/__root.tsx new file mode 100644 index 0000000000..e245ab4549 --- /dev/null +++ b/e2e/react-start/route-modules/packages/catalog/src/routes/__root.tsx @@ -0,0 +1,21 @@ +export type {} from '../requirements' +import { Outlet } from '@tanstack/react-router' +import { createModuleRoot } from '../routeScope.gen' + +export const Route = createModuleRoot()({ + component: CatalogRoom, +}) + +// The module's region: a room tagged with its package and where it is +// mounted. +function CatalogRoom() { + return ( +
+

+ @start-route-modules/catalog {Route.fullPath} +

+

Catalog

+ +
+ ) +} diff --git a/e2e/react-start/route-modules/packages/catalog/src/routes/index.tsx b/e2e/react-start/route-modules/packages/catalog/src/routes/index.tsx new file mode 100644 index 0000000000..4b399ce36c --- /dev/null +++ b/e2e/react-start/route-modules/packages/catalog/src/routes/index.tsx @@ -0,0 +1,25 @@ +import { createFileRoute } from '../routeScope.gen' +import { listProducts } from '../api' + +export const Route = createFileRoute('@start-route-modules/catalog:/')({ + loader: () => listProducts(), + component: CatalogPage, +}) + +function CatalogPage() { + const products = Route.useLoaderData() + return ( +
    + {products.map((product) => ( +
  • + + {product.name} + + + {product.price.format()} + +
  • + ))} +
+ ) +} diff --git a/e2e/react-start/route-modules/packages/catalog/src/start.ts b/e2e/react-start/route-modules/packages/catalog/src/start.ts new file mode 100644 index 0000000000..010339ba76 --- /dev/null +++ b/e2e/react-start/route-modules/packages/catalog/src/start.ts @@ -0,0 +1,8 @@ +export type {} from './requirements' +import { createStartModule } from './routeScope.gen' +import { moneyAdapter } from './money' + +export const start = createStartModule(() => ({ + // Contributed: `Money` values cross the network in every application route. + serializationAdapters: [moneyAdapter], +})) diff --git a/e2e/react-start/route-modules/packages/catalog/tsconfig.json b/e2e/react-start/route-modules/packages/catalog/tsconfig.json new file mode 100644 index 0000000000..1de72ddc24 --- /dev/null +++ b/e2e/react-start/route-modules/packages/catalog/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "skipLibCheck": true, + "noEmit": true, + "types": [] + }, + "include": ["src"] +} diff --git a/e2e/react-start/route-modules/packages/catalog/tsconfig.route-types.json b/e2e/react-start/route-modules/packages/catalog/tsconfig.route-types.json new file mode 100644 index 0000000000..0c9aec3caf --- /dev/null +++ b/e2e/react-start/route-modules/packages/catalog/tsconfig.route-types.json @@ -0,0 +1,13 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "emitDeclarationOnly": true, + "noEmitOnError": true, + "declarationMap": true, + "rootDir": ".", + "outDir": ".tanstack/types" + }, + "include": ["src"] +} diff --git a/e2e/react-start/route-modules/packages/notes/package.json b/e2e/react-start/route-modules/packages/notes/package.json new file mode 100644 index 0000000000..87d6fe06d5 --- /dev/null +++ b/e2e/react-start/route-modules/packages/notes/package.json @@ -0,0 +1,34 @@ +{ + "name": "@start-route-modules/notes", + "private": true, + "type": "module", + "tanstack": { + "router": { + "module": true + } + }, + "exports": { + "./route-types": { + "types": "./.tanstack/types/src/routeContract.gen.d.ts" + }, + "./route-module": { + "types": "./.tanstack/types/src/routeModule.gen.d.ts", + "default": "./src/routeModule.gen.ts" + }, + "./package.json": "./package.json" + }, + "scripts": { + "generate": "tsr generate", + "emit-types": "node -e \"require('node:fs').rmSync('.tanstack/types',{recursive:true,force:true})\" && tsc -p tsconfig.route-types.json", + "check": "tsc --noEmit" + }, + "dependencies": { + "@tanstack/react-router": "workspace:^", + "react": "^19.0.0" + }, + "devDependencies": { + "@tanstack/router-cli": "workspace:^", + "@tanstack/router-core": "workspace:^", + "@types/react": "^19.0.8" + } +} diff --git a/e2e/react-start/route-modules/packages/notes/src/routes/__root.tsx b/e2e/react-start/route-modules/packages/notes/src/routes/__root.tsx new file mode 100644 index 0000000000..b2bf618003 --- /dev/null +++ b/e2e/react-start/route-modules/packages/notes/src/routes/__root.tsx @@ -0,0 +1,18 @@ +import { Outlet } from '@tanstack/react-router' +import { createModuleRoot } from '../routeScope.gen' + +export const Route = createModuleRoot()({ component: NotesRoom }) + +// The module's region: a room tagged with its package and where it is +// mounted. +function NotesRoom() { + return ( +
+

+ @start-route-modules/notes {Route.fullPath} +

+

Notes

+ +
+ ) +} diff --git a/e2e/react-start/route-modules/packages/notes/src/routes/index.tsx b/e2e/react-start/route-modules/packages/notes/src/routes/index.tsx new file mode 100644 index 0000000000..085fd35834 --- /dev/null +++ b/e2e/react-start/route-modules/packages/notes/src/routes/index.tsx @@ -0,0 +1,18 @@ +import { createFileRoute } from '../routeScope.gen' + +// A router-only module: the application that mounts it serializes this result. +export const Route = createFileRoute('@start-route-modules/notes:/')({ + loader: () => ({ notes: ['Compose route modules', 'Ship it'] }), + component: NotesPage, +}) + +function NotesPage() { + const { notes } = Route.useLoaderData() + return ( +
    + {notes.map((note) => ( +
  • {note}
  • + ))} +
+ ) +} diff --git a/e2e/react-start/route-modules/packages/notes/tsconfig.json b/e2e/react-start/route-modules/packages/notes/tsconfig.json new file mode 100644 index 0000000000..1de72ddc24 --- /dev/null +++ b/e2e/react-start/route-modules/packages/notes/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "skipLibCheck": true, + "noEmit": true, + "types": [] + }, + "include": ["src"] +} diff --git a/e2e/react-start/route-modules/packages/notes/tsconfig.route-types.json b/e2e/react-start/route-modules/packages/notes/tsconfig.route-types.json new file mode 100644 index 0000000000..0c9aec3caf --- /dev/null +++ b/e2e/react-start/route-modules/packages/notes/tsconfig.route-types.json @@ -0,0 +1,13 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "emitDeclarationOnly": true, + "noEmitOnError": true, + "declarationMap": true, + "rootDir": ".", + "outDir": ".tanstack/types" + }, + "include": ["src"] +} diff --git a/e2e/react-start/route-modules/packages/settings/package.json b/e2e/react-start/route-modules/packages/settings/package.json new file mode 100644 index 0000000000..58223e6483 --- /dev/null +++ b/e2e/react-start/route-modules/packages/settings/package.json @@ -0,0 +1,36 @@ +{ + "name": "@start-route-modules/settings", + "private": true, + "type": "module", + "tanstack": { + "router": { + "module": true + } + }, + "exports": { + "./route-types": { + "types": "./.tanstack/types/src/routeContract.gen.d.ts" + }, + "./route-module": { + "types": "./.tanstack/types/src/routeModule.gen.d.ts", + "default": "./src/routeModule.gen.ts" + }, + "./package.json": "./package.json" + }, + "scripts": { + "generate": "tsr generate", + "emit-types": "node -e \"require('node:fs').rmSync('.tanstack/types',{recursive:true,force:true})\" && tsc -p tsconfig.route-types.json", + "check": "tsc --noEmit" + }, + "dependencies": { + "@tanstack/react-router": "workspace:^", + "@tanstack/react-start": "workspace:^", + "react": "^19.0.0" + }, + "devDependencies": { + "@tanstack/router-cli": "workspace:^", + "@tanstack/router-core": "workspace:^", + "@tanstack/start-client-core": "workspace:^", + "@types/react": "^19.0.8" + } +} diff --git a/e2e/react-start/route-modules/packages/settings/src/api.ts b/e2e/react-start/route-modules/packages/settings/src/api.ts new file mode 100644 index 0000000000..2699f06ded --- /dev/null +++ b/e2e/react-start/route-modules/packages/settings/src/api.ts @@ -0,0 +1,6 @@ +import { createServerFn } from './routeScope.gen' + +/** The profile of an owner, loaded on the server. */ +export const getProfile = createServerFn() + .validator((owner: { kind: string; id: string }) => owner) + .handler(({ data }) => ({ kind: data.kind, handle: `@${data.id}` })) diff --git a/e2e/react-start/route-modules/packages/settings/src/routes/__root.tsx b/e2e/react-start/route-modules/packages/settings/src/routes/__root.tsx new file mode 100644 index 0000000000..db49802df7 --- /dev/null +++ b/e2e/react-start/route-modules/packages/settings/src/routes/__root.tsx @@ -0,0 +1,38 @@ +import { Outlet } from '@tanstack/react-router' +import { createModuleRoot } from '../routeScope.gen' + +/** Whose settings an installation shows, provided by its host route. */ +export interface Owner { + kind: 'organization' | 'person' + id: string + name: string +} + +// The store installs the settings twice: below `/orgs/$orgId` and below +// `/people/$personId`. Each host route provides its owner. +export const Route = createModuleRoot<{ owner: Owner }>()({ + component: SettingsRoom, +}) + +// The module's region: a room tagged with the installation it renders and +// where that installation is mounted. +function SettingsRoom() { + const { owner } = Route.useRouteContext() + const match = Route.useMatch({ + select: ({ routeId, fullPath, pathname }) => ({ + installation: routeId.slice(0, routeId.indexOf(':')), + fullPath, + pathname, + }), + }) + return ( +
+

+ {match.installation} {match.fullPath} + → {match.pathname} +

+

{`Settings of ${owner.name}`}

+ +
+ ) +} diff --git a/e2e/react-start/route-modules/packages/settings/src/routes/index.tsx b/e2e/react-start/route-modules/packages/settings/src/routes/index.tsx new file mode 100644 index 0000000000..86e80418f9 --- /dev/null +++ b/e2e/react-start/route-modules/packages/settings/src/routes/index.tsx @@ -0,0 +1,15 @@ +import { Link, createFileRoute } from '../routeScope.gen' + +export const Route = createFileRoute('@start-route-modules/settings:/')({ + component: SettingsIndex, +}) + +function SettingsIndex() { + return ( +
    +
  • + Profile +
  • +
+ ) +} diff --git a/e2e/react-start/route-modules/packages/settings/src/routes/profile.tsx b/e2e/react-start/route-modules/packages/settings/src/routes/profile.tsx new file mode 100644 index 0000000000..88f10273ba --- /dev/null +++ b/e2e/react-start/route-modules/packages/settings/src/routes/profile.tsx @@ -0,0 +1,27 @@ +import { createFileRoute } from '../routeScope.gen' +import { getProfile } from '../api' + +export const Route = createFileRoute('@start-route-modules/settings:/profile')({ + // Each installation loads the profile of the owner its host provides. + loader: ({ context }) => + getProfile({ data: { kind: context.owner.kind, id: context.owner.id } }), + component: Profile, +}) + +function Profile() { + const profile = Route.useLoaderData() + return ( +
+

Profile

+
+
Kind
+
{profile.kind}
+
Handle
+
+ {profile.handle} +
+
+ All settings +
+ ) +} diff --git a/e2e/react-start/route-modules/packages/settings/tsconfig.json b/e2e/react-start/route-modules/packages/settings/tsconfig.json new file mode 100644 index 0000000000..1de72ddc24 --- /dev/null +++ b/e2e/react-start/route-modules/packages/settings/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "skipLibCheck": true, + "noEmit": true, + "types": [] + }, + "include": ["src"] +} diff --git a/e2e/react-start/route-modules/packages/settings/tsconfig.route-types.json b/e2e/react-start/route-modules/packages/settings/tsconfig.route-types.json new file mode 100644 index 0000000000..0c9aec3caf --- /dev/null +++ b/e2e/react-start/route-modules/packages/settings/tsconfig.route-types.json @@ -0,0 +1,13 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "emitDeclarationOnly": true, + "noEmitOnError": true, + "declarationMap": true, + "rootDir": ".", + "outDir": ".tanstack/types" + }, + "include": ["src"] +} diff --git a/e2e/react-start/route-modules/packages/team/package.json b/e2e/react-start/route-modules/packages/team/package.json new file mode 100644 index 0000000000..cb8b8d1f05 --- /dev/null +++ b/e2e/react-start/route-modules/packages/team/package.json @@ -0,0 +1,41 @@ +{ + "name": "@start-route-modules/team", + "private": true, + "type": "module", + "tanstack": { + "router": { + "module": { + "uses": [ + "@start-route-modules/settings" + ] + } + } + }, + "exports": { + "./route-types": { + "types": "./.tanstack/types/src/routeContract.gen.d.ts" + }, + "./route-module": { + "types": "./.tanstack/types/src/routeModule.gen.d.ts", + "default": "./src/routeModule.gen.ts" + }, + "./package.json": "./package.json" + }, + "scripts": { + "generate": "tsr generate", + "emit-types": "node -e \"require('node:fs').rmSync('.tanstack/types',{recursive:true,force:true})\" && tsc -p tsconfig.route-types.json", + "check": "tsc --noEmit" + }, + "dependencies": { + "@start-route-modules/settings": "workspace:*", + "@tanstack/react-router": "workspace:^", + "@tanstack/react-start": "workspace:^", + "react": "^19.0.0" + }, + "devDependencies": { + "@tanstack/router-cli": "workspace:^", + "@tanstack/router-core": "workspace:^", + "@tanstack/start-client-core": "workspace:^", + "@types/react": "^19.0.8" + } +} diff --git a/e2e/react-start/route-modules/packages/team/src/api.ts b/e2e/react-start/route-modules/packages/team/src/api.ts new file mode 100644 index 0000000000..a0df5ce0c6 --- /dev/null +++ b/e2e/react-start/route-modules/packages/team/src/api.ts @@ -0,0 +1,8 @@ +import { createServerFn } from './routeScope.gen' + +/** The members of an organization, loaded on the server. */ +export const listMembers = createServerFn() + .validator((orgId: string) => orgId) + .handler(({ data }) => + ['ada', 'grace'].map((name) => ({ id: name, label: `${name} (${data})` })), + ) diff --git a/e2e/react-start/route-modules/packages/team/src/routes/__root.tsx b/e2e/react-start/route-modules/packages/team/src/routes/__root.tsx new file mode 100644 index 0000000000..f6976ed6d0 --- /dev/null +++ b/e2e/react-start/route-modules/packages/team/src/routes/__root.tsx @@ -0,0 +1,25 @@ +import { Outlet } from '@tanstack/react-router' +import { createModuleRoot } from '../routeScope.gen' + +// The organization comes from the host route the application mounts the team +// under, so the team works below any route that provides it. +export const Route = createModuleRoot<{ org: { id: string; name: string } }>()({ + component: TeamLayout, +}) + +// The module's region: a room tagged with its package and where it is +// mounted, with the URL its mount path resolved to. +function TeamLayout() { + const { org } = Route.useRouteContext() + const pathname = Route.useMatch({ select: (match) => match.pathname }) + return ( +
+

+ @start-route-modules/team {Route.fullPath} + → {pathname} +

+

{`Team of ${org.name}`}

+ +
+ ) +} diff --git a/e2e/react-start/route-modules/packages/team/src/routes/index.tsx b/e2e/react-start/route-modules/packages/team/src/routes/index.tsx new file mode 100644 index 0000000000..d7c8dec462 --- /dev/null +++ b/e2e/react-start/route-modules/packages/team/src/routes/index.tsx @@ -0,0 +1,27 @@ +import { Link, createFileRoute, settings } from '../routeScope.gen' +import { listMembers } from '../api' + +export const Route = createFileRoute('@start-route-modules/team:/')({ + loader: ({ context }) => listMembers({ data: context.org.id }), + component: Members, +}) + +function Members() { + const members = Route.useLoaderData() + return ( + <> +
    + {members.map((member) => ( +
  • + + {member.label} + +
  • + ))} +
+ {/* The settings are installed for organizations and for people: the + team links to the installation of its own organization. */} + Organization profile + + ) +} diff --git a/e2e/react-start/route-modules/packages/team/src/routes/members.$memberId.tsx b/e2e/react-start/route-modules/packages/team/src/routes/members.$memberId.tsx new file mode 100644 index 0000000000..a51df6a1d9 --- /dev/null +++ b/e2e/react-start/route-modules/packages/team/src/routes/members.$memberId.tsx @@ -0,0 +1,28 @@ +import { Link, createFileRoute } from '../routeScope.gen' + +export const Route = createFileRoute( + '@start-route-modules/team:/members/$memberId', +)({ + component: Member, +}) + +function Member() { + const { memberId } = Route.useParams() + const { org } = Route.useRouteContext() + return ( +
+

{`${memberId} at ${org.name}`}

+
+
Organization
+
+ {org.id} +
+
Member
+
+ {memberId} +
+
+ All members +
+ ) +} diff --git a/e2e/react-start/route-modules/packages/team/tsconfig.json b/e2e/react-start/route-modules/packages/team/tsconfig.json new file mode 100644 index 0000000000..1de72ddc24 --- /dev/null +++ b/e2e/react-start/route-modules/packages/team/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "skipLibCheck": true, + "noEmit": true, + "types": [] + }, + "include": ["src"] +} diff --git a/e2e/react-start/route-modules/packages/team/tsconfig.route-types.json b/e2e/react-start/route-modules/packages/team/tsconfig.route-types.json new file mode 100644 index 0000000000..0c9aec3caf --- /dev/null +++ b/e2e/react-start/route-modules/packages/team/tsconfig.route-types.json @@ -0,0 +1,13 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "emitDeclarationOnly": true, + "noEmitOnError": true, + "declarationMap": true, + "rootDir": ".", + "outDir": ".tanstack/types" + }, + "include": ["src"] +} diff --git a/e2e/react-start/route-modules/packages/web/package.json b/e2e/react-start/route-modules/packages/web/package.json new file mode 100644 index 0000000000..f1f50b148b --- /dev/null +++ b/e2e/react-start/route-modules/packages/web/package.json @@ -0,0 +1,34 @@ +{ + "name": "@start-route-modules/web", + "private": true, + "type": "module", + "scripts": { + "dev:vite": "vite dev", + "dev:rsbuild": "rsbuild dev", + "build:vite": "vite build && tsc --noEmit", + "build:rsbuild": "rsbuild build && tsc --noEmit", + "start": "node server.js" + }, + "dependencies": { + "@start-route-modules/catalog": "workspace:*", + "@start-route-modules/notes": "workspace:*", + "@start-route-modules/settings": "workspace:*", + "@start-route-modules/team": "workspace:*", + "@tanstack/react-router": "workspace:^", + "@tanstack/react-router-devtools": "workspace:^", + "@tanstack/react-start": "workspace:^", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@rsbuild/core": "^2.1.0", + "@rsbuild/plugin-react": "^2.0.0", + "@types/node": "^22.10.2", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "@typescript/native": "npm:typescript@^7.0.2", + "@vitejs/plugin-react": "^6.0.1", + "srvx": "^1.0.0", + "vite": "^8.0.14" + } +} diff --git a/e2e/react-start/route-modules/packages/web/route-modules.ts b/e2e/react-start/route-modules/packages/web/route-modules.ts new file mode 100644 index 0000000000..40dc69e6f6 --- /dev/null +++ b/e2e/react-start/route-modules/packages/web/route-modules.ts @@ -0,0 +1,28 @@ +/** + * The route modules the store installs, shared by the Vite and the Rsbuild + * configuration. `tests/workspace.ts` mirrors it for the generation tests. + */ +export const routeModules = { + includes: [ + { module: '@start-route-modules/catalog', at: '/shop' }, + { module: '@start-route-modules/notes', at: '/notes' }, + { + module: '@start-route-modules/team', + parent: '/orgs/$orgId', + at: '/team', + }, + // Installed twice: per organization and per person. + { + module: '@start-route-modules/settings', + parent: '/orgs/$orgId', + at: '/settings', + as: 'orgSettings', + }, + { + module: '@start-route-modules/settings', + parent: '/people/$personId', + at: '/settings', + as: 'personSettings', + }, + ], +} diff --git a/e2e/react-start/route-modules/packages/web/rsbuild.config.ts b/e2e/react-start/route-modules/packages/web/rsbuild.config.ts new file mode 100644 index 0000000000..fcbb669602 --- /dev/null +++ b/e2e/react-start/route-modules/packages/web/rsbuild.config.ts @@ -0,0 +1,16 @@ +import { defineConfig } from '@rsbuild/core' +import { pluginReact } from '@rsbuild/plugin-react' +import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' +import { routeModules } from './route-modules' + +// The e2e build of each toolchain and mode writes to its own directory. +const outDir = process.env.E2E_DIST_DIR ?? 'dist' + +export default defineConfig({ + plugins: [pluginReact(), tanstackStart({ router: { routeModules } })], + output: { + distPath: { + root: outDir, + }, + }, +}) diff --git a/e2e/react-start/route-modules/packages/web/server.js b/e2e/react-start/route-modules/packages/web/server.js new file mode 100644 index 0000000000..3f18062992 --- /dev/null +++ b/e2e/react-start/route-modules/packages/web/server.js @@ -0,0 +1,19 @@ +// Serves a production build of either toolchain: Vite writes the server +// entry to `server/server.js`, Rsbuild to `server/index.js`. +import { spawn } from 'node:child_process' +import { existsSync } from 'node:fs' +import path from 'node:path' + +const distDir = process.env.E2E_DIST_DIR || 'dist' +const serverEntry = + ['server.js', 'index.js'] + .map((file) => path.resolve(distDir, 'server', file)) + .find((file) => existsSync(file)) ?? + path.resolve(distDir, 'server', 'server.js') + +const child = spawn( + 'srvx', + ['--prod', '-s', path.resolve(distDir, 'client'), serverEntry], + { stdio: 'inherit', shell: process.platform === 'win32' }, +) +child.on('exit', (code) => process.exit(code ?? 0)) diff --git a/e2e/react-start/route-modules/packages/web/src/router.tsx b/e2e/react-start/route-modules/packages/web/src/router.tsx new file mode 100644 index 0000000000..b54237fd92 --- /dev/null +++ b/e2e/react-start/route-modules/packages/web/src/router.tsx @@ -0,0 +1,6 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ routeTree, scrollRestoration: true }) +} diff --git a/e2e/react-start/route-modules/packages/web/src/routes/__root.tsx b/e2e/react-start/route-modules/packages/web/src/routes/__root.tsx new file mode 100644 index 0000000000..b6a3041deb --- /dev/null +++ b/e2e/react-start/route-modules/packages/web/src/routes/__root.tsx @@ -0,0 +1,90 @@ +/// +import * as React from 'react' +import type { ReactNode } from 'react' +import { + ClientOnly, + HeadContent, + Link, + Scripts, + createRootRoute, +} from '@tanstack/react-router' +import { catalog, notes, team } from '../routeScope.gen' +import '../styles.css' + +// The router devtools, in development only. +const RouterDevtools = import.meta.env.DEV + ? React.lazy(() => + import('@tanstack/react-router-devtools').then((module) => ({ + default: module.TanStackRouterDevtools, + })), + ) + : () => null + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { title: 'Acme Store' }, + ], + }), + shellComponent: RootDocument, +}) + +function RootDocument({ children }: { children: ReactNode }) { + return ( + + + + + +
+ + + Acme Store + + + server-rendered

}> +

+ hydrated +

+
+
+
{children}
+ + + + + + + ) +} + +/** A small floor plan: outer walls with a door, two inner walls. */ +function PlanMark() { + return ( + + ) +} diff --git a/e2e/react-start/route-modules/packages/web/src/routes/index.tsx b/e2e/react-start/route-modules/packages/web/src/routes/index.tsx new file mode 100644 index 0000000000..471165e1be --- /dev/null +++ b/e2e/react-start/route-modules/packages/web/src/routes/index.tsx @@ -0,0 +1,90 @@ +import { createFileRoute } from '@tanstack/react-router' +import { orgSettings, personSettings } from '../routeScope.gen' + +export const Route = createFileRoute('/')({ + component: Home, +}) + +// A key plan of the store: every module's room where the store mounts it, +// nested like the routes. +function Home() { + return ( + <> +

Home

+

+ The Acme storefront, rendered on the server. Each region is a route + module, drawn as a room: its tag names the package and where the store + mounts it. +

+
+
+

+ @start-route-modules/catalog /shop +

+

+ Prices for the signed-in shopper, refreshed through a server + function. +

+
+
+

+ @start-route-modules/notes /notes +

+

A router-only module; the store serializes its data.

+
+ {/* The organization route is the store's own: the team below it gets + `orgId` from the URL. */} +
+

+ Host route /orgs/$orgId +

+
+
+

+ @start-route-modules/team /team +

+

+ Members of the organization in the URL, loaded on the server. +

+
+
+

+ @start-route-modules/settings#orgSettings /settings +

+

+ + Globex settings + +

+
+
+
+ {/* The settings are installed a second time, per person. */} +
+

+ Host route /people/$personId +

+
+
+

+ @start-route-modules/settings#personSettings{' '} + /settings +

+

+ + Ada's profile + +

+
+
+
+
+ + ) +} diff --git a/e2e/react-start/route-modules/packages/web/src/routes/orgs.$orgId.tsx b/e2e/react-start/route-modules/packages/web/src/routes/orgs.$orgId.tsx new file mode 100644 index 0000000000..3c08aa0637 --- /dev/null +++ b/e2e/react-start/route-modules/packages/web/src/routes/orgs.$orgId.tsx @@ -0,0 +1,15 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +// The host route of the modules mounted per organization: they get its path +// params in their URLs and the organization as context, and its settings +// installation the organization as their owner. +export const Route = createFileRoute('/orgs/$orgId')({ + beforeLoad: ({ params }) => { + const name = params.orgId.toUpperCase() + return { + org: { id: params.orgId, name }, + owner: { kind: 'organization' as const, id: params.orgId, name }, + } + }, + component: () => , +}) diff --git a/e2e/react-start/route-modules/packages/web/src/routes/people.$personId.tsx b/e2e/react-start/route-modules/packages/web/src/routes/people.$personId.tsx new file mode 100644 index 0000000000..19ac32e5c7 --- /dev/null +++ b/e2e/react-start/route-modules/packages/web/src/routes/people.$personId.tsx @@ -0,0 +1,13 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +// The host route of the settings installation per person. +export const Route = createFileRoute('/people/$personId')({ + beforeLoad: ({ params }) => ({ + owner: { + kind: 'person' as const, + id: params.personId, + name: params.personId[0]!.toUpperCase() + params.personId.slice(1), + }, + }), + component: () => , +}) diff --git a/e2e/react-start/route-modules/packages/web/src/start.ts b/e2e/react-start/route-modules/packages/web/src/start.ts new file mode 100644 index 0000000000..5d11d4c173 --- /dev/null +++ b/e2e/react-start/route-modules/packages/web/src/start.ts @@ -0,0 +1,12 @@ +import { createMiddleware, createStart } from '@tanstack/react-start' +import { startModules } from './startModules.gen' + +// Provides the request context the catalog requires. +const shopper = createMiddleware().server(({ next }) => + next({ context: { shopper: 'ada' } }), +) + +export const startInstance = createStart(() => ({ + extends: startModules, + requestMiddleware: [shopper], +})) diff --git a/e2e/react-start/route-modules/packages/web/src/styles.css b/e2e/react-start/route-modules/packages/web/src/styles.css new file mode 100644 index 0000000000..e90577b1bd --- /dev/null +++ b/e2e/react-start/route-modules/packages/web/src/styles.css @@ -0,0 +1,486 @@ +/* + * Acme Store: the route-module fixtures drawn as a floor plan. Every route + * module is a room: a wall line, a zoning tint and a room tag with its package + * and mount path. Violet marks the active route and nothing else. + */ + +:root { + color-scheme: light; + + --ground: #f4f6f9; + --sheet: #ffffff; + --ink: #1f2328; + --ink-2: #4b535c; + --ink-3: #59616b; + --line: #d3d7db; + --wall: #2a3036; + --route: #5b3fd1; + --route-wash: #e9e5fb; + /* Link underlines: 3:1 or better on the ground and on every zone. */ + --underline: color-mix(in srgb, var(--wall) 55%, transparent); + --zone: #eef0f2; + + --font: + ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, + 'Helvetica Neue', Arial, sans-serif; + /* Plan lettering: a local condensed face where there is one. */ + --font-lettering: + 'Avenir Next Condensed', 'Roboto Condensed', 'Arial Narrow', ui-sans-serif, + system-ui, sans-serif; + --mono: ui-monospace, 'SF Mono', Menlo, Consolas, monospace; + + --s1: 4px; + --s2: 8px; + --s3: 12px; + --s4: 16px; + --s5: 20px; + --s6: 24px; + --s8: 32px; + --s10: 40px; + --s12: 48px; + + /* A drafted wall: two lines with the wall's thickness between them. */ + --wall-line: 6px double var(--wall); + --ease-out: cubic-bezier(0.16, 1, 0.3, 1); +} + +/* Zoning: one tint per module, as on a zoning plan. */ +[data-route-module='@start-route-modules/catalog'] { + --zone: #e1ebdd; +} +[data-route-module='@start-route-modules/notes'] { + --zone: #e7e9e4; +} +[data-route-module='@start-route-modules/team'] { + --zone: #d9eeeb; +} +[data-route-module='@start-route-modules/settings'] { + --zone: #efecd2; +} + +*, +*::before, +*::after { + box-sizing: border-box; +} + +html { + background: var(--ground); + scrollbar-color: var(--line) transparent; +} + +body { + margin: 0; + color: var(--ink); + font: 400 15px/1.55 var(--font); + -webkit-font-smoothing: antialiased; +} + +::selection { + background: var(--route-wash); + color: var(--ink); +} + +:focus-visible { + outline: 2px solid var(--wall); + outline-offset: 2px; + border-radius: 2px; +} + +h1, +h2, +h3 { + margin: 0 0 var(--s3); + font-weight: 650; + letter-spacing: -0.02em; + line-height: 1.2; + text-wrap: balance; +} +h1 { + font-size: 30px; +} +h2 { + font-size: 22px; +} +h3 { + font-size: 18px; +} + +p { + margin: 0 0 var(--s3); + max-width: 68ch; +} + +code { + font: 500 0.92em var(--mono); +} + +a { + color: var(--ink); + text-decoration: underline; + text-decoration-color: var(--underline); + text-decoration-thickness: 1px; + text-underline-offset: 3px; + transition: text-decoration-color 160ms var(--ease-out); +} +a:hover { + text-decoration-color: var(--ink); +} + +button { + font: inherit; +} + +/* Shell */ + +.topbar { + position: sticky; + top: 0; + z-index: 10; + display: flex; + align-items: center; + gap: var(--s8); + min-height: 52px; + padding: 0 var(--s6); + background: var(--sheet); + border-bottom: 1px solid var(--line); +} + +.brand { + display: inline-flex; + align-items: center; + gap: var(--s2); + font-weight: 650; + letter-spacing: -0.01em; + text-decoration: none; + white-space: nowrap; +} +.brand-mark { + flex: none; + width: 18px; + height: 18px; + color: var(--wall); +} +.brand small { + color: var(--ink-3); + font-size: 13px; + font-weight: 500; +} + +.nav { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--s1) var(--s5); + font-size: 14px; +} +.nav a { + position: relative; + margin: 0 calc(-1 * var(--s1)); + padding: var(--s3) var(--s1); + color: var(--ink-2); + text-decoration: none; +} +.nav a:hover { + color: var(--ink); +} +.nav a[data-status='active'] { + color: var(--route); +} +.nav a[data-status='active']::after { + content: ''; + position: absolute; + inset: auto var(--s1) 0; + height: 2px; + background: var(--route); +} +.nav-group { + display: inline-flex; + align-items: center; + gap: var(--s4); + padding-left: var(--s5); + border-left: 1px solid var(--line); +} + +/* Whether the page has hydrated: a hollow plan dot until then. */ +.status { + display: inline-flex; + align-items: center; + gap: var(--s2); + margin: 0 0 0 auto; + color: var(--ink-3); + font-size: 13px; + white-space: nowrap; +} +.status::before { + content: ''; + width: 8px; + height: 8px; + border: 2px solid var(--ink-3); + border-radius: 50%; +} +.status.hydrated { + color: var(--ink); +} +.status.hydrated::before { + background: var(--wall); + border-color: var(--wall); +} + +.page { + max-width: 1080px; + margin: 0 auto; + padding: var(--s10) var(--s6) 120px; +} + +.lead { + color: var(--ink-2); + font-size: 17px; +} + +/* Rooms: the signature. A module's region is a room with a wall line, its + zoning tint, and a tag on the wall naming the package and its mount. */ + +.room { + margin-top: var(--s5); + padding: 0 var(--s6) var(--s6); + background: var(--zone) padding-box; + border: var(--wall-line); + animation: room-in 420ms var(--ease-out); +} +.room .room { + margin-top: var(--s8); +} +.room > :last-child { + margin-bottom: 0; +} +/* A room's title has one size whatever its level. */ +.room h1 { + font-size: 22px; +} + +/* The tag sits on the wall: pulled up onto its center line, it wraps on + narrow screens instead of clipping the resolved path. Names and paths keep + their source case: they are identifiers maintainers copy. */ +.room-tag { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 0 var(--s2); + width: fit-content; + max-width: 100%; + margin: -14px 0 var(--s5) calc(var(--s4) - var(--s6)); + padding: 2px var(--s2); + background: var(--sheet); + border: 1px solid var(--wall); + font: 600 12px/16px var(--font-lettering); + font-stretch: condensed; + font-variant-numeric: tabular-nums; + letter-spacing: 0.04em; +} +.room-tag code { + font: 500 11px/16px var(--mono); + color: var(--ink-2); +} +.room-tag .resolved { + color: var(--route); +} + +@keyframes room-in { + from { + background-color: var(--sheet); + } +} + +/* Lists, facts and controls inside rooms */ + +.rows { + margin: 0 0 var(--s4); + padding: 0; + list-style: none; + font-variant-numeric: tabular-nums; + border-top: 1px solid color-mix(in srgb, var(--wall) 22%, transparent); +} +.rows > li { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: var(--s4); + padding: var(--s3) 0; + border-bottom: 1px solid color-mix(in srgb, var(--wall) 22%, transparent); +} + +.rows .meta { + color: var(--ink-3); + font-size: 13px; +} + +.facts { + display: grid; + grid-template-columns: max-content 1fr; + align-items: baseline; + gap: var(--s2) var(--s6); + margin: 0 0 var(--s5); + font-variant-numeric: tabular-nums; +} +.facts dt { + color: var(--ink-3); + font-size: 13px; +} +.facts dd { + margin: 0; +} + +.actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--s3) var(--s5); +} + +.button { + display: inline-flex; + align-items: center; + min-height: 36px; + padding: 0 var(--s4); + color: var(--sheet); + background: var(--wall); + border: 0; + border-radius: 6px; + font-weight: 600; + font-size: 14px; + cursor: pointer; + transition: + background-color 160ms var(--ease-out), + transform 160ms var(--ease-out); +} +.button:hover { + background: var(--ink); +} +.button:active { + transform: translateY(1px); +} +.button[aria-busy='true'] { + background: var(--ink-3); + cursor: progress; +} + +.price { + margin: 0 0 var(--s4); + font-size: 22px; + font-weight: 600; + font-variant-numeric: tabular-nums; + letter-spacing: -0.01em; +} + +.server-state { + margin: 0 0 var(--s5); + padding: var(--s3) 0; + border-block: 1px solid color-mix(in srgb, var(--wall) 22%, transparent); + color: var(--ink-2); + font-size: 14px; +} +.server-state p { + margin: 0; +} + +.data { + font: 500 13px var(--mono); + font-variant-numeric: tabular-nums; +} +/* A value the server just sent again: one pass of a highlighter. */ +.fresh { + animation: fresh 1600ms var(--ease-out); +} +@keyframes fresh { + from { + background-color: #f7e7a1; + } +} + +/* Key plan on the home page: every room where the application mounts it. + A host route that is not a module is a plot boundary around its rooms. */ + +.plan { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + align-items: start; + gap: var(--s8) var(--s6); + margin-top: var(--s10); +} +.plan .room { + margin-top: 0; +} +.plan .room .room { + margin-top: var(--s6); +} +.plan .room > p:not(.room-tag) { + color: var(--ink-2); +} +.plot { + grid-column: 1 / -1; + padding: 0 var(--s6) var(--s6); + border: 1.5px dashed var(--ink-3); +} +.plot-rooms { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); + align-items: start; + gap: var(--s8) var(--s6); + padding-top: var(--s3); +} +.plot > .room-tag { + margin-top: -12px; + margin-bottom: var(--s4); + border-style: dashed; + border-color: var(--ink-3); + font-weight: 500; +} + +@media (max-width: 720px) { + .topbar { + position: static; + flex-wrap: wrap; + gap: 0 var(--s4); + padding: var(--s2) var(--s4) 0; + } + /* One scrolling row below the brand. */ + .nav { + order: 1; + flex-basis: 100%; + flex-wrap: nowrap; + gap: var(--s2); + overflow-x: auto; + scrollbar-width: none; + } + .nav a, + .nav-group { + flex: none; + } + .nav-group { + gap: var(--s2); + padding-left: var(--s2); + } + .page { + padding: var(--s6) var(--s4) 120px; + } + .room { + padding: 0 var(--s4) var(--s4); + } + .room-tag { + margin-left: 0; + } + .plan { + grid-template-columns: minmax(0, 1fr); + } + .plot { + padding: 0 var(--s4) var(--s4); + } +} + +@media (prefers-reduced-motion: reduce) { + .room, + .fresh { + animation: none; + } +} diff --git a/e2e/react-start/route-modules/packages/web/tsconfig.json b/e2e/react-start/route-modules/packages/web/tsconfig.json new file mode 100644 index 0000000000..30641bffe7 --- /dev/null +++ b/e2e/react-start/route-modules/packages/web/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ES2022", + "moduleResolution": "Bundler", + "module": "ESNext", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "skipLibCheck": true, + "noEmit": true, + "types": ["vite/client"] + }, + "include": ["src", "vite.config.ts", "rsbuild.config.ts", "route-modules.ts"] +} diff --git a/e2e/react-start/route-modules/packages/web/vite.config.ts b/e2e/react-start/route-modules/packages/web/vite.config.ts new file mode 100644 index 0000000000..9c60a3a87c --- /dev/null +++ b/e2e/react-start/route-modules/packages/web/vite.config.ts @@ -0,0 +1,14 @@ +import { defineConfig } from 'vite' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' +import { routeModules } from './route-modules' + +// The e2e build of each toolchain and mode writes to its own directory. +const outDir = process.env.E2E_DIST_DIR ?? 'dist' + +export default defineConfig({ + build: { + outDir, + }, + plugins: [tanstackStart({ router: { routeModules } }), viteReact()], +}) diff --git a/e2e/react-start/route-modules/playwright.config.ts b/e2e/react-start/route-modules/playwright.config.ts new file mode 100644 index 0000000000..dea91cd1a1 --- /dev/null +++ b/e2e/react-start/route-modules/playwright.config.ts @@ -0,0 +1,31 @@ +import { defineConfig, devices } from '@playwright/test' +import { appServerReady } from '@tanstack/router-e2e-utils' + +const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const baseURL = `http://localhost:${PORT}` +// Nx builds the application with the toolchain of each mode into +// `E2E_DIST_DIR` (`build::ssr` publishes the route modules first); +// this serves that build. Module files are compiled from source by the +// application. +const command = `cd packages/web && NODE_ENV=production PORT=${PORT} pnpm start` + +export default defineConfig({ + testDir: './e2e', + workers: 1, + reporter: [['line']], + use: { + baseURL, + }, + webServer: { + command, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/react-start/route-modules/playwright.dev.config.ts b/e2e/react-start/route-modules/playwright.dev.config.ts new file mode 100644 index 0000000000..2c920320a9 --- /dev/null +++ b/e2e/react-start/route-modules/playwright.dev.config.ts @@ -0,0 +1,30 @@ +import { defineConfig, devices } from '@playwright/test' +import { appServerReady } from '@tanstack/router-e2e-utils' + +const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' +const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const baseURL = `http://localhost:${PORT}` +// Development: the Start dev server of the toolchain renders module routes, +// runs their server functions and hot-updates their files. +const command = `node scripts/prepare.mjs && pnpm --filter @start-route-modules/web dev:${toolchain} --host 0.0.0.0 --port ${PORT}` + +export default defineConfig({ + testDir: './e2e-dev', + workers: 1, + reporter: [['line']], + use: { + baseURL, + }, + webServer: { + command, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/react-start/route-modules/scripts/prepare.mjs b/e2e/react-start/route-modules/scripts/prepare.mjs new file mode 100644 index 0000000000..4e4c927b79 --- /dev/null +++ b/e2e/react-start/route-modules/scripts/prepare.mjs @@ -0,0 +1,43 @@ +// Generates routes and builds declarations with the packages' TypeScript +// projects. The application's route tree is generated by the Start plugin. +// +// The modules list `@tanstack/router-core` (and the catalog +// `@tanstack/start-client-core`) as dev dependencies only because the fixture +// links the framework packages from the workspace: TypeScript names the types +// of a linked package's dependencies by their own package name. Installed from +// a registry, the declarations name them through `@tanstack/react-router` and +// `@tanstack/react-start`, the only packages modules need. +import { spawnSync } from 'node:child_process' +import { rmSync } from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { Generator, getConfig } from '@tanstack/router-generator' + +const packages = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../packages', +) + +const tsc = path.resolve( + packages, + '../../../../node_modules/.bin', + process.platform === 'win32' ? 'tsc.cmd' : 'tsc', +) + +for (const name of ['catalog', 'notes', 'settings', 'team']) { + const root = path.join(packages, name) + const config = getConfig({ disableLogging: true }, root) + await new Generator({ config, root }).run() + rmSync(path.join(root, '.tanstack/types'), { recursive: true, force: true }) + const result = spawnSync( + tsc, + ['-p', 'tsconfig.route-types.json', '--pretty', 'false'], + { cwd: root, stdio: 'inherit', shell: process.platform === 'win32' }, + ) + if (result.error) { + throw result.error + } + if (result.status !== 0) { + process.exit(result.status ?? 1) + } +} diff --git a/e2e/react-start/route-modules/tests/start-modules.test.ts b/e2e/react-start/route-modules/tests/start-modules.test.ts new file mode 100644 index 0000000000..3b816a79ab --- /dev/null +++ b/e2e/react-start/route-modules/tests/start-modules.test.ts @@ -0,0 +1,328 @@ +import path from 'node:path' +import { + existsSync, + mkdirSync, + readFileSync, + realpathSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs' +import { Generator, getConfig } from '@tanstack/router-generator' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { Workspace, errorsIn } from './workspace' + +let workspace: Workspace + +beforeEach(() => { + workspace = new Workspace() +}) + +afterEach(() => { + workspace.dispose() +}) + +async function publishModules() { + for (const name of ['catalog', 'notes', 'settings', 'team']) { + const result = await workspace.publish(name) + expect(result.diagnostics, name).toEqual([]) + } +} + +describe('Start route modules', () => { + it.each([ + { + specifier: 'http', + importedType: 'IncomingMessage', + requiredContext: '{ request: IncomingMessage }', + validConsumer: + 'export const method: string | undefined = context.request.method', + invalidConsumer: 'export const invalid: number = context.request.method', + }, + { + specifier: '#request-context', + importedType: 'RequestContext', + requiredContext: 'RequestContext', + validConsumer: 'export const traceId: string = context.traceId', + invalidConsumer: 'export const invalid: number = context.traceId', + }, + ])( + 'consumes published requirements that import $specifier', + async ({ + specifier, + importedType, + requiredContext, + validConsumer, + invalidConsumer, + }) => { + const catalog = workspace.pkg('catalog') + const app = workspace.pkg('web') + rmSync(path.join(catalog, 'src'), { recursive: true, force: true }) + mkdirSync(path.join(catalog, 'src/routes'), { recursive: true }) + if (specifier === 'http') { + const nodeTypes = path.join(catalog, 'node_modules/@types/node') + mkdirSync(path.dirname(nodeTypes), { recursive: true }) + if (!existsSync(nodeTypes)) { + symlinkSync( + realpathSync( + path.resolve( + import.meta.dirname, + '../../../../node_modules/@types/node', + ), + ), + nodeTypes, + 'dir', + ) + } + workspace.edit('catalog', 'package.json', (source) => { + const pkg = JSON.parse(source) + pkg.devDependencies['@types/node'] = '*' + return JSON.stringify(pkg) + }) + workspace.edit('catalog', 'tsconfig.json', (source) => { + const config = JSON.parse(source) + config.compilerOptions.types = ['node'] + return JSON.stringify(config) + }) + } else { + mkdirSync(path.join(catalog, 'types'), { recursive: true }) + writeFileSync( + path.join(catalog, 'types/request-context.d.ts'), + 'export interface RequestContext { traceId: string }\n', + ) + workspace.edit('catalog', 'package.json', (source) => { + const pkg = JSON.parse(source) + pkg.imports = { '#request-context': './types/request-context.d.ts' } + return JSON.stringify(pkg) + }) + } + writeFileSync( + path.join(catalog, 'src/requirements.ts'), + `export type { StartModuleRequirements } from '@tanstack/react-start' +import type { ${importedType} } from '${specifier}' +declare module '@tanstack/react-start' { + interface StartModuleRequirements { + '@start-route-modules/catalog': { requestContext: ${requiredContext} } + } +} +`, + ) + writeFileSync( + path.join(catalog, 'src/routes/__root.tsx'), + `export type {} from '../requirements' +import { createModuleRoot } from '../routeScope.gen' +export const Route = createModuleRoot()({}) +`, + ) + const published = await workspace.publish('catalog') + expect(published.diagnostics).toEqual([]) + expect( + readFileSync( + path.join(catalog, '.tanstack/types/src/requirements.d.ts'), + 'utf8', + ), + ).toContain(`from '${specifier}'`) + + rmSync(path.join(app, 'src'), { recursive: true, force: true }) + mkdirSync(path.join(app, 'src/routes'), { recursive: true }) + writeFileSync( + path.join(app, 'src/routes/__root.tsx'), + `import { createRootRoute } from '@tanstack/react-router' +export const Route = createRootRoute() +`, + ) + writeFileSync( + path.join(app, 'src/request-context.ts'), + `import type { StartModuleRequirements } from '@tanstack/react-start' +type RequiredContext = StartModuleRequirements['@start-route-modules/catalog']['requestContext'] +declare module '@tanstack/react-start' { + interface Register { server: { requestContext: RequiredContext } } +} +declare const context: RequiredContext +${validConsumer} +// @ts-expect-error Published requirement imports preserve their field types. +${invalidConsumer} +`, + ) + workspace.edit('web', 'tsconfig.json', (source) => { + const config = JSON.parse(source) + config.compilerOptions.skipLibCheck = false + config.compilerOptions.types = ['node'] + config.include = ['src'] + return JSON.stringify(config) + }) + await new Generator({ + root: app, + config: getConfig( + { + disableLogging: true, + routeModules: { includes: ['@start-route-modules/catalog'] }, + }, + app, + ), + }).run() + rmSync(path.join(catalog, 'src'), { recursive: true, force: true }) + expect(workspace.checkApp().diagnostics).toEqual([]) + }, + ) + + it('checks published requirements-only modules against the default Start instance', async () => { + const catalog = workspace.pkg('catalog') + const app = workspace.pkg('web') + rmSync(path.join(catalog, 'src'), { recursive: true, force: true }) + mkdirSync(path.join(catalog, 'src/routes'), { recursive: true }) + writeFileSync( + path.join(catalog, 'src/requirements.ts'), + `export type { StartModuleRequirements } from '@tanstack/react-start' +declare module '@tanstack/react-start' { + interface StartModuleRequirements { + '@start-route-modules/catalog': { requestContext: { shopper: string } } + } +} +`, + ) + writeFileSync( + path.join(catalog, 'src/routes/__root.tsx'), + `export type {} from '../requirements' +import { createModuleRoot } from '../routeScope.gen' +export const Route = createModuleRoot()({}) +`, + ) + writeFileSync( + path.join(catalog, 'src/routes/index.tsx'), + `import { createFileRoute } from '../routeScope.gen' +export const Route = createFileRoute('@start-route-modules/catalog:/')({}) +`, + ) + const published = await workspace.publish('catalog') + expect(published.diagnostics).toEqual([]) + + rmSync(path.join(app, 'src'), { recursive: true, force: true }) + mkdirSync(path.join(app, 'src/routes'), { recursive: true }) + writeFileSync( + path.join(app, 'src/routes/__root.tsx'), + `import { createRootRoute } from '@tanstack/react-router' +export const Route = createRootRoute() +`, + ) + workspace.edit('web', 'tsconfig.json', (source) => { + const config = JSON.parse(source) + config.compilerOptions.skipLibCheck = false + config.compilerOptions.types = ['node'] + config.include = ['src'] + return JSON.stringify(config) + }) + await new Generator({ + root: app, + config: getConfig( + { + disableLogging: true, + routeModules: { + includes: [ + { + module: '@start-route-modules/catalog', + as: 'requirementsOnly', + at: '/catalog', + }, + ], + }, + }, + app, + ), + }).run() + + // Consumer checking must load the augmentation from the published contract. + rmSync(path.join(catalog, 'src'), { recursive: true, force: true }) + const missing = workspace.checkApp() + expect(missing.ok).toBe(false) + expect( + errorsIn(missing.diagnostics, 'startModules.gen.ts').join('\n'), + ).toContain( + "Route module '@start-route-modules/catalog' requires request context 'shopper' that is not provided from application middleware", + ) + + // handler.fetch can satisfy requirements without a custom Start instance. + writeFileSync( + path.join(app, 'src/request-context.ts'), + `import '@tanstack/react-start' +declare module '@tanstack/react-start' { + interface Register { + server: { requestContext: { shopper: string } } + } +} +`, + ) + expect(workspace.checkApp().diagnostics).toEqual([]) + }) + + it('the application type-checks against the published modules', async () => { + await publishModules() + await workspace.generateApp() + + expect((await workspace.checkApp()).diagnostics).toEqual([]) + }) + + it('the application must provide the request context a module requires', async () => { + await publishModules() + workspace.edit('web', 'src/start.ts', (source) => + source.replace(' requestMiddleware: [shopper],\n', ''), + ) + await workspace.generateApp() + + const result = await workspace.checkApp() + expect(result.ok).toBe(false) + expect( + errorsIn(result.diagnostics, 'startModules.gen.ts').join('\n'), + ).toContain( + "Route module '@start-route-modules/catalog' requires request context 'shopper' that is not provided from application middleware", + ) + }) + + it('the application must install the fragments of its modules', async () => { + await publishModules() + workspace.edit('web', 'src/start.ts', (source) => + source.replace(' extends: startModules,\n', ''), + ) + await workspace.generateApp() + + const result = await workspace.checkApp() + expect(result.ok).toBe(false) + expect( + errorsIn(result.diagnostics, 'startModules.gen.ts').join('\n'), + ).toContain( + "Route module '@start-route-modules/catalog' is not installed: add 'extends: startModules' to createStart()", + ) + }) + + it("a module's server functions and loaders are validated against its fragment", async () => { + workspace.edit('catalog', 'src/start.ts', (source) => + source.replace(' serializationAdapters: [moneyAdapter],\n', ''), + ) + + const result = await workspace.publish('catalog') + expect(result.ok).toBe(false) + // `Money` has a method, so it is only serializable with the adapter. + const diagnostics = result.diagnostics.join('\n') + expect(diagnostics).toMatch(/src\/api\.ts\(\d+,\d+\): error TS2345/) + expect(diagnostics).toContain('Function may not be serializable') + }) + + it("the application serializes a router-only module's results", async () => { + workspace.edit('notes', 'src/routes/index.tsx', (source) => + source.replace( + "loader: () => ({ notes: ['Compose route modules', 'Ship it'] }),", + "loader: () => ({ notes: ['Compose route modules'], open: () => {} }),", + ), + ) + await publishModules() + await workspace.generateApp() + + const result = await workspace.checkApp() + expect(result.ok).toBe(false) + expect( + errorsIn(result.diagnostics, 'routeTree.gen.ts').join('\n'), + ).toContain( + "Route module '@start-route-modules/notes' returns loader or beforeLoad results from '@start-route-modules/notes:/' that the application cannot serialize", + ) + }) +}) diff --git a/e2e/react-start/route-modules/tests/workspace.ts b/e2e/react-start/route-modules/tests/workspace.ts new file mode 100644 index 0000000000..da4a3bf628 --- /dev/null +++ b/e2e/react-start/route-modules/tests/workspace.ts @@ -0,0 +1,225 @@ +import path from 'node:path' +import os from 'node:os' +import crypto from 'node:crypto' +import { spawnSync } from 'node:child_process' +import { + cpSync, + existsSync, + mkdirSync, + readFileSync, + readdirSync, + realpathSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs' +import { fileURLToPath } from 'node:url' +import { Generator, getConfig } from '@tanstack/router-generator' + +const here = path.dirname(fileURLToPath(import.meta.url)) +const fixtureRoot = path.resolve(here, '../packages') +const repoRoot = path.resolve(here, '../../../..') +/** The repository's TypeScript compiler (`tsc` of `@typescript/native`). */ +const tsc = path.join(repoRoot, 'node_modules', '.bin', 'tsc') + +const workspaceScope = '@start-route-modules/' +const generatedFile = /\.gen(?:\.[^.]+)?\.tsx?$/ + +/** The application's route modules (`vite.config.ts`). */ +const routeModules = { + includes: [ + { module: '@start-route-modules/catalog', at: '/shop' }, + { module: '@start-route-modules/notes', at: '/notes' }, + { + module: '@start-route-modules/team', + parent: '/orgs/$orgId', + at: '/team', + }, + { + module: '@start-route-modules/settings', + parent: '/orgs/$orgId', + at: '/settings', + as: 'orgSettings', + }, + { + module: '@start-route-modules/settings', + parent: '/people/$personId', + at: '/settings', + as: 'personSettings', + }, + ], +} + +/** The route tree footer the TanStack Start plugin generates. */ +const startFooter = [ + `import type { getRouter } from './router.tsx' +import type { startInstance } from './start.ts' +declare module '@tanstack/react-start' { + interface Register { + ssr: true + router: Awaited> + config: Awaited> + } +}`, +] + +function listDependencies(nodeModules: string): Array { + if (!existsSync(nodeModules)) { + return [] + } + const entries: Array = [] + for (const entry of readdirSync(nodeModules)) { + if (entry.startsWith('.')) { + continue + } + if (entry.startsWith('@')) { + for (const scoped of readdirSync(path.join(nodeModules, entry))) { + entries.push(`${entry}/${scoped}`) + } + } else { + entries.push(entry) + } + } + return entries +} + +/** + * A copy of the fixture packages in a temporary directory. Workspace route + * modules are linked to their copies; every other dependency is linked to the + * package the repository installed. Nothing generated is copied. + */ +export class Workspace { + readonly root: string + + constructor() { + const dir = path.join( + os.tmpdir(), + `tsr-start-route-modules-${crypto.randomBytes(4).toString('hex')}`, + ) + mkdirSync(dir, { recursive: true }) + this.root = realpathSync(dir) + for (const name of ['catalog', 'notes', 'settings', 'team', 'web']) { + this.addPackage(name) + } + } + + private addPackage(name: string) { + const from = path.join(fixtureRoot, name) + const to = this.pkg(name) + cpSync(from, to, { + recursive: true, + filter: (file) => + !file.includes(`${path.sep}node_modules`) && + !file.includes(`${path.sep}.tanstack`) && + !file.includes(`${path.sep}dist`) && + !generatedFile.test(file), + }) + for (const dependency of listDependencies( + path.join(from, 'node_modules'), + )) { + const link = path.join(to, 'node_modules', dependency) + mkdirSync(path.dirname(link), { recursive: true }) + const target = dependency.startsWith(workspaceScope) + ? this.pkg(dependency.slice(workspaceScope.length)) + : realpathSync(path.join(from, 'node_modules', dependency)) + symlinkSync(target, link, 'dir') + } + } + + pkg(name: string) { + return path.join(this.root, name) + } + + edit(name: string, file: string, edit: (content: string) => string) { + const full = path.join(this.pkg(name), file) + const before = readFileSync(full, 'utf8') + const after = edit(before) + if (after === before) { + throw new Error(`The edit of ${name}/${file} changed nothing`) + } + writeFileSync(full, after) + } + + /** Generates and publishes a route module. */ + async publish(name: string) { + const root = this.pkg(name) + await new Generator({ + config: getConfig({ disableLogging: true }, root), + root, + }).run() + const project = JSON.parse( + readFileSync(path.join(root, 'tsconfig.route-types.json'), 'utf8'), + ) + rmSync( + path.resolve( + root, + project.compilerOptions.declarationDir ?? + project.compilerOptions.outDir, + ), + { recursive: true, force: true }, + ) + return this.compile(name, ['-p', 'tsconfig.route-types.json']) + } + + /** Generates the application's route tree like the Start plugin does. */ + async generateApp() { + const root = this.pkg('web') + const config = getConfig( + { + disableLogging: true, + target: 'react', + routeModules, + routeTreeFileFooter: startFooter, + }, + root, + ) + await new Generator({ config, root }).run() + } + + /** Type-checks the application against the published modules. */ + checkApp() { + return this.compile('web', ['-p', 'tsconfig.json', '--noEmit']) + } + + private compile(name: string, args: Array) { + const result = spawnSync(tsc, [...args, '--pretty', 'false'], { + cwd: this.pkg(name), + encoding: 'utf8', + }) + return { + ok: result.status === 0, + diagnostics: result.error + ? [result.error.message] + : `${result.stdout ?? ''}${result.stderr ?? ''}` + .split(/\r?\n/) + .filter((line) => line.trim() !== ''), + } + } + + dispose() { + rmSync(this.root, { recursive: true, force: true }) + } +} + +/** The diagnostics of a failed check that point into `file`. */ +export function errorsIn(diagnostics: Array, file: string) { + const errors: Array = [] + let current: string | undefined + for (const line of diagnostics) { + if (/^\s/.test(line)) { + if (current !== undefined) { + current += `\n${line}` + } + continue + } + if (current !== undefined) { + errors.push(current) + } + current = + line.startsWith(file) || line.includes(`/${file}(`) ? line : undefined + } + if (current !== undefined) { + errors.push(current) + } + return errors +} diff --git a/e2e/react-start/route-modules/tsconfig.json b/e2e/react-start/route-modules/tsconfig.json new file mode 100644 index 0000000000..341902faed --- /dev/null +++ b/e2e/react-start/route-modules/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "strict": true, + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "skipLibCheck": true, + "noEmit": true, + "types": ["node"] + }, + "include": [ + "tests", + "e2e", + "e2e-dev", + "scripts", + "vitest.config.ts", + "playwright.config.ts", + "playwright.dev.config.ts" + ] +} diff --git a/e2e/react-start/route-modules/vitest.config.ts b/e2e/react-start/route-modules/vitest.config.ts new file mode 100644 index 0000000000..a2233ebb31 --- /dev/null +++ b/e2e/react-start/route-modules/vitest.config.ts @@ -0,0 +1,11 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + include: ['tests/**/*.test.ts'], + // Each test runs the generator and the TypeScript compiler on a workspace. + testTimeout: 120_000, + hookTimeout: 120_000, + fileParallelism: false, + }, +}) diff --git a/e2e/solid-router/route-modules/.gitignore b/e2e/solid-router/route-modules/.gitignore new file mode 100644 index 0000000000..18dd57830b --- /dev/null +++ b/e2e/solid-router/route-modules/.gitignore @@ -0,0 +1,2 @@ +# Generated during the e2e preparation/build, never checked in. +**/route*.gen*.ts diff --git a/e2e/solid-router/route-modules/e2e/scope-parity.spec.ts b/e2e/solid-router/route-modules/e2e/scope-parity.spec.ts new file mode 100644 index 0000000000..9df66d1848 --- /dev/null +++ b/e2e/solid-router/route-modules/e2e/scope-parity.spec.ts @@ -0,0 +1,177 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' + +for (const base of ['/orgs/7/settings', '/users/u1/settings']) { + test(`RouteApi and custom links resolve ${base}`, async ({ page }) => { + await page.goto(`${base}/profile`) + await expect( + page.getByRole('link', { name: 'API members' }), + ).toHaveAttribute('href', `${base}/members`) + await expect( + page.getByRole('link', { name: 'Custom members' }), + ).toHaveAttribute('href', `${base}/members`) + expect( + await page + .getByRole('link', { name: 'API members' }) + .getAttribute('_module'), + ).toBeNull() + expect( + await page + .getByRole('link', { name: 'Custom members' }) + .getAttribute('_module'), + ).toBeNull() + const hostId = base.split('/')[2]! + const hostParams = base.startsWith('/orgs/') + ? { orgId: hostId } + : base.startsWith('/people/') + ? { personId: hostId } + : { userId: hostId } + await expect(page.getByTestId('runtime-params')).toHaveText( + JSON.stringify(hostParams), + ) + await expect(page.getByText('PROFILE_MATCH', { exact: true })).toBeVisible() + await expect(page.getByText('MEMBERS_MATCH', { exact: true })).toHaveCount( + 0, + ) + await page.getByRole('link', { name: 'API members' }).click() + await expect(page.getByText('MEMBERS_PAGE')).toBeVisible() + await expect(page).toHaveURL(`${base}/members`) + }) + + test(`useLinkProps navigates within the document under ${base}`, async ({ + page, + }) => { + await page.goto(`${base}/profile`) + await expect( + page.getByRole('link', { name: 'Custom members' }), + ).toBeVisible() + const documentRequests: Array = [] + page.on('request', (request) => { + if ( + request.isNavigationRequest() && + request.frame() === page.mainFrame() + ) { + documentRequests.push(request.url()) + } + }) + await page.getByRole('link', { name: 'Custom members' }).click() + await expect(page.getByText('MEMBERS_PAGE')).toBeVisible() + await expect(page).toHaveURL(`${base}/members`) + expect(documentRequests).toEqual([]) + }) + + test(`RouteApi navigation resolves ${base}`, async ({ page }) => { + await page.goto(`${base}/profile`) + await page.getByRole('button', { name: 'Navigate members' }).click() + await expect(page.getByText('MEMBERS_PAGE')).toBeVisible() + await expect(page).toHaveURL(`${base}/members`) + }) + + test(`Navigate captures installation under ${base}`, async ({ page }) => { + await page.goto(`${base}/forward`) + await expect(page.getByText('MEMBERS_PAGE')).toBeVisible() + await expect(page).toHaveURL(`${base}/members`) + }) + + test(`component notFound reaches module boundary under ${base}`, async ({ + page, + }) => { + await page.goto(`${base}/missing`) + await expect(page.getByText('MODULE_NOT_FOUND')).toBeVisible() + }) + for (const button of ['Route up', 'Explicit from home']) { + test(`${button} uses the route origin under ${base}`, async ({ page }) => { + await page.goto(`${base}/profile`) + await page.getByRole('button', { name: button, exact: true }).click() + await expect(page).toHaveURL(base) + await expect( + page.getByRole('link', { name: 'Profile', exact: true }), + ).toHaveAttribute('href', `${base}/profile`) + }) + } + + test(`scoped router view builds and navigates under ${base}`, async ({ + page, + }) => { + await page.goto(`${base}/profile`) + await expect(page.getByTestId('scoped-href')).toHaveText(`${base}/members`) + await page.getByRole('button', { name: 'Router members' }).click() + await expect(page).toHaveURL(`${base}/members`) + const profile = page.getByRole('link', { name: 'Profile', exact: true }) + await expect(profile).toHaveAttribute('href', `${base}/profile`) + await profile.click() + await expect(page).toHaveURL(`${base}/profile`) + }) + + test(`Route.Link keeps the installation under ${base}`, async ({ page }) => { + await page.goto(`${base}/profile`) + const home = page.getByRole('link', { name: 'Route home', exact: true }) + await expect(home).toHaveAttribute('href', base) + await home.click() + await expect(page).toHaveURL(base) + await expect( + page.getByRole('link', { name: 'Profile', exact: true }), + ).toHaveAttribute('href', `${base}/profile`) + }) + + test(`scoped lifecycle redirects retain the installation under ${base}`, async ({ + page, + }) => { + await page.goto(`${base}/legacy`) + await expect(page).toHaveURL(`${base}/profile`) + await expect(page.getByText('PROFILE_MATCH', { exact: true })).toBeVisible() + }) + + test(`framework imports keep application coordinates inside ${base}`, async ({ + page, + }) => { + await page.goto(`${base}/profile`) + const host = page.getByRole('link', { name: 'Application host' }) + await expect(host).toHaveAttribute('href', '/orgs/9') + await host.click() + await expect(page).toHaveURL('/orgs/9') + }) +} + +test('module observers and router views follow real installation changes', async ({ + page, +}) => { + await page.goto('/orgs/7/settings/profile') + await expect(page.getByTestId('organization-profile')).toHaveText( + '@route-modules/solid-settings#orgSettings:/profile', + ) + await expect(page.getByTestId('scoped-href')).toHaveText( + '/orgs/7/settings/members', + ) + await page.getByRole('link', { name: 'API members' }).click() + await expect(page).toHaveURL('/orgs/7/settings/members') + await page.getByRole('link', { name: 'Switch to person' }).click() + await expect(page).toHaveURL('/users/u1/settings/profile') + await expect(page.getByTestId('organization-profile')).toHaveText('none') + await expect(page.getByTestId('scoped-href')).toHaveText( + '/users/u1/settings/members', + ) + await page.getByRole('link', { name: 'Switch to organization' }).click() + await expect(page).toHaveURL('/orgs/7/settings/profile') + await expect(page.getByRole('link', { name: 'API members' })).toHaveAttribute( + 'href', + '/orgs/7/settings/members', + ) + const readObserved = () => + page.evaluate( + () => + ( + window as Window & { + observedModuleMatches: Array + } + ).observedModuleMatches, + ) + await expect + .poll(readObserved) + .toContain('@route-modules/solid-settings#userSettings:/profile') + const observed = await readObserved() + expect(observed).toContain( + '@route-modules/solid-settings#orgSettings:/profile', + ) + expect(observed).not.toContain(undefined) +}) diff --git a/e2e/solid-router/route-modules/index.html b/e2e/solid-router/route-modules/index.html new file mode 100644 index 0000000000..5a5556330e --- /dev/null +++ b/e2e/solid-router/route-modules/index.html @@ -0,0 +1,11 @@ + + + + + Route module contracts + + +
+ + + diff --git a/e2e/solid-router/route-modules/package.json b/e2e/solid-router/route-modules/package.json new file mode 100644 index 0000000000..e04e7428a9 --- /dev/null +++ b/e2e/solid-router/route-modules/package.json @@ -0,0 +1,29 @@ +{ + "name": "tanstack-router-e2e-solid-route-modules", + "private": true, + "type": "module", + "scripts": { + "generate": "node scripts/prepare.mjs", + "build": "node scripts/prepare.mjs && vite build && tsc --noEmit && tsc -p packages/settings/tsconfig.json --noEmit", + "preview": "vite preview", + "dev:e2e": "node scripts/prepare.mjs && vite", + "test:e2e": "playwright test --project=chromium" + }, + "dependencies": { + "@route-modules/solid-settings": "workspace:*", + "@tanstack/solid-router": "workspace:^", + "solid-js": "^1.9.10" + }, + "devDependencies": { + "@playwright/test": "^1.61.0", + "@tanstack/router-cli": "workspace:^", + "@tanstack/router-core": "workspace:^", + "@tanstack/router-e2e-utils": "workspace:^", + "@tanstack/router-generator": "workspace:^", + "@tanstack/router-plugin": "workspace:^", + "@types/node": "catalog:", + "vite": "^8.0.14", + "vitest": "catalog:", + "vite-plugin-solid": "^2.11.11" + } +} diff --git a/e2e/solid-router/route-modules/packages/settings/package.json b/e2e/solid-router/route-modules/packages/settings/package.json new file mode 100644 index 0000000000..7fbb8ecee5 --- /dev/null +++ b/e2e/solid-router/route-modules/packages/settings/package.json @@ -0,0 +1,37 @@ +{ + "name": "@route-modules/solid-settings", + "private": true, + "type": "module", + "tanstack": { + "router": { + "module": true + } + }, + "exports": { + "./route-types": { + "types": "./.tanstack/types/src/routeContract.gen.d.ts" + }, + "./route-module": { + "types": "./.tanstack/types/src/routeModule.gen.d.ts", + "default": "./src/routeModule.gen.ts" + }, + "./scope": { + "types": "./.tanstack/types/src/routeScope.gen.d.ts", + "default": "./src/routeScope.gen.ts" + }, + "./package.json": "./package.json" + }, + "scripts": { + "generate": "tsr generate", + "emit-types": "tsc -p tsconfig.route-types.json", + "check": "tsc --noEmit" + }, + "dependencies": { + "@tanstack/solid-router": "workspace:^", + "solid-js": "^1.9.10" + }, + "devDependencies": { + "@tanstack/router-core": "workspace:^", + "@tanstack/router-cli": "workspace:^" + } +} diff --git a/e2e/solid-router/route-modules/packages/settings/src/routes/__root.tsx b/e2e/solid-router/route-modules/packages/settings/src/routes/__root.tsx new file mode 100644 index 0000000000..dd5fc7db8b --- /dev/null +++ b/e2e/solid-router/route-modules/packages/settings/src/routes/__root.tsx @@ -0,0 +1,8 @@ +import { Outlet } from '@tanstack/solid-router' +import { createModuleRoot } from '../routeScope.gen' +export const Route = createModuleRoot<{ + onProfileMatch?: (routeId: string | undefined) => void +}>()({ + component: () => , + notFoundComponent: () =>

MODULE_NOT_FOUND

, +}) diff --git a/e2e/solid-router/route-modules/packages/settings/src/routes/forward.tsx b/e2e/solid-router/route-modules/packages/settings/src/routes/forward.tsx new file mode 100644 index 0000000000..dfeb7629ae --- /dev/null +++ b/e2e/solid-router/route-modules/packages/settings/src/routes/forward.tsx @@ -0,0 +1,4 @@ +import { createFileRoute, Navigate } from '../routeScope.gen' +export const Route = createFileRoute('@route-modules/solid-settings:/forward')({ + component: () => , +}) diff --git a/e2e/solid-router/route-modules/packages/settings/src/routes/index.tsx b/e2e/solid-router/route-modules/packages/settings/src/routes/index.tsx new file mode 100644 index 0000000000..49521d0f90 --- /dev/null +++ b/e2e/solid-router/route-modules/packages/settings/src/routes/index.tsx @@ -0,0 +1,4 @@ +import { createFileRoute, Link } from '../routeScope.gen' +export const Route = createFileRoute('@route-modules/solid-settings:/')({ + component: () => Profile, +}) diff --git a/e2e/solid-router/route-modules/packages/settings/src/routes/legacy.tsx b/e2e/solid-router/route-modules/packages/settings/src/routes/legacy.tsx new file mode 100644 index 0000000000..03de793835 --- /dev/null +++ b/e2e/solid-router/route-modules/packages/settings/src/routes/legacy.tsx @@ -0,0 +1,6 @@ +import { createFileRoute, redirect } from '../routeScope.gen' +export const Route = createFileRoute('@route-modules/solid-settings:/legacy')({ + beforeLoad: () => { + throw redirect({ to: '/profile' }) + }, +}) diff --git a/e2e/solid-router/route-modules/packages/settings/src/routes/members.tsx b/e2e/solid-router/route-modules/packages/settings/src/routes/members.tsx new file mode 100644 index 0000000000..7675c942c8 --- /dev/null +++ b/e2e/solid-router/route-modules/packages/settings/src/routes/members.tsx @@ -0,0 +1,11 @@ +import { createFileRoute, getRouteApi } from '../routeScope.gen' +const ProfileLink = getRouteApi('@route-modules/solid-settings:/profile').Link +export const Route = createFileRoute('@route-modules/solid-settings:/members')({ + loader: () => ({ label: 'members' as const }), + component: () => ( + <> +

MEMBERS_PAGE

+ Profile + + ), +}) diff --git a/e2e/solid-router/route-modules/packages/settings/src/routes/missing.tsx b/e2e/solid-router/route-modules/packages/settings/src/routes/missing.tsx new file mode 100644 index 0000000000..cc90818852 --- /dev/null +++ b/e2e/solid-router/route-modules/packages/settings/src/routes/missing.tsx @@ -0,0 +1,6 @@ +import { createFileRoute, notFound } from '../routeScope.gen' +export const Route = createFileRoute('@route-modules/solid-settings:/missing')({ + component: () => { + throw notFound({ routeId: '@route-modules/solid-settings:' }) + }, +}) diff --git a/e2e/solid-router/route-modules/packages/settings/src/routes/profile.tsx b/e2e/solid-router/route-modules/packages/settings/src/routes/profile.tsx new file mode 100644 index 0000000000..352cf6b63f --- /dev/null +++ b/e2e/solid-router/route-modules/packages/settings/src/routes/profile.tsx @@ -0,0 +1,56 @@ +import { createRenderEffect } from 'solid-js' +import { Link as ApplicationLink } from '@tanstack/solid-router' +import { + createFileRoute, + getRouteApi, + MatchRoute, + useLinkProps, + useNavigate, + useRouter, +} from '../routeScope.gen' +const api = getRouteApi('@route-modules/solid-settings:/profile') +export const Route = createFileRoute('@route-modules/solid-settings:/profile')({ + component: () => { + const navigate = api.useNavigate() + const routeNavigate = Route.useNavigate() + const relativeNavigate = useNavigate({ from: '/profile' }) + const anchor = useLinkProps({ to: '/members' }) + const match = Route.useMatch({ shouldThrow: false }) + const scopedRouter = useRouter() + const observe = scopedRouter.options.context?.onProfileMatch + createRenderEffect(() => observe?.(match()?.routeId)) + return ( + <> + {match()?.routeId} + + {JSON.stringify(match()?.params)} + + API members + + Custom members + + PROFILE_MATCH + + + MEMBERS_MATCH + + + {scopedRouter.buildLocation({ to: '/members' }).href} + + + + + Route home + + Application host + + + ) + }, +}) diff --git a/e2e/solid-router/route-modules/packages/settings/src/routes/search.tsx b/e2e/solid-router/route-modules/packages/settings/src/routes/search.tsx new file mode 100644 index 0000000000..4b7cf73052 --- /dev/null +++ b/e2e/solid-router/route-modules/packages/settings/src/routes/search.tsx @@ -0,0 +1,4 @@ +import { createFileRoute } from '../routeScope.gen' +export const Route = createFileRoute('@route-modules/solid-settings:/search')({ + validateSearch: (search: { query: string }) => search, +}) diff --git a/e2e/solid-router/route-modules/packages/settings/tsconfig.json b/e2e/solid-router/route-modules/packages/settings/tsconfig.json new file mode 100644 index 0000000000..c77693ae51 --- /dev/null +++ b/e2e/solid-router/route-modules/packages/settings/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "preserve", + "jsxImportSource": "solid-js", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "skipLibCheck": true, + "noEmit": true, + "types": [] + }, + "include": ["src"] +} diff --git a/e2e/solid-router/route-modules/packages/settings/tsconfig.route-types.json b/e2e/solid-router/route-modules/packages/settings/tsconfig.route-types.json new file mode 100644 index 0000000000..0c9aec3caf --- /dev/null +++ b/e2e/solid-router/route-modules/packages/settings/tsconfig.route-types.json @@ -0,0 +1,13 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "emitDeclarationOnly": true, + "noEmitOnError": true, + "declarationMap": true, + "rootDir": ".", + "outDir": ".tanstack/types" + }, + "include": ["src"] +} diff --git a/e2e/solid-router/route-modules/packages/settings/tsr.config.json b/e2e/solid-router/route-modules/packages/settings/tsr.config.json new file mode 100644 index 0000000000..078264aa1f --- /dev/null +++ b/e2e/solid-router/route-modules/packages/settings/tsr.config.json @@ -0,0 +1,3 @@ +{ + "target": "solid" +} diff --git a/e2e/solid-router/route-modules/playwright.config.ts b/e2e/solid-router/route-modules/playwright.config.ts new file mode 100644 index 0000000000..56f2d789b1 --- /dev/null +++ b/e2e/solid-router/route-modules/playwright.config.ts @@ -0,0 +1,17 @@ +import { defineConfig, devices } from '@playwright/test' +import { appServerReady } from '@tanstack/router-e2e-utils' + +const PORT = Number(process.env.E2E_APP_PORT ?? 0) +export default defineConfig({ + testDir: './e2e', + workers: 1, + reporter: [['line']], + use: { baseURL: `http://localhost:${PORT}` }, + webServer: { + command: `pnpm build && pnpm preview --host 0.0.0.0 --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + }, + projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }], +}) diff --git a/e2e/solid-router/route-modules/scripts/prepare.mjs b/e2e/solid-router/route-modules/scripts/prepare.mjs new file mode 100644 index 0000000000..c7bad5c894 --- /dev/null +++ b/e2e/solid-router/route-modules/scripts/prepare.mjs @@ -0,0 +1,28 @@ +import { spawnSync } from 'node:child_process' +import { rmSync } from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { Generator, getConfig } from '@tanstack/router-generator' + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') +const provider = path.join(root, 'packages/settings') +await new Generator({ + config: getConfig({ disableLogging: true }, provider), + root: provider, +}).run() +rmSync(path.join(provider, '.tanstack/types'), { recursive: true, force: true }) +const result = spawnSync( + 'pnpm', + ['exec', 'tsc', '-p', 'tsconfig.route-types.json', '--pretty', 'false'], + { cwd: provider, stdio: 'inherit', shell: process.platform === 'win32' }, +) +if (result.error) { + throw result.error +} +if (result.status !== 0) { + process.exit(result.status ?? 1) +} +await new Generator({ + config: getConfig({ disableLogging: true }, root), + root, +}).run() diff --git a/e2e/solid-router/route-modules/src/main.tsx b/e2e/solid-router/route-modules/src/main.tsx new file mode 100644 index 0000000000..9f01709fdb --- /dev/null +++ b/e2e/solid-router/route-modules/src/main.tsx @@ -0,0 +1,19 @@ +import { render } from 'solid-js/web' +import { RouterProvider, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +const observedModuleMatches: Array = [] +Object.assign(window, { observedModuleMatches }) +const router = createRouter({ + routeTree, + context: { onProfileMatch: (routeId) => observedModuleMatches.push(routeId) }, +}) +declare module '@tanstack/solid-router' { + interface Register { + router: typeof router + } +} +render( + () => , + document.getElementById('app')!, +) diff --git a/e2e/solid-router/route-modules/src/routes/__root.tsx b/e2e/solid-router/route-modules/src/routes/__root.tsx new file mode 100644 index 0000000000..fbc4f195e7 --- /dev/null +++ b/e2e/solid-router/route-modules/src/routes/__root.tsx @@ -0,0 +1,29 @@ +import { createRootRouteWithContext, Outlet } from '@tanstack/solid-router' +import { orgSettings, userSettings } from '../routeScope.gen' +export const Route = createRootRouteWithContext<{ + onProfileMatch?: (routeId: string | undefined) => void +}>()({ + component: () => { + const organizationProfile = orgSettings.useMatch({ + from: '@route-modules/solid-settings:/profile', + shouldThrow: false, + }) + return ( + <> + + + + ) + }, + notFoundComponent: () =>

APP_NOT_FOUND

, +}) diff --git a/e2e/solid-router/route-modules/src/routes/orgs.$orgId.tsx b/e2e/solid-router/route-modules/src/routes/orgs.$orgId.tsx new file mode 100644 index 0000000000..8a19e7b731 --- /dev/null +++ b/e2e/solid-router/route-modules/src/routes/orgs.$orgId.tsx @@ -0,0 +1,2 @@ +import { createFileRoute } from '@tanstack/solid-router' +export const Route = createFileRoute('/orgs/$orgId')({}) diff --git a/e2e/solid-router/route-modules/src/routes/users.$userId.tsx b/e2e/solid-router/route-modules/src/routes/users.$userId.tsx new file mode 100644 index 0000000000..d7bcb5d927 --- /dev/null +++ b/e2e/solid-router/route-modules/src/routes/users.$userId.tsx @@ -0,0 +1,2 @@ +import { createFileRoute } from '@tanstack/solid-router' +export const Route = createFileRoute('/users/$userId')({}) diff --git a/e2e/solid-router/route-modules/tsconfig.json b/e2e/solid-router/route-modules/tsconfig.json new file mode 100644 index 0000000000..8d28f99d15 --- /dev/null +++ b/e2e/solid-router/route-modules/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "preserve", + "jsxImportSource": "solid-js", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "skipLibCheck": false, + "noEmit": true, + "types": ["vite/client"] + }, + "include": ["src", "type-tests"] +} diff --git a/e2e/solid-router/route-modules/tsr.config.json b/e2e/solid-router/route-modules/tsr.config.json new file mode 100644 index 0000000000..99b9443380 --- /dev/null +++ b/e2e/solid-router/route-modules/tsr.config.json @@ -0,0 +1,19 @@ +{ + "target": "solid", + "routeModules": { + "includes": [ + { + "module": "@route-modules/solid-settings", + "parent": "/orgs/$orgId", + "at": "/settings", + "as": "orgSettings" + }, + { + "module": "@route-modules/solid-settings", + "parent": "/users/$userId", + "at": "/settings", + "as": "userSettings" + } + ] + } +} diff --git a/e2e/solid-router/route-modules/type-tests/scope-contracts.tsx b/e2e/solid-router/route-modules/type-tests/scope-contracts.tsx new file mode 100644 index 0000000000..bae1999534 --- /dev/null +++ b/e2e/solid-router/route-modules/type-tests/scope-contracts.tsx @@ -0,0 +1,95 @@ +import { expectTypeOf, test } from 'vitest' +import { orgSettings, userSettings } from '../src/routeScope.gen' +import * as settings from '@route-modules/solid-settings/scope' + +test('reusable options preserve their installation through spreads and arrays', () => { + const user = userSettings.linkOptions({ + to: '/members', + params: () => ({ userId: 'u1', orgId: '7' }), + }) + expectTypeOf( + user._module, + ).toEqualTypeOf<'@route-modules/solid-settings#userSettings'>() + const same = + const { _module, ...neutral } = user + const compatiblePathsAndParams = + void compatiblePathsAndParams + void _module + // @ts-expect-error An explicit sibling installation is a conflicting scope. + const different = + // @ts-expect-error Rewrapping must not erase the conflicting scope. + orgSettings.linkOptions({ ...user }) + // @ts-expect-error Arrays preserve each entry's destination scope. + orgSettings.linkOptions([user]) + // @ts-expect-error Redirects enforce the same receiving-scope contract. + orgSettings.redirect(user) + orgSettings.linkOptions({ + to: '/members', + params: { orgId: '7' }, + // @ts-expect-error A mask cannot silently retarget another installation's options. + mask: user, + }) + // @ts-expect-error Hook defaults must retain and check a reusable scope stamp. + orgSettings.useNavigate({ ...user, from: '/profile' }) + // @ts-expect-error The callback checks the same destination stamp. + orgSettings.useNavigate()(user) + void same + void different +}) + +test('module-typed helper targets only known route IDs', () => { + settings.notFound({ routeId: '@route-modules/solid-settings:' }) + settings.notFound() + // @ts-expect-error This route is not declared by the module. + settings.notFound({ routeId: '@route-modules/solid-settings:/absent' }) +}) + +test('blocker locations describe the entire application and raw URL values', () => { + settings.useBlocker({ + shouldBlockFn: ({ current, next }) => { + expectTypeOf(current.routeId).toEqualTypeOf() + expectTypeOf(next.fullPath).toEqualTypeOf() + expectTypeOf(next.params).toEqualTypeOf< + Record + >() + expectTypeOf(next.search).toEqualTypeOf>() + return false + }, + }) +}) + +test('match selectors expose foreign data and the generated guard restores known data', () => { + settings.useMatch({ + strict: false, + select: (match) => { + expectTypeOf(match.context).toBeUnknown() + expectTypeOf(match.loaderData).toBeUnknown() + return match.routeId + }, + }) + settings.useMatches({ + select: (matches) => { + expectTypeOf(matches[0]!.context).toBeUnknown() + for (const match of matches) { + if ( + settings.isScopedMatch(match) && + match.localRouteId === '@route-modules/solid-settings:/members' + ) { + expectTypeOf(match.loaderData).toEqualTypeOf< + { label: 'members' } | undefined + >() + expectTypeOf(match.fullPath).toEqualTypeOf() + } + } + return matches.length + }, + }) +}) + +test('MatchRoute accepts only the scope paths in JSX', () => { + const own = + // @ts-expect-error This path is not a module route. + const foreign = + void own + void foreign +}) diff --git a/e2e/solid-router/route-modules/type-tests/validation-aliases.tsx b/e2e/solid-router/route-modules/type-tests/validation-aliases.tsx new file mode 100644 index 0000000000..db957af10e --- /dev/null +++ b/e2e/solid-router/route-modules/type-tests/validation-aliases.tsx @@ -0,0 +1,110 @@ +import { expectTypeOf, test } from 'vitest' +import type { orgSettings } from '../src/routeScope.gen' + +test('every generated validation alias preserves its namespace contract', () => { + type Options = { to: '/profile'; params: { orgId: '7' } } + const options: Options = { to: '/profile', params: { orgId: '7' } } + const link: orgSettings.ValidateLinkOptions = options + const links: orgSettings.ValidateLinkOptionsArray = [ + options, + ] + const navigate: orgSettings.ValidateNavigateOptions = options + const navigations: orgSettings.ValidateNavigateOptionsArray< + readonly [Options] + > = [options] + const redirect: orgSettings.ValidateRedirectOptions = options + const redirects: orgSettings.ValidateRedirectOptionsArray< + readonly [Options] + > = [options] + expectTypeOf().toMatchTypeOf() + expectTypeOf().toMatchTypeOf() + expectTypeOf().toMatchTypeOf() + expectTypeOf().toMatchTypeOf() + expectTypeOf().toMatchTypeOf() + expectTypeOf().toMatchTypeOf() + + const from: orgSettings.ValidateFromPath<'/profile'> = '/profile' + const to: orgSettings.ValidateToPath<'/profile'> = '/profile' + const search: orgSettings.ValidateSearch<'/search'> = { + search: { query: 'hello' }, + } + const params: orgSettings.ValidateParams<'/profile'> = { + params: { orgId: '7' }, + } + const id: orgSettings.ValidateId<'@route-modules/solid-settings:/profile'> = + '@route-modules/solid-settings:/profile' + const useSearch: orgSettings.ValidateUseSearchOptions<{ + from: '@route-modules/solid-settings:/profile' + }> = { from: '@route-modules/solid-settings:/profile' } + const useParams: orgSettings.ValidateUseParamsOptions<{ + from: '@route-modules/solid-settings:/profile' + }> = { from: '@route-modules/solid-settings:/profile' } + void [from, to, search, params, id, useSearch, useParams] + + const foreignPath = { + to: '/orgs/$orgId', + params: { orgId: '7' }, + } as const + const foreignPaths = [foreignPath] as const + const foreignOrigin = { from: '/orgs/$orgId' } as const + const wrongSearch = { search: { query: 42 } } + const wrongParams = { params: { userId: 'u1' } } + + // @ts-expect-error The validation alias is bound to this module's paths. + const invalidLink: orgSettings.ValidateLinkOptions = + foreignPath + // @ts-expect-error Tuple entries retain the generated scope. + const invalidLinks: orgSettings.ValidateLinkOptionsArray< + typeof foreignPaths + > = foreignPaths + // @ts-expect-error Navigation wrappers cannot escape the module paths. + const invalidNavigate: orgSettings.ValidateNavigateOptions< + typeof foreignPath + > = foreignPath + // @ts-expect-error Every navigation array entry is checked. + const invalidNavigations: orgSettings.ValidateNavigateOptionsArray< + typeof foreignPaths + > = foreignPaths + // @ts-expect-error Redirect wrappers retain module path validation. + const invalidRedirect: orgSettings.ValidateRedirectOptions< + typeof foreignPath + > = foreignPath + // @ts-expect-error Every redirect array entry is checked. + const invalidRedirects: orgSettings.ValidateRedirectOptionsArray< + typeof foreignPaths + > = foreignPaths + // @ts-expect-error A route origin must be a path in the module. + const invalidFrom: orgSettings.ValidateFromPath<'/profile'> = '/orgs/$orgId' + // @ts-expect-error A destination must be a path in the module. + const invalidTo: orgSettings.ValidateToPath<'/profile'> = '/orgs/$orgId' + // @ts-expect-error Search validation follows the generated route schema. + const invalidSearch: orgSettings.ValidateSearch<'/search'> = wrongSearch + // @ts-expect-error The named installation requires its own host parameter. + const invalidParams: orgSettings.ValidateParams<'/profile'> = wrongParams + // @ts-expect-error A foreign route ID is not a module route. + const invalidId: orgSettings.ValidateId<'@route-modules/solid-settings:/profile'> = + '/orgs/$orgId' + // @ts-expect-error Search selectors must name a route in this module. + const invalidUseSearch: orgSettings.ValidateUseSearchOptions< + typeof foreignOrigin + > = foreignOrigin + // @ts-expect-error Parameter selectors must name a route in this module. + const invalidUseParams: orgSettings.ValidateUseParamsOptions< + typeof foreignOrigin + > = foreignOrigin + void [ + invalidLink, + invalidLinks, + invalidNavigate, + invalidNavigations, + invalidRedirect, + invalidRedirects, + invalidFrom, + invalidTo, + invalidSearch, + invalidParams, + invalidId, + invalidUseSearch, + invalidUseParams, + ] +}) diff --git a/e2e/solid-router/route-modules/vite.config.ts b/e2e/solid-router/route-modules/vite.config.ts new file mode 100644 index 0000000000..f966227153 --- /dev/null +++ b/e2e/solid-router/route-modules/vite.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from 'vite' +import solid from 'vite-plugin-solid' +import { tanstackRouter } from '@tanstack/router-plugin/vite' + +export default defineConfig({ + plugins: [ + tanstackRouter({ target: 'solid', autoCodeSplitting: true }), + solid(), + ], +}) diff --git a/e2e/vue-router/route-modules/.gitignore b/e2e/vue-router/route-modules/.gitignore new file mode 100644 index 0000000000..18dd57830b --- /dev/null +++ b/e2e/vue-router/route-modules/.gitignore @@ -0,0 +1,2 @@ +# Generated during the e2e preparation/build, never checked in. +**/route*.gen*.ts diff --git a/e2e/vue-router/route-modules/e2e/scope-parity.spec.ts b/e2e/vue-router/route-modules/e2e/scope-parity.spec.ts new file mode 100644 index 0000000000..2690e77001 --- /dev/null +++ b/e2e/vue-router/route-modules/e2e/scope-parity.spec.ts @@ -0,0 +1,175 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' + +for (const base of ['/orgs/7/settings', '/users/u1/settings']) { + test(`RouteApi and custom links resolve ${base}`, async ({ page }) => { + await page.goto(`${base}/profile`) + await expect( + page.getByRole('link', { name: 'API members' }), + ).toHaveAttribute('href', `${base}/members`) + await expect( + page.getByRole('link', { name: 'Custom members' }), + ).toHaveAttribute('href', `${base}/members`) + expect( + await page + .getByRole('link', { name: 'API members' }) + .getAttribute('_module'), + ).toBeNull() + expect( + await page + .getByRole('link', { name: 'Custom members' }) + .getAttribute('_module'), + ).toBeNull() + const hostId = base.split('/')[2]! + const hostParams = base.startsWith('/orgs/') + ? { orgId: hostId } + : base.startsWith('/people/') + ? { personId: hostId } + : { userId: hostId } + await expect(page.getByTestId('runtime-params')).toHaveText( + JSON.stringify(hostParams), + ) + await expect(page.getByText('PROFILE_MATCH', { exact: true })).toBeVisible() + await expect(page.getByText('MEMBERS_MATCH', { exact: true })).toHaveCount( + 0, + ) + await page.getByRole('link', { name: 'API members' }).click() + await expect(page.getByText('MEMBERS_PAGE')).toBeVisible() + await expect(page).toHaveURL(`${base}/members`) + }) + + test(`useLinkProps navigates within the document under ${base}`, async ({ + page, + }) => { + await page.goto(`${base}/profile`) + await expect( + page.getByRole('link', { name: 'Custom members' }), + ).toBeVisible() + const documentRequests: Array = [] + page.on('request', (request) => { + if ( + request.isNavigationRequest() && + request.frame() === page.mainFrame() + ) { + documentRequests.push(request.url()) + } + }) + await page.getByRole('link', { name: 'Custom members' }).click() + await expect(page.getByText('MEMBERS_PAGE')).toBeVisible() + await expect(page).toHaveURL(`${base}/members`) + expect(documentRequests).toEqual([]) + }) + + test(`RouteApi navigation resolves ${base}`, async ({ page }) => { + await page.goto(`${base}/profile`) + await page.getByRole('button', { name: 'Navigate members' }).click() + await expect(page.getByText('MEMBERS_PAGE')).toBeVisible() + await expect(page).toHaveURL(`${base}/members`) + }) + + test(`Navigate captures installation under ${base}`, async ({ page }) => { + await page.goto(`${base}/forward`) + await expect(page.getByText('MEMBERS_PAGE')).toBeVisible() + await expect(page).toHaveURL(`${base}/members`) + }) + + test(`component notFound reaches module boundary under ${base}`, async ({ + page, + }) => { + await page.goto(`${base}/missing`) + await expect(page.getByText('MODULE_NOT_FOUND')).toBeVisible() + }) + for (const button of ['Route up', 'Explicit from home']) { + test(`${button} uses the route origin under ${base}`, async ({ page }) => { + await page.goto(`${base}/profile`) + await page.getByRole('button', { name: button, exact: true }).click() + await expect(page).toHaveURL(base) + await expect( + page.getByRole('link', { name: 'Profile', exact: true }), + ).toHaveAttribute('href', `${base}/profile`) + }) + } + + test(`scoped router view builds and navigates under ${base}`, async ({ + page, + }) => { + await page.goto(`${base}/profile`) + await expect(page.getByTestId('scoped-href')).toHaveText(`${base}/members`) + await page.getByRole('button', { name: 'Router members' }).click() + await expect(page).toHaveURL(`${base}/members`) + const profile = page.getByRole('link', { name: 'Profile', exact: true }) + await expect(profile).toHaveAttribute('href', `${base}/profile`) + await profile.click() + await expect(page).toHaveURL(`${base}/profile`) + }) + + test(`Route.Link keeps the installation under ${base}`, async ({ page }) => { + await page.goto(`${base}/profile`) + const home = page.getByRole('link', { name: 'Route home', exact: true }) + await expect(home).toHaveAttribute('href', base) + await home.click() + await expect(page).toHaveURL(base) + await expect( + page.getByRole('link', { name: 'Profile', exact: true }), + ).toHaveAttribute('href', `${base}/profile`) + }) + + test(`scoped lifecycle redirects retain the installation under ${base}`, async ({ + page, + }) => { + await page.goto(`${base}/legacy`) + await expect(page).toHaveURL(`${base}/profile`) + await expect(page.getByText('PROFILE_MATCH', { exact: true })).toBeVisible() + }) + + test(`framework imports keep application coordinates inside ${base}`, async ({ + page, + }) => { + await page.goto(`${base}/profile`) + const host = page.getByRole('link', { name: 'Application host' }) + await expect(host).toHaveAttribute('href', '/orgs/9') + await host.click() + await expect(page).toHaveURL('/orgs/9') + }) +} + +test('module observers and router views follow real installation changes', async ({ + page, +}) => { + await page.goto('/orgs/7/settings/profile') + await expect(page.getByTestId('organization-profile')).toHaveText( + '@route-modules/vue-settings#orgSettings:/profile', + ) + await expect(page.getByTestId('scoped-href')).toHaveText( + '/orgs/7/settings/members', + ) + await page.getByRole('link', { name: 'API members' }).click() + await expect(page).toHaveURL('/orgs/7/settings/members') + await page.getByRole('link', { name: 'Switch to person' }).click() + await expect(page).toHaveURL('/users/u1/settings/profile') + await expect(page.getByTestId('organization-profile')).toHaveText('none') + await expect(page.getByTestId('scoped-href')).toHaveText( + '/users/u1/settings/members', + ) + await page.getByRole('link', { name: 'Switch to organization' }).click() + await expect(page).toHaveURL('/orgs/7/settings/profile') + await expect(page.getByRole('link', { name: 'API members' })).toHaveAttribute( + 'href', + '/orgs/7/settings/members', + ) + const readObserved = () => + page.evaluate( + () => + ( + window as Window & { + observedModuleMatches: Array + } + ).observedModuleMatches, + ) + await expect + .poll(readObserved) + .toContain('@route-modules/vue-settings#userSettings:/profile') + const observed = await readObserved() + expect(observed).toContain('@route-modules/vue-settings#orgSettings:/profile') + expect(observed).not.toContain(undefined) +}) diff --git a/e2e/vue-router/route-modules/index.html b/e2e/vue-router/route-modules/index.html new file mode 100644 index 0000000000..5a5556330e --- /dev/null +++ b/e2e/vue-router/route-modules/index.html @@ -0,0 +1,11 @@ + + + + + Route module contracts + + +
+ + + diff --git a/e2e/vue-router/route-modules/package.json b/e2e/vue-router/route-modules/package.json new file mode 100644 index 0000000000..ad2a94a537 --- /dev/null +++ b/e2e/vue-router/route-modules/package.json @@ -0,0 +1,29 @@ +{ + "name": "tanstack-router-e2e-vue-route-modules", + "private": true, + "type": "module", + "scripts": { + "generate": "node scripts/prepare.mjs", + "build": "node scripts/prepare.mjs && vite build && tsc --noEmit && tsc -p packages/settings/tsconfig.json --noEmit", + "preview": "vite preview", + "dev:e2e": "node scripts/prepare.mjs && vite", + "test:e2e": "playwright test --project=chromium" + }, + "dependencies": { + "@route-modules/vue-settings": "workspace:*", + "@tanstack/vue-router": "workspace:^", + "vue": "^3.5.16" + }, + "devDependencies": { + "@playwright/test": "^1.61.0", + "@tanstack/router-cli": "workspace:^", + "@tanstack/router-core": "workspace:^", + "@tanstack/router-e2e-utils": "workspace:^", + "@tanstack/router-generator": "workspace:^", + "@tanstack/router-plugin": "workspace:^", + "@types/node": "catalog:", + "vite": "^8.0.14", + "vitest": "catalog:", + "@vitejs/plugin-vue-jsx": "^5.1.5" + } +} diff --git a/e2e/vue-router/route-modules/packages/settings/package.json b/e2e/vue-router/route-modules/packages/settings/package.json new file mode 100644 index 0000000000..10eaf438b0 --- /dev/null +++ b/e2e/vue-router/route-modules/packages/settings/package.json @@ -0,0 +1,37 @@ +{ + "name": "@route-modules/vue-settings", + "private": true, + "type": "module", + "tanstack": { + "router": { + "module": true + } + }, + "exports": { + "./route-types": { + "types": "./.tanstack/types/src/routeContract.gen.d.ts" + }, + "./route-module": { + "types": "./.tanstack/types/src/routeModule.gen.d.ts", + "default": "./src/routeModule.gen.ts" + }, + "./scope": { + "types": "./.tanstack/types/src/routeScope.gen.d.ts", + "default": "./src/routeScope.gen.ts" + }, + "./package.json": "./package.json" + }, + "scripts": { + "generate": "tsr generate", + "emit-types": "tsc -p tsconfig.route-types.json", + "check": "tsc --noEmit" + }, + "dependencies": { + "@tanstack/vue-router": "workspace:^", + "vue": "^3.5.16" + }, + "devDependencies": { + "@tanstack/router-core": "workspace:^", + "@tanstack/router-cli": "workspace:^" + } +} diff --git a/e2e/vue-router/route-modules/packages/settings/src/routes/__root.tsx b/e2e/vue-router/route-modules/packages/settings/src/routes/__root.tsx new file mode 100644 index 0000000000..818a747831 --- /dev/null +++ b/e2e/vue-router/route-modules/packages/settings/src/routes/__root.tsx @@ -0,0 +1,9 @@ +import * as Vue from 'vue' +import { Outlet } from '@tanstack/vue-router' +import { createModuleRoot } from '../routeScope.gen' +export const Route = createModuleRoot<{ + onProfileMatch?: (routeId: string | undefined) => void +}>()({ + component: () => , + notFoundComponent: () =>

MODULE_NOT_FOUND

, +}) diff --git a/e2e/vue-router/route-modules/packages/settings/src/routes/forward.tsx b/e2e/vue-router/route-modules/packages/settings/src/routes/forward.tsx new file mode 100644 index 0000000000..a01bf2b8b6 --- /dev/null +++ b/e2e/vue-router/route-modules/packages/settings/src/routes/forward.tsx @@ -0,0 +1,5 @@ +import * as Vue from 'vue' +import { createFileRoute, Navigate } from '../routeScope.gen' +export const Route = createFileRoute('@route-modules/vue-settings:/forward')({ + component: () => , +}) diff --git a/e2e/vue-router/route-modules/packages/settings/src/routes/index.tsx b/e2e/vue-router/route-modules/packages/settings/src/routes/index.tsx new file mode 100644 index 0000000000..55697a39de --- /dev/null +++ b/e2e/vue-router/route-modules/packages/settings/src/routes/index.tsx @@ -0,0 +1,4 @@ +import { createFileRoute, Link } from '../routeScope.gen' +export const Route = createFileRoute('@route-modules/vue-settings:/')({ + component: () => Profile, +}) diff --git a/e2e/vue-router/route-modules/packages/settings/src/routes/legacy.tsx b/e2e/vue-router/route-modules/packages/settings/src/routes/legacy.tsx new file mode 100644 index 0000000000..a83a5cd897 --- /dev/null +++ b/e2e/vue-router/route-modules/packages/settings/src/routes/legacy.tsx @@ -0,0 +1,6 @@ +import { createFileRoute, redirect } from '../routeScope.gen' +export const Route = createFileRoute('@route-modules/vue-settings:/legacy')({ + beforeLoad: () => { + throw redirect({ to: '/profile' }) + }, +}) diff --git a/e2e/vue-router/route-modules/packages/settings/src/routes/members.tsx b/e2e/vue-router/route-modules/packages/settings/src/routes/members.tsx new file mode 100644 index 0000000000..a71c4fb4bf --- /dev/null +++ b/e2e/vue-router/route-modules/packages/settings/src/routes/members.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute, getRouteApi } from '../routeScope.gen' +const ProfileLink = getRouteApi('@route-modules/vue-settings:/profile').Link +export const Route = createFileRoute('@route-modules/vue-settings:/members')({ + loader: () => ({ label: 'members' as const }), + component: () => ( + <> +

MEMBERS_PAGE

+ Profile + + ), +}) diff --git a/e2e/vue-router/route-modules/packages/settings/src/routes/missing.tsx b/e2e/vue-router/route-modules/packages/settings/src/routes/missing.tsx new file mode 100644 index 0000000000..eb114f3dc1 --- /dev/null +++ b/e2e/vue-router/route-modules/packages/settings/src/routes/missing.tsx @@ -0,0 +1,6 @@ +import { createFileRoute, notFound } from '../routeScope.gen' +export const Route = createFileRoute('@route-modules/vue-settings:/missing')({ + component: () => { + throw notFound({ routeId: '@route-modules/vue-settings:' }) + }, +}) diff --git a/e2e/vue-router/route-modules/packages/settings/src/routes/profile.tsx b/e2e/vue-router/route-modules/packages/settings/src/routes/profile.tsx new file mode 100644 index 0000000000..b3cb158126 --- /dev/null +++ b/e2e/vue-router/route-modules/packages/settings/src/routes/profile.tsx @@ -0,0 +1,58 @@ +import * as Vue from 'vue' +import { Link as ApplicationLink } from '@tanstack/vue-router' +import { + createFileRoute, + getRouteApi, + MatchRoute, + useLinkProps, + useNavigate, + useRouter, +} from '../routeScope.gen' +const api = getRouteApi('@route-modules/vue-settings:/profile') +export const Route = createFileRoute('@route-modules/vue-settings:/profile')({ + component: Vue.defineComponent({ + setup() { + const navigate = api.useNavigate() + const routeNavigate = Route.useNavigate() + const relativeNavigate = useNavigate({ from: '/profile' }) + const anchor = useLinkProps({ to: '/members' }) + const match = Route.useMatch({ shouldThrow: false }) + const scopedRouter = useRouter() + const observe = scopedRouter.options.context?.onProfileMatch + Vue.watchEffect(() => observe?.(match.value?.routeId), { flush: 'sync' }) + return () => ( + <> + {match.value?.routeId} + + {JSON.stringify(match.value?.params)} + + API members + + Custom members + + PROFILE_MATCH + + + MEMBERS_MATCH + + + {scopedRouter.buildLocation({ to: '/members' }).href} + + + + + Route home + + Application host + + + ) + }, + }), +}) diff --git a/e2e/vue-router/route-modules/packages/settings/src/routes/search.tsx b/e2e/vue-router/route-modules/packages/settings/src/routes/search.tsx new file mode 100644 index 0000000000..ce7240ca62 --- /dev/null +++ b/e2e/vue-router/route-modules/packages/settings/src/routes/search.tsx @@ -0,0 +1,4 @@ +import { createFileRoute } from '../routeScope.gen' +export const Route = createFileRoute('@route-modules/vue-settings:/search')({ + validateSearch: (search: { query: string }) => search, +}) diff --git a/e2e/vue-router/route-modules/packages/settings/tsconfig.json b/e2e/vue-router/route-modules/packages/settings/tsconfig.json new file mode 100644 index 0000000000..03e4f22814 --- /dev/null +++ b/e2e/vue-router/route-modules/packages/settings/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "preserve", + "jsxImportSource": "vue", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "skipLibCheck": true, + "noEmit": true, + "types": [] + }, + "include": ["src"] +} diff --git a/e2e/vue-router/route-modules/packages/settings/tsconfig.route-types.json b/e2e/vue-router/route-modules/packages/settings/tsconfig.route-types.json new file mode 100644 index 0000000000..0c9aec3caf --- /dev/null +++ b/e2e/vue-router/route-modules/packages/settings/tsconfig.route-types.json @@ -0,0 +1,13 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "declaration": true, + "emitDeclarationOnly": true, + "noEmitOnError": true, + "declarationMap": true, + "rootDir": ".", + "outDir": ".tanstack/types" + }, + "include": ["src"] +} diff --git a/e2e/vue-router/route-modules/packages/settings/tsr.config.json b/e2e/vue-router/route-modules/packages/settings/tsr.config.json new file mode 100644 index 0000000000..e026c80dc2 --- /dev/null +++ b/e2e/vue-router/route-modules/packages/settings/tsr.config.json @@ -0,0 +1,3 @@ +{ + "target": "vue" +} diff --git a/e2e/vue-router/route-modules/playwright.config.ts b/e2e/vue-router/route-modules/playwright.config.ts new file mode 100644 index 0000000000..56f2d789b1 --- /dev/null +++ b/e2e/vue-router/route-modules/playwright.config.ts @@ -0,0 +1,17 @@ +import { defineConfig, devices } from '@playwright/test' +import { appServerReady } from '@tanstack/router-e2e-utils' + +const PORT = Number(process.env.E2E_APP_PORT ?? 0) +export default defineConfig({ + testDir: './e2e', + workers: 1, + reporter: [['line']], + use: { baseURL: `http://localhost:${PORT}` }, + webServer: { + command: `pnpm build && pnpm preview --host 0.0.0.0 --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + }, + projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }], +}) diff --git a/e2e/vue-router/route-modules/scripts/prepare.mjs b/e2e/vue-router/route-modules/scripts/prepare.mjs new file mode 100644 index 0000000000..c7bad5c894 --- /dev/null +++ b/e2e/vue-router/route-modules/scripts/prepare.mjs @@ -0,0 +1,28 @@ +import { spawnSync } from 'node:child_process' +import { rmSync } from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { Generator, getConfig } from '@tanstack/router-generator' + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') +const provider = path.join(root, 'packages/settings') +await new Generator({ + config: getConfig({ disableLogging: true }, provider), + root: provider, +}).run() +rmSync(path.join(provider, '.tanstack/types'), { recursive: true, force: true }) +const result = spawnSync( + 'pnpm', + ['exec', 'tsc', '-p', 'tsconfig.route-types.json', '--pretty', 'false'], + { cwd: provider, stdio: 'inherit', shell: process.platform === 'win32' }, +) +if (result.error) { + throw result.error +} +if (result.status !== 0) { + process.exit(result.status ?? 1) +} +await new Generator({ + config: getConfig({ disableLogging: true }, root), + root, +}).run() diff --git a/e2e/vue-router/route-modules/src/main.tsx b/e2e/vue-router/route-modules/src/main.tsx new file mode 100644 index 0000000000..239fc24f38 --- /dev/null +++ b/e2e/vue-router/route-modules/src/main.tsx @@ -0,0 +1,16 @@ +import { createApp, h } from 'vue' +import { RouterProvider, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +const observedModuleMatches: Array = [] +Object.assign(window, { observedModuleMatches }) +const router = createRouter({ + routeTree, + context: { onProfileMatch: (routeId) => observedModuleMatches.push(routeId) }, +}) +declare module '@tanstack/vue-router' { + interface Register { + router: typeof router + } +} +createApp({ setup: () => () => h(RouterProvider, { router }) }).mount('#app') diff --git a/e2e/vue-router/route-modules/src/routes/__root.tsx b/e2e/vue-router/route-modules/src/routes/__root.tsx new file mode 100644 index 0000000000..567c442bb3 --- /dev/null +++ b/e2e/vue-router/route-modules/src/routes/__root.tsx @@ -0,0 +1,32 @@ +import * as Vue from 'vue' +import { createRootRouteWithContext, Outlet } from '@tanstack/vue-router' +import { orgSettings, userSettings } from '../routeScope.gen' +export const Route = createRootRouteWithContext<{ + onProfileMatch?: (routeId: string | undefined) => void +}>()({ + component: Vue.defineComponent({ + setup() { + const organizationProfile = orgSettings.useMatch({ + from: '@route-modules/vue-settings:/profile', + shouldThrow: false, + }) + return () => ( + <> + + + + ) + }, + }), + notFoundComponent: () =>

APP_NOT_FOUND

, +}) diff --git a/e2e/vue-router/route-modules/src/routes/orgs.$orgId.tsx b/e2e/vue-router/route-modules/src/routes/orgs.$orgId.tsx new file mode 100644 index 0000000000..8612ff63dc --- /dev/null +++ b/e2e/vue-router/route-modules/src/routes/orgs.$orgId.tsx @@ -0,0 +1,2 @@ +import { createFileRoute } from '@tanstack/vue-router' +export const Route = createFileRoute('/orgs/$orgId')({}) diff --git a/e2e/vue-router/route-modules/src/routes/users.$userId.tsx b/e2e/vue-router/route-modules/src/routes/users.$userId.tsx new file mode 100644 index 0000000000..591ed91014 --- /dev/null +++ b/e2e/vue-router/route-modules/src/routes/users.$userId.tsx @@ -0,0 +1,2 @@ +import { createFileRoute } from '@tanstack/vue-router' +export const Route = createFileRoute('/users/$userId')({}) diff --git a/e2e/vue-router/route-modules/tsconfig.json b/e2e/vue-router/route-modules/tsconfig.json new file mode 100644 index 0000000000..9e43460be8 --- /dev/null +++ b/e2e/vue-router/route-modules/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "preserve", + "jsxImportSource": "vue", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "skipLibCheck": false, + "noEmit": true, + "types": ["vite/client"] + }, + "include": ["src", "type-tests"] +} diff --git a/e2e/vue-router/route-modules/tsr.config.json b/e2e/vue-router/route-modules/tsr.config.json new file mode 100644 index 0000000000..4c17a3b082 --- /dev/null +++ b/e2e/vue-router/route-modules/tsr.config.json @@ -0,0 +1,19 @@ +{ + "target": "vue", + "routeModules": { + "includes": [ + { + "module": "@route-modules/vue-settings", + "parent": "/orgs/$orgId", + "at": "/settings", + "as": "orgSettings" + }, + { + "module": "@route-modules/vue-settings", + "parent": "/users/$userId", + "at": "/settings", + "as": "userSettings" + } + ] + } +} diff --git a/e2e/vue-router/route-modules/type-tests/scope-contracts.tsx b/e2e/vue-router/route-modules/type-tests/scope-contracts.tsx new file mode 100644 index 0000000000..a32b8448a8 --- /dev/null +++ b/e2e/vue-router/route-modules/type-tests/scope-contracts.tsx @@ -0,0 +1,95 @@ +import { expectTypeOf, test } from 'vitest' +import { orgSettings, userSettings } from '../src/routeScope.gen' +import * as settings from '@route-modules/vue-settings/scope' + +test('reusable options preserve their installation through spreads and arrays', () => { + const user = userSettings.linkOptions({ + to: '/members', + params: () => ({ userId: 'u1', orgId: '7' }), + }) + expectTypeOf( + user._module, + ).toEqualTypeOf<'@route-modules/vue-settings#userSettings'>() + const same = + const { _module, ...neutral } = user + const compatiblePathsAndParams = + void compatiblePathsAndParams + void _module + // @ts-expect-error An explicit sibling installation is a conflicting scope. + const different = + // @ts-expect-error Rewrapping must not erase the conflicting scope. + orgSettings.linkOptions({ ...user }) + // @ts-expect-error Arrays preserve each entry's destination scope. + orgSettings.linkOptions([user]) + // @ts-expect-error Redirects enforce the same receiving-scope contract. + orgSettings.redirect(user) + orgSettings.linkOptions({ + to: '/members', + params: { orgId: '7' }, + // @ts-expect-error A mask cannot silently retarget another installation's options. + mask: user, + }) + // @ts-expect-error Hook defaults must retain and check a reusable scope stamp. + orgSettings.useNavigate({ ...user, from: '/profile' }) + // @ts-expect-error The callback checks the same destination stamp. + orgSettings.useNavigate()(user) + void same + void different +}) + +test('module-typed helper targets only known route IDs', () => { + settings.notFound({ routeId: '@route-modules/vue-settings:' }) + settings.notFound() + // @ts-expect-error This route is not declared by the module. + settings.notFound({ routeId: '@route-modules/vue-settings:/absent' }) +}) + +test('blocker locations describe the entire application and raw URL values', () => { + settings.useBlocker({ + shouldBlockFn: ({ current, next }) => { + expectTypeOf(current.routeId).toEqualTypeOf() + expectTypeOf(next.fullPath).toEqualTypeOf() + expectTypeOf(next.params).toEqualTypeOf< + Record + >() + expectTypeOf(next.search).toEqualTypeOf>() + return false + }, + }) +}) + +test('match selectors expose foreign data and the generated guard restores known data', () => { + settings.useMatch({ + strict: false, + select: (match) => { + expectTypeOf(match.context).toBeUnknown() + expectTypeOf(match.loaderData).toBeUnknown() + return match.routeId + }, + }) + settings.useMatches({ + select: (matches) => { + expectTypeOf(matches[0]!.context).toBeUnknown() + for (const match of matches) { + if ( + settings.isScopedMatch(match) && + match.localRouteId === '@route-modules/vue-settings:/members' + ) { + expectTypeOf(match.loaderData).toEqualTypeOf< + { label: 'members' } | undefined + >() + expectTypeOf(match.fullPath).toEqualTypeOf() + } + } + return matches.length + }, + }) +}) + +test('MatchRoute accepts only the scope paths in JSX', () => { + const own = + // @ts-expect-error This path is not a module route. + const foreign = + void own + void foreign +}) diff --git a/e2e/vue-router/route-modules/type-tests/validation-aliases.tsx b/e2e/vue-router/route-modules/type-tests/validation-aliases.tsx new file mode 100644 index 0000000000..3952934073 --- /dev/null +++ b/e2e/vue-router/route-modules/type-tests/validation-aliases.tsx @@ -0,0 +1,110 @@ +import { expectTypeOf, test } from 'vitest' +import type { orgSettings } from '../src/routeScope.gen' + +test('every generated validation alias preserves its namespace contract', () => { + type Options = { to: '/profile'; params: { orgId: '7' } } + const options: Options = { to: '/profile', params: { orgId: '7' } } + const link: orgSettings.ValidateLinkOptions = options + const links: orgSettings.ValidateLinkOptionsArray = [ + options, + ] + const navigate: orgSettings.ValidateNavigateOptions = options + const navigations: orgSettings.ValidateNavigateOptionsArray< + readonly [Options] + > = [options] + const redirect: orgSettings.ValidateRedirectOptions = options + const redirects: orgSettings.ValidateRedirectOptionsArray< + readonly [Options] + > = [options] + expectTypeOf().toMatchTypeOf() + expectTypeOf().toMatchTypeOf() + expectTypeOf().toMatchTypeOf() + expectTypeOf().toMatchTypeOf() + expectTypeOf().toMatchTypeOf() + expectTypeOf().toMatchTypeOf() + + const from: orgSettings.ValidateFromPath<'/profile'> = '/profile' + const to: orgSettings.ValidateToPath<'/profile'> = '/profile' + const search: orgSettings.ValidateSearch<'/search'> = { + search: { query: 'hello' }, + } + const params: orgSettings.ValidateParams<'/profile'> = { + params: { orgId: '7' }, + } + const id: orgSettings.ValidateId<'@route-modules/vue-settings:/profile'> = + '@route-modules/vue-settings:/profile' + const useSearch: orgSettings.ValidateUseSearchOptions<{ + from: '@route-modules/vue-settings:/profile' + }> = { from: '@route-modules/vue-settings:/profile' } + const useParams: orgSettings.ValidateUseParamsOptions<{ + from: '@route-modules/vue-settings:/profile' + }> = { from: '@route-modules/vue-settings:/profile' } + void [from, to, search, params, id, useSearch, useParams] + + const foreignPath = { + to: '/orgs/$orgId', + params: { orgId: '7' }, + } as const + const foreignPaths = [foreignPath] as const + const foreignOrigin = { from: '/orgs/$orgId' } as const + const wrongSearch = { search: { query: 42 } } + const wrongParams = { params: { userId: 'u1' } } + + // @ts-expect-error The validation alias is bound to this module's paths. + const invalidLink: orgSettings.ValidateLinkOptions = + foreignPath + // @ts-expect-error Tuple entries retain the generated scope. + const invalidLinks: orgSettings.ValidateLinkOptionsArray< + typeof foreignPaths + > = foreignPaths + // @ts-expect-error Navigation wrappers cannot escape the module paths. + const invalidNavigate: orgSettings.ValidateNavigateOptions< + typeof foreignPath + > = foreignPath + // @ts-expect-error Every navigation array entry is checked. + const invalidNavigations: orgSettings.ValidateNavigateOptionsArray< + typeof foreignPaths + > = foreignPaths + // @ts-expect-error Redirect wrappers retain module path validation. + const invalidRedirect: orgSettings.ValidateRedirectOptions< + typeof foreignPath + > = foreignPath + // @ts-expect-error Every redirect array entry is checked. + const invalidRedirects: orgSettings.ValidateRedirectOptionsArray< + typeof foreignPaths + > = foreignPaths + // @ts-expect-error A route origin must be a path in the module. + const invalidFrom: orgSettings.ValidateFromPath<'/profile'> = '/orgs/$orgId' + // @ts-expect-error A destination must be a path in the module. + const invalidTo: orgSettings.ValidateToPath<'/profile'> = '/orgs/$orgId' + // @ts-expect-error Search validation follows the generated route schema. + const invalidSearch: orgSettings.ValidateSearch<'/search'> = wrongSearch + // @ts-expect-error The named installation requires its own host parameter. + const invalidParams: orgSettings.ValidateParams<'/profile'> = wrongParams + // @ts-expect-error A foreign route ID is not a module route. + const invalidId: orgSettings.ValidateId<'@route-modules/vue-settings:/profile'> = + '/orgs/$orgId' + // @ts-expect-error Search selectors must name a route in this module. + const invalidUseSearch: orgSettings.ValidateUseSearchOptions< + typeof foreignOrigin + > = foreignOrigin + // @ts-expect-error Parameter selectors must name a route in this module. + const invalidUseParams: orgSettings.ValidateUseParamsOptions< + typeof foreignOrigin + > = foreignOrigin + void [ + invalidLink, + invalidLinks, + invalidNavigate, + invalidNavigations, + invalidRedirect, + invalidRedirects, + invalidFrom, + invalidTo, + invalidSearch, + invalidParams, + invalidId, + invalidUseSearch, + invalidUseParams, + ] +}) diff --git a/e2e/vue-router/route-modules/vite.config.ts b/e2e/vue-router/route-modules/vite.config.ts new file mode 100644 index 0000000000..51084a35b1 --- /dev/null +++ b/e2e/vue-router/route-modules/vite.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from 'vite' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { tanstackRouter } from '@tanstack/router-plugin/vite' + +export default defineConfig({ + plugins: [ + tanstackRouter({ target: 'vue', autoCodeSplitting: true }), + vueJsx(), + ], +}) diff --git a/eslint.config.js b/eslint.config.js index f58cc3fd10..f3a0c389ca 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -4,9 +4,23 @@ import { tanstackConfig } from '@tanstack/eslint-config' import unusedImports from 'eslint-plugin-unused-imports' +// Packages that set their own `no-restricted-syntax` must include this entry. +export const routerCoreAugmentation = { + selector: "TSModuleDeclaration[id.value='@tanstack/router-core']", + message: + "Augment '@tanstack/router-core/extensions' instead. Augmenting the main entry makes emitted declarations import router types from '@tanstack/router-core' (see packages/router-core/src/extensions.ts).", +} + /** @type {import('eslint').Linter.Config[]} */ export default [ ...tanstackConfig, + { + name: 'tanstack/router-core-augmentation', + files: ['src/**/*.{ts,tsx}'], + rules: { + 'no-restricted-syntax': ['error', routerCoreAugmentation], + }, + }, { name: 'tanstack/temp', rules: { diff --git a/examples/react/start-large-route-modules/.gitignore b/examples/react/start-large-route-modules/.gitignore new file mode 100644 index 0000000000..f9cade74f3 --- /dev/null +++ b/examples/react/start-large-route-modules/.gitignore @@ -0,0 +1,21 @@ +node_modules +.DS_Store +dist +dist-ssr +*.local + +# Written by `pnpm gen`: the route modules, the application's package.json +# (it depends on every generated module) and the files listing the modules. +/modules +/app/package.json +/app/node_modules +/app/route-modules.gen.ts +/app/src/moduleIndex.gen.tsx +/measurements + +# Generated by the route generator. +**/routeTree.gen.ts +**/routeScope.gen.ts +**/routeContract.gen.ts +**/routeModule.gen.ts +**/startModules.gen.ts diff --git a/examples/react/start-large-route-modules/.prettierignore b/examples/react/start-large-route-modules/.prettierignore new file mode 100644 index 0000000000..2be5eaa6ec --- /dev/null +++ b/examples/react/start-large-route-modules/.prettierignore @@ -0,0 +1,4 @@ +**/build +**/public +pnpm-lock.yaml +routeTree.gen.ts \ No newline at end of file diff --git a/examples/react/start-large-route-modules/README.md b/examples/react/start-large-route-modules/README.md new file mode 100644 index 0000000000..51596a70f7 --- /dev/null +++ b/examples/react/start-large-route-modules/README.md @@ -0,0 +1,80 @@ +# TanStack Start - Large Route Modules Example + +A TanStack Start application that installs many generated route modules, to +measure how builds and type checks scale with the number of modules. + +- [Route modules guide](https://tanstack.com/start/latest/docs/framework/react/guide/route-modules) + +## Layout + +- `app/`: the application. It installs every module and provides the request + context the modules require. +- `template/`: the module templates. `account` is a small module every feature + module links to. `feature` is copied once per feature module. Its layout, + item list, item and search routes load data through the module's own server + functions and middleware, and `pages/page.tsx` is copied to fill up the route + count. +- `modules/`: the generated module packages (not committed). They are linked + like workspace packages and resolve their dependencies from this example. + +## Getting Started + +```sh +pnpm install +pnpm gen +pnpm dev +``` + +`pnpm gen` generates routes and builds each package's declarations with +`tsc -p tsconfig.route-types.json`, the account module first. The script cleans +each declaration output before compiling. Router handles route generation; +the package build handles declaration output, and a task runner such as Nx can +schedule these steps in dependency order. It also writes the application files that list the +modules: `app/package.json`, `app/route-modules.gen.ts` and +`app/src/moduleIndex.gen.tsx`. Options: + +- `--modules `: number of feature modules (default 50). +- `--routes `: routes per feature module, at least 5 (default 10). +- `--transpiled`: ships the modules as JavaScript, the way a module prebuilt to + transpiled ESM would. The application still code-splits and compiles them. + +`pnpm dev` and `pnpm build` generate the default modules if none exist yet. +Run `pnpm gen` again to change their number. + +Each feature declares its cross-module references in `tanstack.router.module.uses`. +The application selects each module's mount path explicitly in `includes[].at`. +The feature's viewer requirement is a type-only `StartModuleRequirements` +augmentation; the application supplies that context through request middleware. + +## Build + +```sh +pnpm build # Vite +pnpm build:rsbuild # Rsbuild +pnpm start +``` + +The Nx build targets are uncached because these commands preserve the selected +workload in ignored generated directories. Their output must be built for the +current workload instead of restored from a cache that omits those inputs. + +## Measure + +```sh +pnpm gen --modules 100 +pnpm measure --runs 3 --profile +pnpm gen --modules 100 --transpiled +pnpm measure --runs 3 --profile +``` + +`pnpm measure` builds the application with Vite and with Rsbuild (one of them +with `--toolchain vite` or `--toolchain rsbuild`) and prints the median and +fastest build time. `--profile` adds one build under the V8 CPU profiler. It +lists where the JavaScript threads spent their time, by package. Time spent +inside a TanStack plugin, including the Babel passes it runs, counts for that +plugin. The results are saved to `measurements/` (not committed). + +The example lists `@tanstack/router-core` and `@tanstack/start-client-core` +because it links the framework packages from this repository: the modules' +declarations name the types of a linked package's dependencies by their own +package name. diff --git a/examples/react/start-large-route-modules/app/rsbuild.config.ts b/examples/react/start-large-route-modules/app/rsbuild.config.ts new file mode 100644 index 0000000000..bbb8ab7955 --- /dev/null +++ b/examples/react/start-large-route-modules/app/rsbuild.config.ts @@ -0,0 +1,11 @@ +import { defineConfig } from '@rsbuild/core' +import { pluginReact } from '@rsbuild/plugin-react' +import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' +import { routeModules } from './route-modules.gen' + +export default defineConfig({ + server: { + port: 3000, + }, + plugins: [pluginReact(), tanstackStart({ router: { routeModules } })], +}) diff --git a/examples/react/start-large-route-modules/app/server.js b/examples/react/start-large-route-modules/app/server.js new file mode 100644 index 0000000000..36d7e661c3 --- /dev/null +++ b/examples/react/start-large-route-modules/app/server.js @@ -0,0 +1,18 @@ +// Serves a production build of either toolchain: Vite writes the server +// entry to `server/server.js`, Rsbuild to `server/index.js`. +import { spawn } from 'node:child_process' +import { existsSync } from 'node:fs' +import path from 'node:path' + +const serverEntry = + ['server.js', 'index.js'] + .map((file) => path.resolve('dist', 'server', file)) + .find((file) => existsSync(file)) ?? + path.resolve('dist', 'server', 'server.js') + +const child = spawn( + 'srvx', + ['--prod', '-s', path.resolve('dist', 'client'), serverEntry], + { stdio: 'inherit', shell: process.platform === 'win32' }, +) +child.on('exit', (code) => process.exit(code ?? 0)) diff --git a/examples/react/start-large-route-modules/app/src/router.tsx b/examples/react/start-large-route-modules/app/src/router.tsx new file mode 100644 index 0000000000..a00a209fc4 --- /dev/null +++ b/examples/react/start-large-route-modules/app/src/router.tsx @@ -0,0 +1,10 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: 'intent', + scrollRestoration: true, + }) +} diff --git a/examples/react/start-large-route-modules/app/src/routes/__root.tsx b/examples/react/start-large-route-modules/app/src/routes/__root.tsx new file mode 100644 index 0000000000..2f0f71764e --- /dev/null +++ b/examples/react/start-large-route-modules/app/src/routes/__root.tsx @@ -0,0 +1,44 @@ +/// +import type { ReactNode } from 'react' +import { + HeadContent, + Link, + Scripts, + createRootRoute, +} from '@tanstack/react-router' +import { account } from '../routeScope.gen' +import '../styles.css' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { title: 'Large route modules' }, + ], + }), + shellComponent: RootDocument, +}) + +function RootDocument({ children }: { children: ReactNode }) { + return ( + + + + + +
+ + Large route modules + + +
+
{children}
+ + + + ) +} diff --git a/examples/react/start-large-route-modules/app/src/routes/index.tsx b/examples/react/start-large-route-modules/app/src/routes/index.tsx new file mode 100644 index 0000000000..1f710d26aa --- /dev/null +++ b/examples/react/start-large-route-modules/app/src/routes/index.tsx @@ -0,0 +1,23 @@ +import { createFileRoute } from '@tanstack/react-router' +import { moduleIndex } from '../moduleIndex.gen' + +export const Route = createFileRoute('/')({ + component: Home, +}) + +function Home() { + return ( + <> +

Modules

+

+ {moduleIndex.length} generated feature modules, each its own package + with its own routes, server functions and middleware. +

+
    + {moduleIndex.map(({ name, link }) => ( +
  • {link}
  • + ))} +
+ + ) +} diff --git a/examples/react/start-large-route-modules/app/src/start.ts b/examples/react/start-large-route-modules/app/src/start.ts new file mode 100644 index 0000000000..1205da611b --- /dev/null +++ b/examples/react/start-large-route-modules/app/src/start.ts @@ -0,0 +1,10 @@ +import { createMiddleware, createStart } from '@tanstack/react-start' + +// Provides the request context every feature module requires. +const viewer = createMiddleware().server(({ next }) => + next({ context: { viewer: 'ada' } }), +) + +export const startInstance = createStart(() => ({ + requestMiddleware: [viewer], +})) diff --git a/examples/react/start-large-route-modules/app/src/styles.css b/examples/react/start-large-route-modules/app/src/styles.css new file mode 100644 index 0000000000..46046be435 --- /dev/null +++ b/examples/react/start-large-route-modules/app/src/styles.css @@ -0,0 +1,114 @@ +:root { + color-scheme: light; + --ground: #f5f6f8; + --sheet: #ffffff; + --ink: #1f2328; + --ink-2: #565e67; + --line: #d6dadf; + --accent: #3d5bd9; + --font: + ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, + 'Helvetica Neue', Arial, sans-serif; + --mono: ui-monospace, 'SF Mono', Menlo, Consolas, monospace; +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + background: var(--ground); + color: var(--ink); + font: 15px/1.5 var(--font); +} + +a { + color: inherit; + text-underline-offset: 3px; +} + +a.active { + color: var(--accent); + font-weight: 600; +} + +.topbar { + display: flex; + align-items: center; + gap: 24px; + padding: 12px 24px; + background: var(--sheet); + border-bottom: 1px solid var(--line); +} + +.brand { + font-weight: 700; + text-decoration: none; +} + +.nav, +.module-nav { + display: flex; + flex-wrap: wrap; + gap: 16px; +} + +.page { + max-width: 960px; + margin: 0 auto; + padding: 32px 24px 64px; +} + +.lead { + color: var(--ink-2); + max-width: 60ch; +} + +.grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); + gap: 8px; + padding: 0; + list-style: none; +} + +.grid a { + display: block; + padding: 8px 12px; + background: var(--sheet); + border: 1px solid var(--line); + border-radius: 6px; + text-decoration: none; +} + +.module { + padding: 20px 24px; + background: var(--sheet); + border: 1px solid var(--line); + border-radius: 8px; +} + +.module-tag { + margin: 0 0 4px; + color: var(--ink-2); + font: 12px/1.4 var(--mono); +} + +.rows { + padding-left: 20px; +} + +.facts { + display: grid; + grid-template-columns: max-content 1fr; + gap: 4px 16px; +} + +.facts dt { + color: var(--ink-2); +} + +.facts dd { + margin: 0; +} diff --git a/examples/react/start-large-route-modules/app/tsconfig.json b/examples/react/start-large-route-modules/app/tsconfig.json new file mode 100644 index 0000000000..60398c44b4 --- /dev/null +++ b/examples/react/start-large-route-modules/app/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ES2022", + "moduleResolution": "Bundler", + "module": "ESNext", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "skipLibCheck": true, + "noEmit": true, + "types": ["vite/client"] + }, + "include": [ + "src", + "vite.config.ts", + "rsbuild.config.ts", + "route-modules.gen.ts" + ] +} diff --git a/examples/react/start-large-route-modules/app/vite.config.ts b/examples/react/start-large-route-modules/app/vite.config.ts new file mode 100644 index 0000000000..f211ef9e0b --- /dev/null +++ b/examples/react/start-large-route-modules/app/vite.config.ts @@ -0,0 +1,11 @@ +import { defineConfig } from 'vite' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' +import { routeModules } from './route-modules.gen' + +export default defineConfig({ + server: { + port: 3000, + }, + plugins: [tanstackStart({ router: { routeModules } }), viteReact()], +}) diff --git a/examples/react/start-large-route-modules/package.json b/examples/react/start-large-route-modules/package.json new file mode 100644 index 0000000000..acffbe1479 --- /dev/null +++ b/examples/react/start-large-route-modules/package.json @@ -0,0 +1,49 @@ +{ + "name": "tanstack-start-example-large-route-modules", + "private": true, + "sideEffects": false, + "type": "module", + "nx": { + "targets": { + "build": { + "cache": false + }, + "build:rsbuild": { + "cache": false + } + } + }, + "scripts": { + "gen": "node scripts/gen.mjs", + "dev": "node scripts/gen.mjs --if-missing && cd app && vite dev", + "dev:rsbuild": "node scripts/gen.mjs --if-missing && cd app && rsbuild dev", + "build": "node scripts/gen.mjs --if-missing && cd app && vite build && tsc --noEmit", + "build:rsbuild": "node scripts/gen.mjs --if-missing && cd app && rsbuild build && tsc --noEmit", + "start": "cd app && node server.js", + "measure": "node scripts/measure.mjs" + }, + "dependencies": { + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-start": "^1.169.4", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@rsbuild/core": "^2.1.0", + "@rsbuild/plugin-react": "^2.0.0", + "@tanstack/router-core": "^1.171.39", + "@tanstack/router-generator": "^1.167.46", + "@tanstack/start-client-core": "^1.170.39", + "@types/node": "^22.5.4", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "@typescript/native": "npm:typescript@^7.0.2", + "@vitejs/plugin-react": "^6.0.1", + "srvx": "^1.0.0", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" + }, + "keywords": [], + "author": "", + "license": "ISC" +} diff --git a/examples/react/start-large-route-modules/scripts/gen.mjs b/examples/react/start-large-route-modules/scripts/gen.mjs new file mode 100644 index 0000000000..c7107aa461 --- /dev/null +++ b/examples/react/start-large-route-modules/scripts/gen.mjs @@ -0,0 +1,384 @@ +// Generates the route modules of the example from `template/` and the +// application files that list them, then generates and publishes every module +// in dependency order, with ordinary TypeScript declaration builds. +// +// pnpm gen [--modules ] [--routes ] +// [--transpiled] [--if-missing] +// +// `--if-missing` keeps the modules of an earlier run: `dev` and `build` +// generate the default modules only in a fresh checkout. +// +// `--transpiled` ships every module as JavaScript, the way a module built to +// transpiled ESM would: after publishing its types, each module's TypeScript +// sources are replaced with their oxc output and its manifest lists the +// JavaScript route files. The application still code-splits and compiles +// them. Comparing builds with and without it measures what prebuilding the +// modules that way saves. +// +// The modules are packages in `modules/`, linked like workspace packages: +// `modules/node_modules/` for the modules that use each other and +// `app/node_modules` for the application. They resolve everything else from +// the example's own dependencies. +import { spawn } from 'node:child_process' +import { existsSync } from 'node:fs' +import { + mkdir, + readFile, + readdir, + rm, + symlink, + writeFile, +} from 'node:fs/promises' +import os from 'node:os' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { parseArgs } from 'node:util' +import { Generator, getConfig } from '@tanstack/router-generator' +import { transformWithOxc } from 'vite' + +const { values } = parseArgs({ + options: { + modules: { type: 'string', default: '50' }, + routes: { type: 'string', default: '10' }, + transpiled: { type: 'boolean', default: false }, + 'if-missing': { type: 'boolean', default: false }, + }, +}) +const featureCount = Number(values.modules) +const routeCount = Number(values.routes) +// Every feature has a layout, an item list, an item and a search route, and +// fills the rest with pages. +const pageCount = routeCount - 4 +if (!Number.isInteger(featureCount) || featureCount < 1) { + throw new Error('--modules must be a positive integer') +} +if (!Number.isInteger(routeCount) || pageCount < 1) { + throw new Error('--routes must be an integer of at least 5') +} + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') +const templateDir = path.join(root, 'template') +const modulesDir = path.join(root, 'modules') +const appDir = path.join(root, 'app') +const scope = '@large-route-modules' + +if ( + values['if-missing'] && + existsSync(path.join(appDir, 'route-modules.gen.ts')) +) { + process.exit(0) +} + +const features = Array.from({ length: featureCount }, (_, index) => ({ + name: `feature-${index}`, + title: `Feature ${index}`, +})) + +async function listFiles(dir, base = dir) { + const files = [] + for (const entry of await readdir(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name) + if (entry.isDirectory()) { + files.push(...(await listFiles(full, base))) + } else { + files.push(path.relative(base, full)) + } + } + return files +} + +async function write(file, content) { + await mkdir(path.dirname(file), { recursive: true }) + await writeFile(file, content) +} + +function replaceAll(content, replacements) { + let result = content + for (const [placeholder, value] of Object.entries(replacements)) { + result = result.replaceAll(placeholder, value) + } + return result +} + +function modulePackageJson({ name, dependencies = {} }) { + return { + name: `${scope}/${name}`, + private: true, + type: 'module', + tanstack: { router: { module: { uses: Object.keys(dependencies) } } }, + exports: { + './route-types': { + types: './.tanstack/types/src/routeContract.gen.d.ts', + }, + './route-module': { + types: './.tanstack/types/src/routeModule.gen.d.ts', + default: './src/routeModule.gen.ts', + }, + './package.json': './package.json', + }, + dependencies: { + ...dependencies, + '@tanstack/react-router': '*', + '@tanstack/react-start': '*', + react: '*', + }, + } +} + +const moduleTsconfig = { + compilerOptions: { + strict: true, + esModuleInterop: true, + jsx: 'react-jsx', + target: 'ESNext', + moduleResolution: 'Bundler', + module: 'ESNext', + lib: ['DOM', 'DOM.Iterable', 'ES2022'], + skipLibCheck: true, + noEmit: true, + types: [], + }, + include: ['src'], +} + +const json = (value) => `${JSON.stringify(value, null, 2)}\n` + +async function writeModule(name, templateName, packageJson, replacements) { + const dir = path.join(modulesDir, name) + const template = path.join(templateDir, templateName) + for (const file of await listFiles(template)) { + const content = await readFile(path.join(template, file), 'utf8') + if (file === path.join('src', 'routes', 'pages', 'page.tsx')) { + for (let page = 0; page < pageCount; page++) { + await write( + path.join(dir, 'src', 'routes', 'pages', `page-${page}.tsx`), + replaceAll(content, { + ...replacements, + __NEXT_PAGE__: String((page + 1) % pageCount), + __PAGE__: String(page), + }), + ) + } + } else { + await write(path.join(dir, file), replaceAll(content, replacements)) + } + } + await write(path.join(dir, 'package.json'), json(packageJson)) + await write(path.join(dir, 'tsconfig.json'), json(moduleTsconfig)) + await write( + path.join(dir, 'tsconfig.route-types.json'), + json({ + extends: './tsconfig.json', + compilerOptions: { + noEmit: false, + declaration: true, + emitDeclarationOnly: true, + noEmitOnError: true, + declarationMap: true, + rootDir: '.', + outDir: '.tanstack/types', + }, + }), + ) + await symlink( + path.join('..', '..', name), + path.join(modulesDir, 'node_modules', scope, name), + 'dir', + ) +} + +async function runPool(items, concurrency, task) { + const queue = [...items] + await Promise.all( + Array.from({ length: Math.min(concurrency, queue.length) }, async () => { + while (queue.length) { + await task(queue.shift()) + } + }), + ) +} + +async function generate(name) { + const dir = path.join(modulesDir, name) + const config = getConfig({ disableLogging: true }, dir) + await new Generator({ config, root: dir }).run() +} + +async function emitTypes(name) { + const packageRoot = path.join(modulesDir, name) + await rm(path.join(packageRoot, '.tanstack/types'), { + recursive: true, + force: true, + }) + await new Promise((resolve, reject) => { + const child = spawn( + path.join( + root, + 'node_modules/.bin', + process.platform === 'win32' ? 'tsc.cmd' : 'tsc', + ), + ['-p', 'tsconfig.route-types.json', '--pretty', 'false'], + { + cwd: packageRoot, + stdio: 'inherit', + shell: process.platform === 'win32', + }, + ) + child.once('error', reject) + child.once('close', (code) => { + if (code === 0) { + resolve() + } else { + reject(new Error(`Declaration build of ${name} exited with ${code}`)) + } + }) + }) +} + +const started = performance.now() + +await rm(modulesDir, { recursive: true, force: true }) +await rm(path.join(appDir, 'node_modules'), { recursive: true, force: true }) +await mkdir(path.join(modulesDir, 'node_modules', scope), { recursive: true }) +await mkdir(path.join(appDir, 'node_modules'), { recursive: true }) +await symlink( + path.join('..', '..', 'modules', 'node_modules', scope), + path.join(appDir, 'node_modules', scope), + 'dir', +) + +await writeModule( + 'account', + 'account', + modulePackageJson({ name: 'account' }), + {}, +) +for (const feature of features) { + await writeModule( + feature.name, + 'feature', + modulePackageJson({ + name: feature.name, + dependencies: { [`${scope}/account`]: 'link:../account' }, + }), + { __MODULE_ID__: `${scope}/${feature.name}`, __TITLE__: feature.title }, + ) +} + +// The application depends on every module it installs. +const moduleIds = ['account', ...features.map((feature) => feature.name)].map( + (name) => `${scope}/${name}`, +) +await write( + path.join(appDir, 'package.json'), + json({ + name: `${scope}/app`, + private: true, + type: 'module', + dependencies: { + ...Object.fromEntries( + moduleIds.map((id) => [ + id, + `link:../modules/${id.slice(scope.length + 1)}`, + ]), + ), + '@tanstack/react-router': '*', + '@tanstack/react-start': '*', + react: '*', + 'react-dom': '*', + }, + }), +) +await write( + path.join(appDir, 'route-modules.gen.ts'), + `// Written by \`pnpm gen\`: the modules the application installs. +export const routeModules = { + includes: ${JSON.stringify( + moduleIds.map((module) => ({ + module, + at: `/${module.slice(scope.length + 1)}`, + })), + null, + 2, + ).replaceAll('\n', '\n ')}, +} +`, +) +const namespace = (name) => name.replace(/-(\w)/g, (_, c) => c.toUpperCase()) +await write( + path.join(appDir, 'src', 'moduleIndex.gen.tsx'), + `// Written by \`pnpm gen\`: a link to every feature module. +import { ${features.map((feature) => namespace(feature.name)).join(', ')} } from './routeScope.gen' + +export const moduleIndex = [ +${features + .map( + (feature) => + ` { name: '${feature.name}', link: <${namespace(feature.name)}.Link to="/">${feature.title} },`, + ) + .join('\n')} +] +`, +) + +// The features use the account module: it is published first. +await generate('account') +await emitTypes('account') +for (const feature of features) { + await generate(feature.name) +} +await runPool( + features.map((feature) => feature.name), + os.availableParallelism(), + emitTypes, +) + +async function transpile(name) { + const dir = path.join(modulesDir, name) + const src = path.join(dir, 'src') + for (const file of await listFiles(src)) { + if (!/\.tsx?$/.test(file)) { + continue + } + const source = path.join(src, file) + const result = await transformWithOxc( + await readFile(source, 'utf8'), + source, + { jsx: { runtime: 'automatic' } }, + ) + await writeFile(source.replace(/\.tsx?$/, '.js'), result.code) + await rm(source) + } + const manifestPath = path.join(dir, '.tanstack', 'route-module.json') + const manifest = JSON.parse(await readFile(manifestPath, 'utf8')) + for (const routeFile of manifest.routeFiles) { + routeFile.file = routeFile.file.replace(/\.tsx?$/, '.js') + } + for (const tree of manifest.clientTrees) { + tree.file = tree.file.replace(/\.tsx?$/, '.js') + tree.clientFile = tree.clientFile.replace(/\.tsx?$/, '.js') + } + await writeFile(manifestPath, json(manifest)) + const packageJsonPath = path.join(dir, 'package.json') + const packageJson = JSON.parse(await readFile(packageJsonPath, 'utf8')) + packageJson.exports['./route-module'].default = './src/routeModule.gen.js' + await writeFile(packageJsonPath, json(packageJson)) +} + +if (values.transpiled) { + await runPool( + ['account', ...features.map((feature) => feature.name)], + os.availableParallelism(), + transpile, + ) +} + +const seconds = ((performance.now() - started) / 1000).toFixed(1) +console.log( + `Generated ${featureCount} feature modules with ${routeCount} routes each, plus the account module${values.transpiled ? ', as transpiled JavaScript,' : ''} in ${seconds}s.`, +) +if (!existsSync(path.join(appDir, 'src', 'routeTree.gen.ts'))) { + console.log( + 'The application generates its route tree on `pnpm dev` or `pnpm build`.', + ) +} diff --git a/examples/react/start-large-route-modules/scripts/measure.mjs b/examples/react/start-large-route-modules/scripts/measure.mjs new file mode 100644 index 0000000000..0c130f5a76 --- /dev/null +++ b/examples/react/start-large-route-modules/scripts/measure.mjs @@ -0,0 +1,242 @@ +// Measures production builds of the application with the modules `pnpm gen` +// generated last. +// +// pnpm measure [--toolchain vite|rsbuild] [--runs ] [--profile] +// +// Each run is a fresh build process without the type check. `--profile` adds +// one run under the V8 CPU profiler and lists where the JavaScript thread +// spent its time, grouped by package. Work in native threads (Rolldown, Oxc, +// Rspack, SWC) shows up only as the JavaScript thread waiting for it. +import { spawn } from 'node:child_process' +import { existsSync } from 'node:fs' +import { mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises' +import { createRequire } from 'node:module' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { parseArgs } from 'node:util' + +const { values } = parseArgs({ + options: { + toolchain: { type: 'string', multiple: true }, + runs: { type: 'string', default: '3' }, + profile: { type: 'boolean', default: false }, + }, +}) +const toolchains = values.toolchain ?? ['vite', 'rsbuild'] +const runs = Number(values.runs) + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') +const appDir = path.join(root, 'app') +const modulesDir = path.join(root, 'modules') +const require = createRequire(path.join(root, 'package.json')) + +const bins = { + vite: path.join( + path.dirname(require.resolve('vite/package.json')), + 'bin', + 'vite.js', + ), + rsbuild: path.join( + path.dirname(require.resolve('@rsbuild/core/package.json')), + 'bin', + 'rsbuild.js', + ), +} + +if (!existsSync(path.join(appDir, 'route-modules.gen.ts'))) { + throw new Error('Generate the modules first: pnpm gen') +} + +async function listFiles(dir) { + const files = [] + for (const entry of await readdir(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name) + if (entry.isDirectory()) { + files.push(...(await listFiles(full))) + } else { + files.push(full) + } + } + return files +} + +function build(toolchain, nodeArgs = []) { + return new Promise((resolve, reject) => { + const started = performance.now() + const child = spawn( + process.execPath, + [...nodeArgs, bins[toolchain], 'build'], + { + cwd: appDir, + env: { ...process.env, NODE_ENV: 'production' }, + stdio: ['ignore', 'ignore', 'pipe'], + }, + ) + let stderr = '' + child.stderr.on('data', (chunk) => (stderr += chunk)) + child.on('error', reject) + child.on('close', (code) => { + if (code !== 0) { + reject(new Error(`${toolchain} build failed:\n${stderr}`)) + } else { + resolve(performance.now() - started) + } + }) + }) +} + +const workspacePackages = path.resolve(root, '..', '..', '..', 'packages') + +/** The package a profiled function belongs to, or a V8 category. */ +function categorize(callFrame) { + const url = callFrame.url + if (!url) { + return callFrame.functionName.startsWith('(') + ? callFrame.functionName + : '(native)' + } + if (url.startsWith('node:')) { + return 'node' + } + const file = url.startsWith('file://') ? fileURLToPath(url) : url + const nodeModules = file.lastIndexOf(`${path.sep}node_modules${path.sep}`) + if (nodeModules !== -1) { + const [first, second] = file + .slice(nodeModules + '/node_modules/'.length) + .split(path.sep) + return first.startsWith('@') ? `${first}/${second}` : first + } + if (file.startsWith(workspacePackages + path.sep)) { + return `@tanstack/${file.slice(workspacePackages.length + 1).split(path.sep)[0]}` + } + return path.relative(root, file).split(path.sep)[0] +} + +/** + * Sums the sampled time of the profiles by the package of the sampled + * function, except that time spent inside a TanStack package's call (its + * Babel passes, for example) counts for the outermost TanStack package on the + * stack: the plugin that ran. + */ +async function summarizeProfiles(dir) { + const times = new Map() + let total = 0 + for (const file of await readdir(dir)) { + const profile = JSON.parse(await readFile(path.join(dir, file), 'utf8')) + const nodes = new Map(profile.nodes.map((node) => [node.id, node])) + const parents = new Map() + for (const node of profile.nodes) { + for (const child of node.children ?? []) { + parents.set(child, node.id) + } + } + const owners = new Map() + const ownerOf = (id) => { + if (!owners.has(id)) { + const parent = parents.get(id) + const outer = parent === undefined ? undefined : ownerOf(parent) + const category = categorize(nodes.get(id).callFrame) + owners.set( + id, + outer ?? (category.startsWith('@tanstack/') ? category : undefined), + ) + } + return owners.get(id) + } + for (let index = 0; index < profile.samples.length; index++) { + const id = profile.samples[index] + const delta = profile.timeDeltas[index] / 1000 + const owner = ownerOf(id) + const category = owner + ? `${owner} (with callees)` + : categorize(nodes.get(id).callFrame) + times.set(category, (times.get(category) ?? 0) + delta) + total += delta + } + } + return { + total, + categories: [...times] + .sort((a, b) => b[1] - a[1]) + .map(([category, ms]) => ({ category, ms })), + } +} + +const median = (numbers) => { + const sorted = [...numbers].sort((a, b) => a - b) + const middle = Math.floor(sorted.length / 2) + return sorted.length % 2 + ? sorted[middle] + : (sorted[middle - 1] + sorted[middle]) / 2 +} +const ms = (value) => `${Math.round(value).toLocaleString('en-US')} ms` + +const moduleNames = (await readdir(modulesDir)).filter( + (name) => name !== 'node_modules', +) +const moduleFiles = ( + await Promise.all( + moduleNames.map((name) => listFiles(path.join(modulesDir, name, 'src'))), + ) +).flat() +const moduleCount = moduleNames.length +const transpiled = !moduleFiles.some((file) => /\.tsx?$/.test(file)) +console.log( + `${moduleCount} modules, ${moduleFiles.length} module source files (${transpiled ? 'transpiled JavaScript' : 'TypeScript'})`, +) + +const results = { + date: new Date().toISOString(), + modules: moduleCount, + moduleFiles: moduleFiles.length, + transpiled, + toolchains: {}, +} + +for (const toolchain of toolchains) { + if (!bins[toolchain]) { + throw new Error(`Unknown toolchain "${toolchain}": use vite or rsbuild`) + } + const times = [] + for (let run = 0; run < runs; run++) { + await rm(path.join(appDir, 'dist'), { recursive: true, force: true }) + times.push(await build(toolchain)) + } + const clientChunks = ( + await listFiles(path.join(appDir, 'dist', 'client')) + ).filter((file) => file.endsWith('.js')).length + console.log( + `${toolchain}: median ${ms(median(times))}, min ${ms(Math.min(...times))} over ${runs} runs (${clientChunks} client chunks)`, + ) + const result = { times, clientChunks } + + if (values.profile) { + const profileDir = path.join( + root, + 'measurements', + `${toolchain}-cpuprofile`, + ) + await rm(profileDir, { recursive: true, force: true }) + await mkdir(profileDir, { recursive: true }) + await rm(path.join(appDir, 'dist'), { recursive: true, force: true }) + await build(toolchain, ['--cpu-prof', `--cpu-prof-dir=${profileDir}`]) + const summary = await summarizeProfiles(profileDir) + console.log(` JavaScript threads, ${ms(summary.total)} sampled:`) + for (const { category, ms: time } of summary.categories.slice(0, 15)) { + console.log( + ` ${category.padEnd(44)} ${ms(time).padStart(10)} ${((time / summary.total) * 100).toFixed(1).padStart(5)}%`, + ) + } + result.profile = summary + } + results.toolchains[toolchain] = result +} + +await mkdir(path.join(root, 'measurements'), { recursive: true }) +const resultFile = path.join( + root, + 'measurements', + `${results.date.replace(/[:.]/g, '-')}.json`, +) +await writeFile(resultFile, `${JSON.stringify(results, null, 2)}\n`) +console.log(`Saved ${path.relative(root, resultFile)}`) diff --git a/examples/react/start-large-route-modules/template/account/src/api.ts b/examples/react/start-large-route-modules/template/account/src/api.ts new file mode 100644 index 0000000000..c94341627d --- /dev/null +++ b/examples/react/start-large-route-modules/template/account/src/api.ts @@ -0,0 +1,8 @@ +import { createServerFn } from './routeScope.gen' + +/** The signed-in account, loaded on the server. */ +export const getAccount = createServerFn().handler(() => ({ + name: 'Ada Lovelace', + plan: 'Team', + seats: 12, +})) diff --git a/examples/react/start-large-route-modules/template/account/src/routes/__root.tsx b/examples/react/start-large-route-modules/template/account/src/routes/__root.tsx new file mode 100644 index 0000000000..244e474f54 --- /dev/null +++ b/examples/react/start-large-route-modules/template/account/src/routes/__root.tsx @@ -0,0 +1,18 @@ +import { Outlet } from '@tanstack/react-router' +import { createModuleRoot } from '../routeScope.gen' + +export const Route = createModuleRoot()({ + component: AccountLayout, +}) + +function AccountLayout() { + return ( +
+

+ @large-route-modules/account {Route.fullPath} +

+

Account

+ +
+ ) +} diff --git a/examples/react/start-large-route-modules/template/account/src/routes/index.tsx b/examples/react/start-large-route-modules/template/account/src/routes/index.tsx new file mode 100644 index 0000000000..01480ab45a --- /dev/null +++ b/examples/react/start-large-route-modules/template/account/src/routes/index.tsx @@ -0,0 +1,21 @@ +import { createFileRoute } from '../routeScope.gen' +import { getAccount } from '../api' + +export const Route = createFileRoute('@large-route-modules/account:/')({ + loader: () => getAccount(), + component: Account, +}) + +function Account() { + const account = Route.useLoaderData() + return ( +
+
Name
+
{account.name}
+
Plan
+
{account.plan}
+
Seats
+
{account.seats}
+
+ ) +} diff --git a/examples/react/start-large-route-modules/template/feature/src/api.ts b/examples/react/start-large-route-modules/template/feature/src/api.ts new file mode 100644 index 0000000000..4cf635cb26 --- /dev/null +++ b/examples/react/start-large-route-modules/template/feature/src/api.ts @@ -0,0 +1,45 @@ +import { notFound } from '@tanstack/react-router' +import { createMiddleware, createServerFn } from './routeScope.gen' + +// Module-local: only this module's server functions run it. +const audience = createMiddleware({ type: 'function' }).server( + ({ context, next }) => + next({ context: { audience: `${context.viewer} in __MODULE_ID__` } }), +) + +const items = Array.from({ length: 24 }, (_, index) => ({ + id: `item-${index + 1}`, + name: `__TITLE__ item ${index + 1}`, + quantity: (index * 7) % 13, +})) + +export const listItems = createServerFn() + .middleware([audience]) + .handler(({ context }) => ({ + audience: context.audience, + items: items.slice(0, 8).map(({ id, name }) => ({ id, name })), + })) + +export const getItem = createServerFn() + .middleware([audience]) + .validator((id: string) => id) + .handler(({ data, context }) => { + const item = items.find((candidate) => candidate.id === data) + if (!item) { + throw notFound() + } + return { ...item, viewedBy: context.audience } + }) + +const pageSize = 6 + +/** Filters the items on whichever side runs the loader. */ +export function searchItems(query: string, page: number) { + const matches = items.filter((item) => + item.name.toLowerCase().includes(query.toLowerCase()), + ) + return { + items: matches.slice((page - 1) * pageSize, page * pageSize), + hasMore: matches.length > page * pageSize, + } +} diff --git a/examples/react/start-large-route-modules/template/feature/src/requirements.ts b/examples/react/start-large-route-modules/template/feature/src/requirements.ts new file mode 100644 index 0000000000..4f1f611458 --- /dev/null +++ b/examples/react/start-large-route-modules/template/feature/src/requirements.ts @@ -0,0 +1,10 @@ +export type { StartModuleRequirements } from '@tanstack/react-start' + +// The application says who is viewing; the module does not authenticate. +declare module '@tanstack/react-start' { + interface StartModuleRequirements { + ['__MODULE_ID__']: { + requestContext: { viewer: string } + } + } +} diff --git a/examples/react/start-large-route-modules/template/feature/src/routes/$itemId.tsx b/examples/react/start-large-route-modules/template/feature/src/routes/$itemId.tsx new file mode 100644 index 0000000000..3619e92ef4 --- /dev/null +++ b/examples/react/start-large-route-modules/template/feature/src/routes/$itemId.tsx @@ -0,0 +1,28 @@ +import { Link, account, createFileRoute } from '../routeScope.gen' +import { getItem } from '../api' + +export const Route = createFileRoute('__MODULE_ID__:/$itemId')({ + loader: ({ params }) => getItem({ data: params.itemId }), + component: Item, +}) + +function Item() { + const item = Route.useLoaderData() + return ( +
+

{item.name}

+
+
Quantity
+
{item.quantity}
+
Viewed by
+
+ {item.viewedBy} +
+
+

+ All items ·{' '} + Your account +

+
+ ) +} diff --git a/examples/react/start-large-route-modules/template/feature/src/routes/__root.tsx b/examples/react/start-large-route-modules/template/feature/src/routes/__root.tsx new file mode 100644 index 0000000000..2c74ff494e --- /dev/null +++ b/examples/react/start-large-route-modules/template/feature/src/routes/__root.tsx @@ -0,0 +1,28 @@ +import { Outlet } from '@tanstack/react-router' +import { Link, createModuleRoot } from '../routeScope.gen' +export type {} from '../requirements' + +export const Route = createModuleRoot()({ + component: FeatureLayout, +}) + +function FeatureLayout() { + return ( +
+

+ __MODULE_ID__ {Route.fullPath} +

+

__TITLE__

+ + +
+ ) +} diff --git a/examples/react/start-large-route-modules/template/feature/src/routes/index.tsx b/examples/react/start-large-route-modules/template/feature/src/routes/index.tsx new file mode 100644 index 0000000000..0bb446ebda --- /dev/null +++ b/examples/react/start-large-route-modules/template/feature/src/routes/index.tsx @@ -0,0 +1,25 @@ +import { Link, createFileRoute } from '../routeScope.gen' +import { listItems } from '../api' + +export const Route = createFileRoute('__MODULE_ID__:/')({ + loader: () => listItems(), + component: Items, +}) + +function Items() { + const { audience, items } = Route.useLoaderData() + return ( + <> +

Loaded on the server for {audience}.

+
    + {items.map((item) => ( +
  • + + {item.name} + +
  • + ))} +
+ + ) +} diff --git a/examples/react/start-large-route-modules/template/feature/src/routes/pages/page.tsx b/examples/react/start-large-route-modules/template/feature/src/routes/pages/page.tsx new file mode 100644 index 0000000000..e4e2b1a42c --- /dev/null +++ b/examples/react/start-large-route-modules/template/feature/src/routes/pages/page.tsx @@ -0,0 +1,30 @@ +import { Fragment } from 'react' +import { Link, createFileRoute } from '../../routeScope.gen' + +export const Route = createFileRoute('__MODULE_ID__:/pages/page-__PAGE__')({ + loader: () => ({ + rows: Array.from({ length: 8 }, (_, index) => ({ + label: `Row ${index + 1}`, + value: (index + 1) * (__PAGE__ + 1), + })), + }), + component: Page, +}) + +function Page() { + const { rows } = Route.useLoaderData() + return ( +
+

Page __PAGE__ of __TITLE__

+
+ {rows.map((row) => ( + +
{row.label}
+
{row.value}
+
+ ))} +
+ Next page +
+ ) +} diff --git a/examples/react/start-large-route-modules/template/feature/src/routes/search.tsx b/examples/react/start-large-route-modules/template/feature/src/routes/search.tsx new file mode 100644 index 0000000000..a6316c2946 --- /dev/null +++ b/examples/react/start-large-route-modules/template/feature/src/routes/search.tsx @@ -0,0 +1,44 @@ +import { Link, createFileRoute } from '../routeScope.gen' +import { searchItems } from '../api' + +export const Route = createFileRoute('__MODULE_ID__:/search')({ + validateSearch: (search: Record) => ({ + q: typeof search.q === 'string' ? search.q : '', + page: Math.max(1, Number(search.page) || 1), + }), + loaderDeps: ({ search }) => search, + loader: ({ deps }) => searchItems(deps.q, deps.page), + component: Search, +}) + +function Search() { + const { q, page } = Route.useSearch() + const results = Route.useLoaderData() + const navigate = Route.useNavigate() + return ( + <> + + navigate({ search: { q: event.target.value, page: 1 } }) + } + /> +
    + {results.items.map((item) => ( +
  • + + {item.name} + +
  • + ))} +
+ {results.hasMore ? ( + + Next results + + ) : null} + + ) +} diff --git a/packages/eslint-plugin-router/src/__tests__/fixtures/app/package.json b/packages/eslint-plugin-router/src/__tests__/fixtures/app/package.json new file mode 100644 index 0000000000..87b8a0c318 --- /dev/null +++ b/packages/eslint-plugin-router/src/__tests__/fixtures/app/package.json @@ -0,0 +1,4 @@ +{ + "name": "@fixture/app", + "private": true +} diff --git a/packages/eslint-plugin-router/src/__tests__/fixtures/route-module/package.json b/packages/eslint-plugin-router/src/__tests__/fixtures/route-module/package.json new file mode 100644 index 0000000000..346800ea14 --- /dev/null +++ b/packages/eslint-plugin-router/src/__tests__/fixtures/route-module/package.json @@ -0,0 +1,9 @@ +{ + "name": "@fixture/route-module", + "private": true, + "tanstack": { + "router": { + "module": true + } + } +} diff --git a/packages/eslint-plugin-router/src/__tests__/route-module-imports.rule.test.ts b/packages/eslint-plugin-router/src/__tests__/route-module-imports.rule.test.ts new file mode 100644 index 0000000000..8cf1df7ca9 --- /dev/null +++ b/packages/eslint-plugin-router/src/__tests__/route-module-imports.rule.test.ts @@ -0,0 +1,101 @@ +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { RuleTester } from '@typescript-eslint/rule-tester' + +import { + name, + rule, +} from '../rules/route-module-imports/route-module-imports.rule' + +const fixtures = path.join( + path.dirname(fileURLToPath(import.meta.url)), + 'fixtures', +) +const moduleFile = path.join(fixtures, 'route-module/src/routes/index.tsx') +const appFile = path.join(fixtures, 'app/src/routes/index.tsx') +const generatedFile = path.join(fixtures, 'route-module/src/routeScope.gen.ts') + +const ruleTester = new RuleTester() + +ruleTester.run(name, rule, { + valid: [ + { + name: 'scope imports in a route module', + filename: moduleFile, + code: ` + import { createFileRoute, Link } from '../routeScope.gen' + export const Route = createFileRoute('@fixture/route-module:/')({}) + `, + }, + { + name: 'APIs the scope does not provide', + filename: moduleFile, + code: ` + import { Outlet, notFound, createSerializationAdapter } from '@tanstack/react-router' + import { createMiddleware, useServerFn } from '@tanstack/react-start' + `, + }, + { + name: 'type-only imports', + filename: moduleFile, + code: ` + import type { Link } from '@tanstack/react-router' + import { type useNavigate } from '@tanstack/solid-router' + `, + }, + { + name: 'applications are not route modules', + filename: appFile, + code: ` + import { createFileRoute, Link, createRootRoute } from '@tanstack/react-router' + import { createServerFn } from '@tanstack/react-start' + `, + }, + { + name: 'generated files', + filename: generatedFile, + code: ` + import { createServerFn as createStartServerFn } from '@tanstack/react-start' + `, + }, + ], + invalid: [ + { + name: 'routing APIs from the framework package', + filename: moduleFile, + code: ` + import { createFileRoute, Link as RouterLink, Outlet } from '@tanstack/react-router' + import { useNavigate } from '@tanstack/vue-router' + `, + errors: [ + { messageId: 'useRouteScope', data: { name: 'createFileRoute' } }, + { messageId: 'useRouteScope', data: { name: 'Link' } }, + { messageId: 'useRouteScope', data: { name: 'useNavigate' } }, + ], + }, + { + name: 'root route constructors', + filename: moduleFile, + code: ` + import { createRootRouteWithContext } from '@tanstack/solid-router' + `, + errors: [ + { + messageId: 'useModuleRoot', + data: { name: 'createRootRouteWithContext' }, + }, + ], + }, + { + name: 'Start APIs from the framework package', + filename: moduleFile, + code: ` + import { createServerFn, createStartModule } from '@tanstack/react-start' + `, + errors: [ + { messageId: 'useRouteScope', data: { name: 'createServerFn' } }, + { messageId: 'useRouteScope', data: { name: 'createStartModule' } }, + ], + }, + ], +}) diff --git a/packages/eslint-plugin-router/src/index.ts b/packages/eslint-plugin-router/src/index.ts index 7b8855cdf2..5bbc48de1e 100644 --- a/packages/eslint-plugin-router/src/index.ts +++ b/packages/eslint-plugin-router/src/index.ts @@ -27,6 +27,7 @@ Object.assign(plugin.configs, { rules: { '@tanstack/router/create-route-property-order': 'warn', '@tanstack/router/route-param-names': 'error', + '@tanstack/router/route-module-imports': 'error', }, }, 'flat/recommended': [ @@ -37,6 +38,7 @@ Object.assign(plugin.configs, { rules: { '@tanstack/router/create-route-property-order': 'warn', '@tanstack/router/route-param-names': 'error', + '@tanstack/router/route-module-imports': 'error', }, }, ], diff --git a/packages/eslint-plugin-router/src/rules.ts b/packages/eslint-plugin-router/src/rules.ts index 1042929a45..ebe904d098 100644 --- a/packages/eslint-plugin-router/src/rules.ts +++ b/packages/eslint-plugin-router/src/rules.ts @@ -1,5 +1,6 @@ import * as createRoutePropertyOrder from './rules/create-route-property-order/create-route-property-order.rule' import * as routeParamNames from './rules/route-param-names/route-param-names.rule' +import * as routeModuleImports from './rules/route-module-imports/route-module-imports.rule' import type { ESLintUtils } from '@typescript-eslint/utils' import type { ExtraRuleDocs } from './types' @@ -14,4 +15,5 @@ export const rules: Record< > = { [createRoutePropertyOrder.name]: createRoutePropertyOrder.rule, [routeParamNames.name]: routeParamNames.rule, + [routeModuleImports.name]: routeModuleImports.rule, } diff --git a/packages/eslint-plugin-router/src/rules/route-module-imports/constants.ts b/packages/eslint-plugin-router/src/rules/route-module-imports/constants.ts new file mode 100644 index 0000000000..3381caad47 --- /dev/null +++ b/packages/eslint-plugin-router/src/rules/route-module-imports/constants.ts @@ -0,0 +1,37 @@ +/** + * Routing APIs a route module's generated scope (`routeScope.gen.ts`) exports + * typed against the module's own routes. + */ +export const scopedRouterApis = [ + 'createFileRoute', + 'Link', + 'createLink', + 'linkOptions', + 'Navigate', + 'useNavigate', + 'redirect', + 'MatchRoute', + 'useMatchRoute', + 'useRouter', + 'getRouteApi', + 'useMatch', + 'useMatches', + 'useParentMatches', + 'useChildMatches', + 'useLoaderData', + 'useLoaderDeps', + 'useSearch', + 'useParams', + 'useRouteContext', + 'useLocation', + 'useRouterState', +] as const + +/** Root route constructors; a route module's root is `createModuleRoot`. */ +export const rootRouteConstructors = [ + 'createRootRoute', + 'createRootRouteWithContext', +] as const + +/** Start APIs a Start route module's scope exports. */ +export const scopedStartApis = ['createServerFn', 'createStartModule'] as const diff --git a/packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.rule.ts b/packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.rule.ts new file mode 100644 index 0000000000..ab20f09c87 --- /dev/null +++ b/packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.rule.ts @@ -0,0 +1,90 @@ +import path from 'node:path' +import { AST_NODE_TYPES, ESLintUtils } from '@typescript-eslint/utils' + +import { getDocsUrl } from '../../utils/get-docs-url' +import { + rootRouteConstructors, + scopedRouterApis, + scopedStartApis, +} from './constants' +import { isGeneratedFile, isInRouteModule } from './route-module-imports.utils' +import type { ExtraRuleDocs } from '../../types' + +const createRule = ESLintUtils.RuleCreator(getDocsUrl) + +const routerPackage = /^@tanstack\/(react|solid|vue)-router$/ +const startPackage = /^@tanstack\/(react|solid|vue)-start$/ +const scopedRouterApiSet = new Set(scopedRouterApis) +const rootRouteConstructorSet = new Set(rootRouteConstructors) +const scopedStartApiSet = new Set(scopedStartApis) + +export const name = 'route-module-imports' + +export const rule = createRule({ + name, + meta: { + type: 'problem', + docs: { + description: + 'Ensure route modules import routing and Start APIs from their generated route scope', + recommended: 'error', + }, + messages: { + useRouteScope: + '"{{name}}" in a route module must be imported from its generated route scope (routeScope.gen), which types it against the module\'s own routes.', + useModuleRoot: + 'The root route of a route module is created with "createModuleRoot" from its generated route scope (routeScope.gen), not with "{{name}}".', + }, + schema: [], + }, + defaultOptions: [], + + create(context) { + const filename = context.filename + if (isGeneratedFile(filename) || !isInRouteModule(path.dirname(filename))) { + return {} + } + + return { + ImportDeclaration(node) { + if (node.importKind === 'type') { + return + } + const source = node.source.value + const fromRouter = routerPackage.test(source) + const fromStart = startPackage.test(source) + if (!fromRouter && !fromStart) { + return + } + for (const specifier of node.specifiers) { + if ( + specifier.type !== AST_NODE_TYPES.ImportSpecifier || + specifier.importKind === 'type' + ) { + continue + } + const imported = + specifier.imported.type === AST_NODE_TYPES.Identifier + ? specifier.imported.name + : specifier.imported.value + if (fromRouter && rootRouteConstructorSet.has(imported)) { + context.report({ + node: specifier, + messageId: 'useModuleRoot', + data: { name: imported }, + }) + } else if ( + (fromRouter && scopedRouterApiSet.has(imported)) || + (fromStart && scopedStartApiSet.has(imported)) + ) { + context.report({ + node: specifier, + messageId: 'useRouteScope', + data: { name: imported }, + }) + } + } + }, + } + }, +}) diff --git a/packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.utils.ts b/packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.utils.ts new file mode 100644 index 0000000000..c72e6df0a8 --- /dev/null +++ b/packages/eslint-plugin-router/src/rules/route-module-imports/route-module-imports.utils.ts @@ -0,0 +1,50 @@ +import fs from 'node:fs' +import path from 'node:path' + +const routeModuleByDirectory = new Map() + +function readsAsRouteModule(packageJsonPath: string): boolean { + try { + const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) + return packageJson?.tanstack?.router?.module !== undefined + } catch { + return false + } +} + +/** + * Whether `directory` belongs to a route module: its nearest `package.json` + * declares `tanstack.router.module`. Results are cached per directory. + */ +export function isInRouteModule(directory: string): boolean { + const visited: Array = [] + let current = path.resolve(directory) + let result = false + for (;;) { + const cached = routeModuleByDirectory.get(current) + if (cached !== undefined) { + result = cached + break + } + visited.push(current) + const packageJsonPath = path.join(current, 'package.json') + if (fs.existsSync(packageJsonPath)) { + result = readsAsRouteModule(packageJsonPath) + break + } + const parent = path.dirname(current) + if (parent === current) { + break + } + current = parent + } + for (const dir of visited) { + routeModuleByDirectory.set(dir, result) + } + return result +} + +/** Generated files (`routeScope.gen.ts` imports the framework itself). */ +export function isGeneratedFile(filename: string): boolean { + return /\.gen\.[cm]?[jt]sx?$/.test(filename) +} diff --git a/packages/eslint-plugin-router/tsconfig.json b/packages/eslint-plugin-router/tsconfig.json index cbceff3f8b..1715152a91 100644 --- a/packages/eslint-plugin-router/tsconfig.json +++ b/packages/eslint-plugin-router/tsconfig.json @@ -1,7 +1,8 @@ { "extends": "../../tsconfig.json", "compilerOptions": { - "moduleResolution": "Bundler" + "moduleResolution": "Bundler", + "types": ["node"] }, "include": ["src", "eslint.config.js", "vite.config.ts"] } diff --git a/packages/react-router/package.json b/packages/react-router/package.json index 9a61d5af25..94ce82d1ac 100644 --- a/packages/react-router/package.json +++ b/packages/react-router/package.json @@ -27,12 +27,12 @@ "clean": "rimraf ./dist && rimraf ./coverage", "test:eslint": "eslint", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js -p tsconfig.legacy.json", - "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js -p tsconfig.legacy.json", - "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js -p tsconfig.legacy.json", - "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js -p tsconfig.legacy.json", - "test:types:ts60": "tsc6 -p tsconfig.legacy.json", - "test:types:ts70": "tsc -p tsconfig.legacy.json", + "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js -p tsconfig.legacy.json && node ../../node_modules/typescript56/lib/tsc.js -p tests/registered-router-cycle/tsconfig.json", + "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js -p tsconfig.legacy.json && node ../../node_modules/typescript57/lib/tsc.js -p tests/registered-router-cycle/tsconfig.json", + "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js -p tsconfig.legacy.json && node ../../node_modules/typescript58/lib/tsc.js -p tests/registered-router-cycle/tsconfig.json", + "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js -p tsconfig.legacy.json && node ../../node_modules/typescript59/lib/tsc.js -p tests/registered-router-cycle/tsconfig.json", + "test:types:ts60": "tsc6 -p tsconfig.legacy.json && tsc6 -p tests/registered-router-cycle/tsconfig.json", + "test:types:ts70": "tsc -p tsconfig.legacy.json && tsc -p tests/registered-router-cycle/tsconfig.json", "test:unit": "vitest", "test:unit:dev": "pnpm run test:unit --watch --hideSkippedTests", "test:perf": "vitest bench", @@ -81,7 +81,17 @@ "default": "./dist/cjs/ssr/client.cjs" } }, - "./package.json": "./package.json" + "./package.json": "./package.json", + "./_internal/route-module": { + "import": { + "types": "./dist/esm/route-module-internal.d.ts", + "default": "./dist/esm/route-module-internal.js" + }, + "require": { + "types": "./dist/cjs/route-module-internal.d.cts", + "default": "./dist/cjs/route-module-internal.cjs" + } + } }, "sideEffects": false, "files": [ diff --git a/packages/react-router/src/Match.tsx b/packages/react-router/src/Match.tsx index db1d341ec4..8e84163119 100644 --- a/packages/react-router/src/Match.tsx +++ b/packages/react-router/src/Match.tsx @@ -1,5 +1,6 @@ 'use client' +import { resolveRouteId } from '@tanstack/router-core/_internal/route-module' import * as React from 'react' import { useSelector } from '@tanstack/react-store' import { isNotFound, rootRouteId } from '@tanstack/router-core' @@ -111,7 +112,10 @@ function matchView(router: ReturnType, match: AnyRouteMatch) { { error.routeId ??= match.routeId - if (error.routeId !== match.routeId) { + if ( + (resolveRouteId?.(router, error.routeId, match.routeId) ?? + error.routeId) !== match.routeId + ) { throw error } const notFoundElement = React.createElement( diff --git a/packages/react-router/src/Matches.tsx b/packages/react-router/src/Matches.tsx index a20c862b23..50c118769a 100644 --- a/packages/react-router/src/Matches.tsx +++ b/packages/react-router/src/Matches.tsx @@ -25,12 +25,14 @@ import type { MakeRouteMatchUnion, MaskOptions, MatchRouteOptions, + Register, RegisteredRouter, + RegisteredRouterOf, ResolveRoute, ToSubOptionsProps, } from '@tanstack/router-core' -declare module '@tanstack/router-core' { +declare module '@tanstack/router-core/extensions' { export interface RouteMatchExtensions { meta?: Array links?: Array @@ -134,6 +136,21 @@ export type UseMatchRouteOptions< MaskOptions & MatchRouteOptions +/** + * The signature of `useMatchRoute`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useMatchRoute` of this type. + */ +export type UseMatchRouteFn = < + TRouter extends AnyRouter = RegisteredRouterOf, +>() => < + const TFrom extends string = string, + const TTo extends string | undefined = undefined, + const TMaskFrom extends string = TFrom, + const TMaskTo extends string = '', +>( + opts: UseMatchRouteOptions, +) => false | Expand['types']['allParams']> + /** * Create a matcher function for testing locations against route definitions. * @@ -213,6 +230,20 @@ export type MakeMatchRouteOptions< | React.ReactNode } +/** + * The signature of `MatchRoute`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `MatchRoute` of this type. + */ +export type MatchRouteFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TFrom extends string = string, + const TTo extends string | undefined = undefined, + const TMaskFrom extends string = TFrom, + const TMaskTo extends string = '', +>( + props: MakeMatchRouteOptions, +) => any + /** * Component that conditionally renders its children based on whether a route * matches the provided `from`/`to` options. If `children` is a function, it @@ -252,6 +283,19 @@ export type UseMatchesResult< TSelected, > = unknown extends TSelected ? Array> : TSelected +/** + * The signature of `useMatches`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useMatches` of this type. + */ +export type UseMatchesFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TSelected = unknown, + TStructuralSharing extends boolean = boolean, +>( + opts?: UseMatchesBaseOptions & + StructuralSharingOption, +) => UseMatchesResult + export function useMatches< TRouter extends AnyRouter = RegisteredRouter, TSelected = unknown, @@ -280,6 +324,19 @@ export function useMatches< ) as UseMatchesResult } +/** + * The signature of `useParentMatches`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useParentMatches` of this type. + */ +export type UseParentMatchesFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TSelected = unknown, + TStructuralSharing extends boolean = boolean, +>( + opts?: UseMatchesBaseOptions & + StructuralSharingOption, +) => UseMatchesResult + /** * Read the presented route matches above the current match, or select a * derived value from them. @@ -306,6 +363,19 @@ export function useParentMatches< } as any) } +/** + * The signature of `useChildMatches`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useChildMatches` of this type. + */ +export type UseChildMatchesFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TSelected = unknown, + TStructuralSharing extends boolean = boolean, +>( + opts?: UseMatchesBaseOptions & + StructuralSharingOption, +) => UseMatchesResult + /** * Read the presented route matches below the current match, or select a * derived value from them. diff --git a/packages/react-router/src/fileRoute.ts b/packages/react-router/src/fileRoute.ts index f4d8c9b967..154422460c 100644 --- a/packages/react-router/src/fileRoute.ts +++ b/packages/react-router/src/fileRoute.ts @@ -64,6 +64,81 @@ export function createFileRoute< } } +/** + * The route factory returned by `createFileRoute(path)`. `TDefaultRegister` + * is the scope of the created route: the application's `Register`, or the + * scope register of a route module. + */ +export type FileRouteFactory< + TFilePath extends string, + TParentRoute extends AnyRoute, + TId extends RouteConstraints['TId'], + TPath extends RouteConstraints['TPath'], + TFullPath extends RouteConstraints['TFullPath'], + TDefaultRegister = Register, +> = < + TRegister = TDefaultRegister, + TSearchValidator = undefined, + TParams = ResolveParams, + TRouteContextFn = AnyContext, + TBeforeLoadFn = AnyContext, + TLoaderDeps extends Record = {}, + TLoaderFn = undefined, + TChildren = unknown, + TSSR = unknown, + const TMiddlewares = unknown, + THandlers = undefined, +>( + options?: FileBaseRouteOptions< + TRegister, + TParentRoute, + TId, + TPath, + TSearchValidator, + TParams, + TLoaderDeps, + TLoaderFn, + AnyContext, + TRouteContextFn, + TBeforeLoadFn, + AnyContext, + TSSR, + TMiddlewares, + THandlers + > & + UpdatableRouteOptions< + TParentRoute, + TId, + TFullPath, + TParams, + TSearchValidator, + TLoaderFn, + TLoaderDeps, + AnyContext, + TRouteContextFn, + TBeforeLoadFn + >, +) => Route< + TRegister, + TParentRoute, + TPath, + TFullPath, + TFilePath, + TId, + TSearchValidator, + TParams, + AnyContext, + TRouteContextFn, + TBeforeLoadFn, + TLoaderDeps, + TLoaderFn, + TChildren, + unknown, + TSSR, + TMiddlewares, + THandlers +> + /** @deprecated It's no longer recommended to use the `FileRoute` class directly. Instead, use `createFileRoute('/path/to/file')(options)` to create a file route. @@ -85,68 +160,13 @@ export class FileRoute< this.silent = _opts?.silent } - createRoute = < - TRegister = Register, - TSearchValidator = undefined, - TParams = ResolveParams, - TRouteContextFn = AnyContext, - TBeforeLoadFn = AnyContext, - TLoaderDeps extends Record = {}, - TLoaderFn = undefined, - TChildren = unknown, - TSSR = unknown, - const TMiddlewares = unknown, - THandlers = undefined, - >( - options?: FileBaseRouteOptions< - TRegister, - TParentRoute, - TId, - TPath, - TSearchValidator, - TParams, - TLoaderDeps, - TLoaderFn, - AnyContext, - TRouteContextFn, - TBeforeLoadFn, - AnyContext, - TSSR, - TMiddlewares, - THandlers - > & - UpdatableRouteOptions< - TParentRoute, - TId, - TFullPath, - TParams, - TSearchValidator, - TLoaderFn, - TLoaderDeps, - AnyContext, - TRouteContextFn, - TBeforeLoadFn - >, - ): Route< - TRegister, - TParentRoute, - TPath, - TFullPath, + createRoute: FileRouteFactory< TFilePath, + TParentRoute, TId, - TSearchValidator, - TParams, - AnyContext, - TRouteContextFn, - TBeforeLoadFn, - TLoaderDeps, - TLoaderFn, - TChildren, - unknown, - TSSR, - TMiddlewares, - THandlers - > => { + TPath, + TFullPath + > = (options) => { if (process.env.NODE_ENV !== 'production') { if (!this.silent) { console.warn( @@ -192,7 +212,7 @@ export function FileRouteLoader< return (loaderFn) => loaderFn as any } -declare module '@tanstack/router-core' { +declare module '@tanstack/router-core/extensions' { export interface LazyRoute { useMatch: UseMatchRoute useRouteContext: UseRouteContextRoute diff --git a/packages/react-router/src/index.tsx b/packages/react-router/src/index.tsx index 23ebf57938..96d6bbbcb8 100644 --- a/packages/react-router/src/index.tsx +++ b/packages/react-router/src/index.tsx @@ -185,6 +185,8 @@ export type { ResolvedRedirect, MakeRouteMatch, MakeRouteMatchUnion, + KnownRouteMatchUnion, + ForeignRouteMatch, RouteMatch, AnyRouteMatch, RouteContextFn, @@ -269,9 +271,54 @@ export type { DefaultRouteTypes, RouteTypes, } from './route' +// `createFileRoute` returns router-core's `Route`, and `Route` above is this +// package's class: declarations name the type of file routes through this +// export, so they need no import of `@tanstack/router-core`. +export type { Route as RouteCore } from '@tanstack/router-core' export { createRouter, Router } from './router' +export type { + FileRoutesByPathEntry, + FileRouteScope, + RouteScope, +} from './routeModule' +export type { FileRouteFactory } from './fileRoute' +export type { + HostedRouter, + InstallationRoutesById, + MountedRoutesById, + ModuleRootRoute, + ModuleRootRouteOptions, + MountRouteModuleOptions, + RedirectFn, + RegisteredRouterOf, + ScopeRouter, + ScopedRouter, + ScopedRouterView, + ValidateRouteModuleMount, + ValidateRouteModuleMountPath, +} from '@tanstack/router-core' +export type { GetRouteApiFn } from './route' +export type { CreateLinkFn, LinkOptionsFn } from './link' +export type { NavigateComponentFn, UseNavigateFn } from './useNavigate' +export type { + MatchRouteFn, + UseChildMatchesFn, + UseMatchRouteFn, + UseMatchesFn, + UseParentMatchesFn, +} from './Matches' +export type { UseRouterFn } from './useRouter' +export type { UseMatchFn } from './useMatch' +export type { UseLoaderDataFn } from './useLoaderData' +export type { UseLoaderDepsFn } from './useLoaderDeps' +export type { UseSearchFn } from './useSearch' +export type { UseParamsFn } from './useParams' +export type { UseRouteContextFn } from './useRouteContext' +export type { UseLocationFn } from './useLocation' +export type { UseRouterStateFn } from './useRouterState' + export { lazyFn, SearchParamError } from '@tanstack/router-core' export { RouterProvider, RouterContextProvider } from './RouterProvider' diff --git a/packages/react-router/src/link.tsx b/packages/react-router/src/link.tsx index ce6a7ed9d1..0087ef991d 100644 --- a/packages/react-router/src/link.tsx +++ b/packages/react-router/src/link.tsx @@ -12,16 +12,20 @@ import { import { isServer } from '@tanstack/router-core/isServer' import { useRouter } from './useRouter' import { createLinkScope, matchContext } from './matchContext' - import type { ActiveOptions, AnyRouter, Constrain, LinkOptions, ParsedLocation, + Register, RegisteredRouter, + RegisteredRouterOf, + RouteModuleScope, RoutePaths, + ScopedRouteOptions, } from '@tanstack/router-core' + import type { ReactNode } from 'react' import type { ValidateLinkOptions, @@ -131,6 +135,17 @@ function resolveIsActive( * @returns React anchor props suitable for `` or custom components. * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useLinkPropsHook */ +export type UseLinkPropsFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TFrom extends string = string, + TTo extends string = '', + TMaskFrom extends string = TFrom, + TMaskTo extends string = '', +>( + options: UseLinkPropsOptions, + forwardedRef?: React.ForwardedRef, +) => React.ComponentPropsWithRef<'a'> + export function useLinkProps< TRouter extends AnyRouter = RegisteredRouter, const TFrom extends string = string, @@ -172,6 +187,9 @@ export function useLinkProps< host?: 'a' | React.ElementType, ): React.ComponentPropsWithRef<'a'> { const router = useRouter() + // The route of the nearest match: it scopes the links of a route, and + // module destinations resolve to the installation it belongs to. + const routeId = React.useContext(matchContext) // ========================================================================== // SERVER EARLY RETURN @@ -188,7 +206,7 @@ export function useLinkProps< // browser-build constant `isServer = false` and drop this server block, // together with `getServerLinkProps` and the key sets only it references. if (isServer ?? router.isServer) { - return getServerLinkProps(router, options, forwardedRef, host) + return getServerLinkProps(router, options, forwardedRef, host, routeId) } // ========================================================================== @@ -239,7 +257,14 @@ export function useLinkProps< onMouseEnter, onMouseLeave, onTouchStart, - } = options as typeof options & { to?: string } + // Route-module scope; constant for a given scoped component. + _module, + _fromRoute, + } = options as typeof options & { + to?: string + _module?: RouteModuleScope + _fromRoute?: string + } // eslint-disable-next-line react-hooks/rules-of-hooks const [stableSearch, stableParams, stableActiveOptions] = useStableValues( @@ -249,8 +274,6 @@ export function useLinkProps< ) // The links of a route share its location source. Links outside every // match share one that never departs. - // eslint-disable-next-line react-hooks/rules-of-hooks - const routeId = React.useContext(matchContext) const scope = ((router.stores._linkScopes ??= {})[routeId!] ??= createLinkScope(router, routeId)) @@ -270,7 +293,9 @@ export function useLinkProps< return [options, () => state] as const } - const dest = { ...options } as any + // The nearest route resolves module destinations to the installation + // the link renders under; other destinations ignore it. + const dest = { ...options, _nearestRoute: routeId } as any let source: ParsedLocation | undefined let state: LinkState let hydrationState: LinkState | undefined @@ -335,6 +360,8 @@ export function useLinkProps< options.state, options.mask, options.unsafeRelative, + _module, + _fromRoute, stableActiveOptions, disabled, ]) @@ -450,9 +477,14 @@ export function useLinkProps< cancelPreload(innerRef) // The current options carry the navigation controls; `dest` only - // contributes the location the link displays. Navigation builds again - // to run `validateSearch` before committing. - router.navigate({ ...options, _fromLocation: dest._fromLocation }) + // contributes the location the link displays and the installation of a + // module destination. Navigation builds again to run `validateSearch` + // before committing. + router.navigate({ + ...options, + _fromLocation: dest._fromLocation, + _nearestRoute: routeId, + }) } } @@ -504,6 +536,8 @@ const ROUTER_OPTION_KEYS = /* @__PURE__ */ new Set([ 'inactiveProps', 'activeOptions', '_asChild', + '_module', + '_fromRoute', ]) // Copies the element props. An object rest would test every key against the @@ -588,6 +622,7 @@ function getServerLinkProps( options: any, forwardedRef: React.ForwardedRef | undefined, host: 'a' | React.ElementType | undefined, + routeId: string | undefined, ): React.ComponentPropsWithRef<'a'> { const { to, disabled, activeOptions } = options as { to: string | undefined @@ -600,7 +635,13 @@ function getServerLinkProps( // Direct-scheme links need no route resolution. Blocked links still use // the shared inactive-prop merge so their server and client markup agree. const next = - directExternalLink === undefined ? router.buildLocation(options) : undefined + directExternalLink === undefined + ? router.buildLocation( + options._module === undefined + ? options + : { ...options, _nearestRoute: routeId }, + ) + : undefined const hrefOption = next ? getHrefOption(next, router, disabled) @@ -778,8 +819,9 @@ export type CreateLinkProps = LinkProps< export type LinkComponent< in out TComp, in out TDefaultFrom extends string = string, + in out TDefaultRegister = Register, > = < - TRouter extends AnyRouter = RegisteredRouter, + TRouter extends AnyRouter = RegisteredRouterOf, const TFrom extends string = TDefaultFrom, const TTo extends string | undefined = undefined, const TMaskFrom extends string = TFrom, @@ -790,10 +832,11 @@ export type LinkComponent< export interface LinkComponentRoute< in out TDefaultFrom extends string = string, + in out TDefaultRegister = Register, > { defaultFrom: TDefaultFrom; < - TRouter extends AnyRouter = RegisteredRouter, + TRouter extends AnyRouter = RegisteredRouterOf, const TTo extends string | undefined = undefined, const TMaskTo extends string = '', >( @@ -808,6 +851,14 @@ export interface LinkComponentRoute< ): React.ReactElement } +/** + * The signature of `createLink`, creating links typed against the router of `TDefaultRegister`. + * Route modules export a `createLink` of this type. + */ +export type CreateLinkFn = ( + Comp: Constrain ReactNode>, +) => LinkComponent + /** * Creates a typed Link-like component that preserves TanStack Router's * navigation semantics and type-safety while delegating rendering to the @@ -899,12 +950,12 @@ export type LinkOptionsFnOptions< ? ValidateLinkOptionsArray : ValidateLinkOptions -export type LinkOptionsFn = < +export type LinkOptionsFn = < const TOptions, - TRouter extends AnyRouter = RegisteredRouter, + TRouter extends AnyRouter = RegisteredRouterOf, >( options: LinkOptionsFnOptions, -) => TOptions +) => ScopedRouteOptions /** * Validate and reuse navigation options for `Link`, `navigate` or `redirect`. diff --git a/packages/react-router/src/matchContext.tsx b/packages/react-router/src/matchContext.tsx index 12db4dbada..0948eb8048 100644 --- a/packages/react-router/src/matchContext.tsx +++ b/packages/react-router/src/matchContext.tsx @@ -4,7 +4,7 @@ import * as React from 'react' import { _isRouteDeparting } from '@tanstack/router-core' import type { AnyRoute, AnyRouter, ParsedLocation } from '@tanstack/router-core' -declare module '@tanstack/router-core' { +declare module '@tanstack/router-core/extensions' { // Declaration merging requires the original type parameters. // eslint-disable-next-line unused-imports/no-unused-vars interface RouterStores { diff --git a/packages/react-router/src/route-module-internal.ts b/packages/react-router/src/route-module-internal.ts new file mode 100644 index 0000000000..3ac86d6306 --- /dev/null +++ b/packages/react-router/src/route-module-internal.ts @@ -0,0 +1,6 @@ +// Internal generated/framework wiring; use generated scopes to author modules. +export * from './routeModule' +export { + mountRouteModule, + getRouteModuleId, +} from '@tanstack/router-core/_internal/route-module' diff --git a/packages/react-router/src/route.tsx b/packages/react-router/src/route.tsx index 57dca9ef02..ad7e403db9 100644 --- a/packages/react-router/src/route.tsx +++ b/packages/react-router/src/route.tsx @@ -4,6 +4,7 @@ import { BaseRouteApi, notFound, } from '@tanstack/router-core' +import { getRouteNavigationScope } from '@tanstack/router-core/_internal/route-module' import React from 'react' import { useLoaderData } from './useLoaderData' import { useLoaderDeps } from './useLoaderDeps' @@ -24,6 +25,7 @@ import type { NotFoundRouteProps, Register, RegisteredRouter, + RegisteredRouterOf, ResolveFullPath, ResolveId, ResolveParams, @@ -48,7 +50,7 @@ import type { UseSearchRoute } from './useSearch' import type { UseRouteContextRoute } from './useRouteContext' import type { LinkComponentRoute } from './link' -declare module '@tanstack/router-core' { +declare module '@tanstack/router-core/extensions' { export interface UpdatableRouteOptionsExtensions { component?: RouteComponent errorComponent?: false | null | undefined | ErrorRouteComponent @@ -67,18 +69,31 @@ declare module '@tanstack/router-core' { export interface RouteExtensions< in out TId extends string, in out TFullPath extends string, + in out TRegister, > { - useMatch: UseMatchRoute - useRouteContext: UseRouteContextRoute - useSearch: UseSearchRoute - useParams: UseParamsRoute - useLoaderDeps: UseLoaderDepsRoute - useLoaderData: UseLoaderDataRoute - useNavigate: () => UseNavigateResult - Link: LinkComponentRoute + useMatch: UseMatchRoute + useRouteContext: UseRouteContextRoute + useSearch: UseSearchRoute + useParams: UseParamsRoute + useLoaderDeps: UseLoaderDepsRoute + useLoaderData: UseLoaderDataRoute + useNavigate: () => UseNavigateResult + Link: LinkComponentRoute } } +/** + * The signature of `getRouteApi`, typed against the router of `TDefaultRegister` unless a + * router type is passed explicitly. Route modules export a `getRouteApi` of + * this type. + */ +export type GetRouteApiFn = < + const TId, + TRouter extends AnyRouter = RegisteredRouterOf, +>( + id: ConstrainLiteral>, +) => RouteApi + /** * Returns a route-specific API that exposes type-safe hooks pre-bound * to a single route ID. Useful for consuming a route's APIs from files @@ -106,49 +121,64 @@ export class RouteApi< super({ id }) } - useMatch: UseMatchRoute = (opts) => { + useMatch: UseMatchRoute = (opts) => { return useMatch({ ...opts, from: this.id } as any) as any } - useRouteContext: UseRouteContextRoute = (opts) => { + useRouteContext: UseRouteContextRoute = (opts) => { return useRouteContext({ ...(opts as any), from: this.id }) } - useSearch: UseSearchRoute = (opts) => { + useSearch: UseSearchRoute = (opts) => { return useSearch({ ...opts, from: this.id } as any) } - useParams: UseParamsRoute = (opts) => { + useParams: UseParamsRoute = (opts) => { return useParams({ ...opts, from: this.id } as any) } - useLoaderDeps: UseLoaderDepsRoute = (opts) => { + useLoaderDeps: UseLoaderDepsRoute = (opts) => { return useLoaderDeps({ ...opts, from: this.id, strict: false } as any) } - useLoaderData: UseLoaderDataRoute = (opts) => { + useLoaderData: UseLoaderDataRoute = (opts) => { return useLoaderData({ ...opts, from: this.id, strict: false } as any) } useNavigate = (): UseNavigateResult< - RouteTypesById['fullPath'] + RouteTypesById['fullPath'], + { router: TRouter } > => { const router = useRouter() - return useNavigate({ from: router.routesById[this.id as string].fullPath }) + return useNavigate( + getRouteNavigationScope( + this.id as string, + router.routesById[this.id as string]?.fullPath, + ) as any, + ) as any } notFound = (opts?: NotFoundError) => { return notFound({ routeId: this.id as string, ...opts }) } - Link: LinkComponentRoute['fullPath']> = - React.forwardRef((props, ref: React.ForwardedRef) => { - const router = useRouter() - const fullPath = router.routesById[this.id as string].fullPath - return - }) as unknown as LinkComponentRoute< - RouteTypesById['fullPath'] - > + Link: LinkComponentRoute< + RouteTypesById['fullPath'], + { router: TRouter } + > = React.forwardRef((props, ref: React.ForwardedRef) => { + const router = useRouter() + const fullPath = router.routesById[this.id as string]?.fullPath + return ( + + ) + }) as unknown as LinkComponentRoute< + RouteTypesById['fullPath'], + { router: TRouter } + > } export class Route< @@ -246,39 +276,47 @@ export class Route< super(options) } - useMatch: UseMatchRoute = (opts) => { + useMatch: UseMatchRoute = (opts) => { return useMatch({ ...opts, from: this.id } as any) as any } - useRouteContext: UseRouteContextRoute = (opts?) => { + useRouteContext: UseRouteContextRoute = (opts?) => { return useRouteContext({ ...(opts as any), from: this.id }) } - useSearch: UseSearchRoute = (opts) => { + useSearch: UseSearchRoute = (opts) => { return useSearch({ ...opts, from: this.id } as any) } - useParams: UseParamsRoute = (opts) => { + useParams: UseParamsRoute = (opts) => { return useParams({ ...opts, from: this.id } as any) } - useLoaderDeps: UseLoaderDepsRoute = (opts) => { + useLoaderDeps: UseLoaderDepsRoute = (opts) => { return useLoaderDeps({ ...opts, from: this.id } as any) } - useLoaderData: UseLoaderDataRoute = (opts) => { + useLoaderData: UseLoaderDataRoute = (opts) => { return useLoaderData({ ...opts, from: this.id } as any) } - useNavigate = (): UseNavigateResult => { - return useNavigate({ from: this.fullPath }) + useNavigate = (): UseNavigateResult => { + return useNavigate( + getRouteNavigationScope(this.id, this.fullPath) as any, + ) as any } - Link: LinkComponentRoute = React.forwardRef( + Link: LinkComponentRoute = React.forwardRef( (props, ref: React.ForwardedRef) => { - return + return ( + + ) }, - ) as unknown as LinkComponentRoute + ) as unknown as LinkComponentRoute } /** @@ -503,39 +541,39 @@ export class RootRoute< super(options) } - useMatch: UseMatchRoute = (opts) => { + useMatch: UseMatchRoute = (opts) => { return useMatch({ ...opts, from: this.id } as any) as any } - useRouteContext: UseRouteContextRoute = (opts) => { + useRouteContext: UseRouteContextRoute = (opts) => { return useRouteContext({ ...(opts as any), from: this.id }) } - useSearch: UseSearchRoute = (opts) => { + useSearch: UseSearchRoute = (opts) => { return useSearch({ ...opts, from: this.id } as any) } - useParams: UseParamsRoute = (opts) => { + useParams: UseParamsRoute = (opts) => { return useParams({ ...opts, from: this.id } as any) } - useLoaderDeps: UseLoaderDepsRoute = (opts) => { + useLoaderDeps: UseLoaderDepsRoute = (opts) => { return useLoaderDeps({ ...opts, from: this.id } as any) } - useLoaderData: UseLoaderDataRoute = (opts) => { + useLoaderData: UseLoaderDataRoute = (opts) => { return useLoaderData({ ...opts, from: this.id } as any) } - useNavigate = (): UseNavigateResult<'/'> => { - return useNavigate({ from: this.fullPath }) + useNavigate = (): UseNavigateResult<'/', TRegister> => { + return useNavigate({ from: this.fullPath }) as any } - Link: LinkComponentRoute<'/'> = React.forwardRef( + Link: LinkComponentRoute<'/', TRegister> = React.forwardRef( (props, ref: React.ForwardedRef) => { return }, - ) as unknown as LinkComponentRoute<'/'> + ) as unknown as LinkComponentRoute<'/', TRegister> } /** diff --git a/packages/react-router/src/routeModule.tsx b/packages/react-router/src/routeModule.tsx new file mode 100644 index 0000000000..c5bca7aa76 --- /dev/null +++ b/packages/react-router/src/routeModule.tsx @@ -0,0 +1,441 @@ +import * as React from 'react' +import { notFound } from '@tanstack/router-core' +import { + bindRouteScopeOptions, + createScopedRedirect, + getInstallationRouteIdMapper, + getScopedRouterView, +} from '@tanstack/router-core/_internal/route-module' +import { Route, getRouteApi } from './route' +import { Link, useLinkProps } from './link' +import { useBlocker } from './useBlocker' +import { Navigate, useNavigate } from './useNavigate' +import { + MatchRoute, + useChildMatches, + useMatchRoute, + useMatches, + useParentMatches, +} from './Matches' +import { useRouter } from './useRouter' +import { matchContext } from './matchContext' +import { useMatch } from './useMatch' +import { useLoaderData } from './useLoaderData' +import { useLoaderDeps } from './useLoaderDeps' +import { useSearch } from './useSearch' +import { useParams } from './useParams' +import { useRouteContext } from './useRouteContext' +import { useLocation } from './useLocation' +import { useRouterState } from './useRouterState' +import type { UseBlockerFn } from './useBlocker' +import type { + AnyContext, + AnyRoute, + AnyRouter, + ModuleRootRoute, + ModuleRootRouteOptions, + NotFoundError, + RedirectFn, + RouteIds, + ScopedRouterView, +} from '@tanstack/router-core' +import type { FileRouteFactory } from './fileRoute' +import type { GetRouteApiFn } from './route' +import type { + CreateLinkFn, + LinkComponent, + LinkOptionsFn, + UseLinkPropsFn, +} from './link' +import type { NavigateComponentFn, UseNavigateFn } from './useNavigate' +import type { + MatchRouteFn, + UseChildMatchesFn, + UseMatchRouteFn, + UseMatchesFn, + UseParentMatchesFn, +} from './Matches' +import type { UseMatchFn } from './useMatch' +import type { UseLoaderDataFn } from './useLoaderData' +import type { UseLoaderDepsFn } from './useLoaderDeps' +import type { UseSearchFn } from './useSearch' +import type { UseParamsFn } from './useParams' +import type { UseRouteContextFn } from './useRouteContext' +import type { UseLocationFn } from './useLocation' +import type { UseRouterStateFn } from './useRouterState' + +/** An entry of a generated module-local `FileRoutesByPath` interface. */ +export interface FileRoutesByPathEntry { + id: string + path: string + fullPath: string + parentRoute: AnyRoute +} + +// Entries reference the route files, whose types depend on these factories: +// read one property at a time and never constrain or check whole entries. +type FileRouteEntry = + TFileRoutesByPath[TFilePath & keyof TFileRoutesByPath] +type FileRouteParent = + FileRouteEntry extends { + parentRoute: infer TParentRoute extends AnyRoute + } + ? TParentRoute + : never +type FileRouteId = + FileRouteEntry extends { + id: infer TId extends string + } + ? TId + : never +type FileRoutePath = + FileRouteEntry extends { + path: infer TPath extends string + } + ? TPath + : never +type FileRouteFullPath = + FileRouteEntry extends { + fullPath: infer TFullPath extends string + } + ? TFullPath + : never + +/** + * Route factories of a route module, typed against the module's generated + * `FileRoutesByPath` and its scope register instead of the application's + * global registrations. + */ +export interface FileRouteScope< + TFileRoutesByPath, + TRegister, + TModuleId extends string, +> { + /** `createFileRoute`, typed against the module's own route files. */ + createFileRoute: ( + path?: TFilePath, + ) => FileRouteFactory< + FileRouteId, + FileRouteParent, + FileRouteId, + FileRoutePath, + FileRouteFullPath, + TRegister + > + /** + * Creates the module root. `TRouterContext` is the router context the module + * requires from the route it is mounted under. + */ + createModuleRoot: () => < + TRouteContextFn = AnyContext, + TBeforeLoadFn = AnyContext, + TSearchValidator = undefined, + TLoaderDeps extends Record = {}, + TLoaderFn = undefined, + TSSR = unknown, + const TServerMiddlewares = unknown, + THandlers = undefined, + >( + options?: ModuleRootRouteOptions< + TModuleId, + TRegister, + TSearchValidator, + TRouterContext, + TRouteContextFn, + TBeforeLoadFn, + TLoaderDeps, + TLoaderFn, + TSSR, + TServerMiddlewares, + THandlers + >, + ) => ModuleRootRoute< + TModuleId, + TRegister, + TSearchValidator, + TRouterContext, + TRouteContextFn, + TBeforeLoadFn, + TLoaderDeps, + TLoaderFn, + unknown, + unknown, + TSSR, + TServerMiddlewares, + THandlers + > +} + +/** Binds only the module-root factory used by generated route scopes. */ +export function bindCreateModuleRoot( + moduleId: TModuleId, +): FileRouteScope['createModuleRoot'] { + return () => (options) => + new Route({ ...(options as any), _module: moduleId }) as any +} + +/** + * The routing APIs of a route scope, typed against `TRouter`. + * + * Path-based APIs (`Link`, `useNavigate`, `redirect`, ...) address routes by + * the module-local paths of the module: they work wherever the module is + * mounted. Id-based APIs (`useMatch`, `getRouteApi`, ...) take qualified route + * ids such as `@acme/products:/$productId`. + */ +export interface RouteScope { + Link: LinkComponent<'a', string, { router: TRouter }> + createLink: CreateLinkFn<{ router: TRouter }> + linkOptions: LinkOptionsFn<'a', { router: TRouter }> + Navigate: NavigateComponentFn<{ router: TRouter }> + useNavigate: UseNavigateFn<{ router: TRouter }> + useLinkProps: UseLinkPropsFn<{ router: TRouter }> + useBlocker: UseBlockerFn<{ router: TRouter }> + notFound: ( + options?: Omit & { + routeId?: RouteIds + }, + ) => NotFoundError + redirect: RedirectFn<{ router: TRouter }> + MatchRoute: MatchRouteFn<{ router: TRouter }> + useMatchRoute: UseMatchRouteFn<{ router: TRouter }> + /** + * The router, viewed from the module: its `navigate`, `buildLocation`, + * `preloadRoute` and `matchRoute` take module-local paths. + */ + useRouter: (opts?: { warn?: boolean }) => ScopedRouterView + getRouteApi: GetRouteApiFn<{ router: TRouter }> + useMatch: UseMatchFn<{ router: TRouter }> + useMatches: UseMatchesFn<{ router: TRouter }> + useParentMatches: UseParentMatchesFn<{ router: TRouter }> + useChildMatches: UseChildMatchesFn<{ router: TRouter }> + useLoaderData: UseLoaderDataFn<{ router: TRouter }> + useLoaderDeps: UseLoaderDepsFn<{ router: TRouter }> + useSearch: UseSearchFn<{ router: TRouter }> + useParams: UseParamsFn<{ router: TRouter }> + useRouteContext: UseRouteContextFn<{ router: TRouter }> + useLocation: UseLocationFn<{ router: TRouter }> + useRouterState: UseRouterStateFn<{ router: TRouter }> +} + +// Each generated ESM export binds only its own API. These functions allocate +// closures/components; they never access a router or register runtime state. +function useBoundOptions(moduleId: string): (options: any) => any { + const router = useRouter() + const routeId = React.useContext(matchContext) + return React.useCallback( + (options: any) => + bindRouteScopeOptions(moduleId, options ?? {}, router, routeId), + [moduleId, router, routeId], + ) +} + +function bindIdHook(moduleId: string, hook: (options: any) => any) { + const toInstallation = getInstallationRouteIdMapper(moduleId) + return toInstallation + ? (options?: { from?: string }) => + hook({ ...options, from: toInstallation(options?.from) }) + : hook +} + +export function bindRouteScopeLink( + moduleId: string, +): RouteScope['Link'] { + const AnyLink = Link as React.ComponentType + return React.forwardRef((props, ref) => { + const bind = useBoundOptions(moduleId) + return + }) as any +} + +export function bindRouteScopeCreateLink( + moduleId: string, +): RouteScope['createLink'] { + const AnyLink = Link as React.ComponentType + return ((Comp: unknown) => + React.forwardRef((props, ref) => { + const bind = useBoundOptions(moduleId) + return + })) as any +} + +export function bindRouteScopeNavigate( + moduleId: string, +): RouteScope['Navigate'] { + const AnyNavigate = Navigate as React.ComponentType + return function ScopedNavigate(props: object) { + const bind = useBoundOptions(moduleId) + return + } as any +} + +export function bindRouteScopeMatchRoute( + moduleId: string, +): RouteScope['MatchRoute'] { + const AnyMatchRoute = MatchRoute as React.ComponentType + return function ScopedMatchRoute(props: object) { + const bind = useBoundOptions(moduleId) + const routeId = React.useContext(matchContext) + return + } as any +} + +export function bindRouteScopeUseLinkProps( + moduleId: string, +): RouteScope['useLinkProps'] { + return function useScopedLinkProps( + options: any, + ref: React.ForwardedRef, + ) { + return useLinkProps(useBoundOptions(moduleId)(options), ref) + } as any +} + +export function bindRouteScopeLinkOptions( + moduleId: string, +): RouteScope['linkOptions'] { + return ((options: any) => + Array.isArray(options) + ? options.map((option) => bindRouteScopeOptions(moduleId, option)) + : bindRouteScopeOptions(moduleId, options)) as any +} + +export function bindRouteScopeUseNavigate( + moduleId: string, +): RouteScope['useNavigate'] { + return function useScopedNavigate(options?: any) { + const bind = useBoundOptions(moduleId) + const navigate = useNavigate(bind(options)) + return React.useCallback( + (next: any) => navigate(bind(next)), + [navigate, bind], + ) + } as any +} + +export function bindRouteScopeRedirect( + moduleId: string, +): RouteScope['redirect'] { + return createScopedRedirect(moduleId) +} + +export function bindRouteScopeUseMatchRoute( + moduleId: string, +): RouteScope['useMatchRoute'] { + return function useScopedMatchRoute() { + const bind = useBoundOptions(moduleId) + const matchRoute = useMatchRoute() + const routeId = React.useContext(matchContext) + return React.useCallback( + (options: any) => + matchRoute({ ...bind(options), _nearestRoute: routeId }), + [matchRoute, bind, routeId], + ) + } as any +} + +export function bindRouteScopeUseRouter( + moduleId: string, +): RouteScope['useRouter'] { + return function useScopedRouter(options?: { warn?: boolean }) { + return getScopedRouterView( + useRouter(options), + moduleId, + React.useContext(matchContext), + ) + } as any +} + +export function bindRouteScopeGetRouteApi( + moduleId: string, +): RouteScope['getRouteApi'] { + const toInstallation = getInstallationRouteIdMapper(moduleId) + return ( + toInstallation + ? (id: string) => getRouteApi(toInstallation(id) as never) + : getRouteApi + ) as any +} + +export function bindRouteScopeUseMatch( + moduleId: string, +): RouteScope['useMatch'] { + return bindIdHook(moduleId, useMatch) as any +} + +export function bindRouteScopeUseLoaderData( + moduleId: string, +): RouteScope['useLoaderData'] { + return bindIdHook(moduleId, useLoaderData) as any +} + +export function bindRouteScopeUseLoaderDeps( + moduleId: string, +): RouteScope['useLoaderDeps'] { + return bindIdHook(moduleId, useLoaderDeps) as any +} + +export function bindRouteScopeUseSearch( + moduleId: string, +): RouteScope['useSearch'] { + return bindIdHook(moduleId, useSearch) as any +} + +export function bindRouteScopeUseParams( + moduleId: string, +): RouteScope['useParams'] { + return bindIdHook(moduleId, useParams) as any +} + +export function bindRouteScopeUseRouteContext( + moduleId: string, +): RouteScope['useRouteContext'] { + return bindIdHook(moduleId, useRouteContext) as any +} + +export function bindRouteScopeUseMatches( + _moduleId: string, +): RouteScope['useMatches'] { + return useMatches as any +} + +export function bindRouteScopeUseParentMatches( + _moduleId: string, +): RouteScope['useParentMatches'] { + return useParentMatches as any +} + +export function bindRouteScopeUseChildMatches( + _moduleId: string, +): RouteScope['useChildMatches'] { + return useChildMatches as any +} + +export function bindRouteScopeUseLocation( + _moduleId: string, +): RouteScope['useLocation'] { + return useLocation as any +} + +export function bindRouteScopeUseRouterState( + _moduleId: string, +): RouteScope['useRouterState'] { + return useRouterState as any +} + +export function bindRouteScopeUseBlocker( + _moduleId: string, +): RouteScope['useBlocker'] { + return useBlocker as any +} + +export function bindRouteScopeNotFound( + moduleId: string, +): RouteScope['notFound'] { + const toInstallation = getInstallationRouteIdMapper(moduleId) + return ((options?: any) => + notFound( + toInstallation && options?.routeId + ? { ...options, routeId: toInstallation(options.routeId) } + : options, + )) as any +} diff --git a/packages/react-router/src/router.ts b/packages/react-router/src/router.ts index de5e89a9fb..041c8ac642 100644 --- a/packages/react-router/src/router.ts +++ b/packages/react-router/src/router.ts @@ -14,7 +14,7 @@ import type { RouteComponent, } from './route' -declare module '@tanstack/router-core' { +declare module '@tanstack/router-core/extensions' { export interface RouterOptionsExtensions { /** * The default `component` a route should use if no component is provided. diff --git a/packages/react-router/src/routerStores.ts b/packages/react-router/src/routerStores.ts index 3197f54681..853c1c21c4 100644 --- a/packages/react-router/src/routerStores.ts +++ b/packages/react-router/src/routerStores.ts @@ -7,7 +7,7 @@ import { isServer } from '@tanstack/router-core/isServer' import type { Readable } from '@tanstack/react-store' import type { GetStoreConfig } from '@tanstack/router-core' -declare module '@tanstack/router-core' { +declare module '@tanstack/router-core/extensions' { export interface RouterReadableStore extends Readable {} } export const getStoreFactory: GetStoreConfig = (opts) => { diff --git a/packages/react-router/src/ssr/serializer.ts b/packages/react-router/src/ssr/serializer.ts index 9a1743c18a..b04f8e1270 100644 --- a/packages/react-router/src/ssr/serializer.ts +++ b/packages/react-router/src/ssr/serializer.ts @@ -1,6 +1,6 @@ import type * as React from 'react' -declare module '@tanstack/router-core' { +declare module '@tanstack/router-core/extensions' { export interface SerializerExtensions { ReadableStream: React.JSX.Element } diff --git a/packages/react-router/src/useBlocker.tsx b/packages/react-router/src/useBlocker.tsx index 65636510c9..55e722c7d0 100644 --- a/packages/react-router/src/useBlocker.tsx +++ b/packages/react-router/src/useBlocker.tsx @@ -1,5 +1,6 @@ 'use client' +import { isServer } from '@tanstack/router-core/isServer' import * as React from 'react' import { useRouter } from './useRouter' import type { @@ -12,6 +13,8 @@ import type { AnyRouter, ParseRoute, RegisteredRouter, + RegisteredRouterOf, + RouteScopeMarker, } from '@tanstack/router-core' type ShouldBlockFnLocation< @@ -31,14 +34,21 @@ type AnyShouldBlockFnLocation = ShouldBlockFnLocation type MakeShouldBlockFnLocationUnion< TRouter extends AnyRouter = RegisteredRouter, TRoute extends AnyRoute = ParseRoute, -> = TRoute extends any +> = TRouter['routeTree'] extends RouteScopeMarker ? ShouldBlockFnLocation< - TRoute['id'], - TRoute['fullPath'], - TRoute['types']['allParams'], - TRoute['types']['fullSearchSchema'] + string, + string, + Record, + Record > - : never + : TRoute extends any + ? ShouldBlockFnLocation< + TRoute['id'], + TRoute['fullPath'], + TRoute['types']['allParams'], + TRoute['types']['fullSearchSchema'] + > + : never type BlockerResolver = | { @@ -130,6 +140,14 @@ function _resolveBlockerOpts( } } +/** The generated module hook observes navigation across the entire application. */ +export type UseBlockerFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TWithResolver extends boolean = false, +>( + opts: UseBlockerOpts, +) => TWithResolver extends true ? BlockerResolver : void + export function useBlocker< TRouter extends AnyRouter = RegisteredRouter, TWithResolver extends boolean = false, @@ -164,15 +182,22 @@ export function useBlocker( const router = useRouter() const { history } = router - const [resolver, setResolver] = React.useState({ + const idle: BlockerResolver = { status: 'idle', current: undefined, next: undefined, action: undefined, proceed: undefined, reset: undefined, - }) + } + if (isServer ?? router.isServer) { + return idle + } + // eslint-disable-next-line react-hooks/rules-of-hooks -- the server condition is static + const [resolver, setResolver] = React.useState(idle) + + // eslint-disable-next-line react-hooks/rules-of-hooks -- the server condition is static React.useEffect(() => { const blockerFnComposed = async (blockerFnArgs: BlockerFnArgs) => { function getLocation( diff --git a/packages/react-router/src/useLoaderData.tsx b/packages/react-router/src/useLoaderData.tsx index 755a39616e..f9781b260c 100644 --- a/packages/react-router/src/useLoaderData.tsx +++ b/packages/react-router/src/useLoaderData.tsx @@ -5,7 +5,9 @@ import type { } from './structuralSharing' import type { AnyRouter, + Register, RegisteredRouter, + RegisteredRouterOf, ResolveUseLoaderData, StrictOrFrom, UseLoaderDataResult, @@ -39,8 +41,8 @@ export type UseLoaderDataOptions< > & StructuralSharingOption -export type UseLoaderDataRoute = < - TRouter extends AnyRouter = RegisteredRouter, +export type UseLoaderDataRoute = < + TRouter extends AnyRouter = RegisteredRouterOf, TSelected = unknown, TStructuralSharing extends boolean = boolean, >( @@ -54,6 +56,26 @@ export type UseLoaderDataRoute = < StructuralSharingOption, ) => UseLoaderDataResult +/** + * The signature of `useLoaderData`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useLoaderData` of this type. + */ +export type UseLoaderDataFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TFrom extends string | undefined = undefined, + TStrict extends boolean = true, + TSelected = unknown, + TStructuralSharing extends boolean = boolean, +>( + opts: UseLoaderDataOptions< + TRouter, + TFrom, + TStrict, + TSelected, + TStructuralSharing + >, +) => UseLoaderDataResult + /** * Read and select the current route's loader data with type‑safety. * diff --git a/packages/react-router/src/useLoaderDeps.tsx b/packages/react-router/src/useLoaderDeps.tsx index 21e7267d4e..014c91efa0 100644 --- a/packages/react-router/src/useLoaderDeps.tsx +++ b/packages/react-router/src/useLoaderDeps.tsx @@ -5,7 +5,9 @@ import type { } from './structuralSharing' import type { AnyRouter, + Register, RegisteredRouter, + RegisteredRouterOf, ResolveUseLoaderDeps, StrictOrFrom, UseLoaderDepsResult, @@ -31,8 +33,8 @@ export type UseLoaderDepsOptions< UseLoaderDepsBaseOptions & StructuralSharingOption -export type UseLoaderDepsRoute = < - TRouter extends AnyRouter = RegisteredRouter, +export type UseLoaderDepsRoute = < + TRouter extends AnyRouter = RegisteredRouterOf, TSelected = unknown, TStructuralSharing extends boolean = boolean, >( @@ -40,6 +42,19 @@ export type UseLoaderDepsRoute = < StructuralSharingOption, ) => UseLoaderDepsResult +/** + * The signature of `useLoaderDeps`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useLoaderDeps` of this type. + */ +export type UseLoaderDepsFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TFrom extends string | undefined = undefined, + TSelected = unknown, + TStructuralSharing extends boolean = boolean, +>( + opts: UseLoaderDepsOptions, +) => UseLoaderDepsResult + /** * Read and select the current route's loader dependencies object. * diff --git a/packages/react-router/src/useLocation.tsx b/packages/react-router/src/useLocation.tsx index 5fa39fa92e..155dd88ea6 100644 --- a/packages/react-router/src/useLocation.tsx +++ b/packages/react-router/src/useLocation.tsx @@ -10,7 +10,9 @@ import type { } from './structuralSharing' import type { AnyRouter, + Register, RegisteredRouter, + RegisteredRouterOf, RouterState, } from '@tanstack/router-core' @@ -31,6 +33,19 @@ export type UseLocationResult< ? RouterState['location'] : TSelected +/** + * The signature of `useLocation`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useLocation` of this type. + */ +export type UseLocationFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TSelected = unknown, + TStructuralSharing extends boolean = boolean, +>( + opts?: UseLocationBaseOptions & + StructuralSharingOption, +) => UseLocationResult + /** * Read the current location from the router state with optional selection. * Useful for subscribing to just the pieces of location you care about. diff --git a/packages/react-router/src/useMatch.tsx b/packages/react-router/src/useMatch.tsx index 95a4aaa286..c6a8b6802d 100644 --- a/packages/react-router/src/useMatch.tsx +++ b/packages/react-router/src/useMatch.tsx @@ -3,6 +3,7 @@ import * as React from 'react' import { useSelector } from '@tanstack/react-store' import { invariant, replaceEqualDeep } from '@tanstack/router-core' +import { resolveRouteId } from '@tanstack/router-core/_internal/route-module' import { isServer } from '@tanstack/router-core/isServer' import { dummyMatchContext, matchContext } from './matchContext' import { useRouter } from './useRouter' @@ -14,7 +15,10 @@ import type { AnyRouter, MakeRouteMatch, MakeRouteMatchUnion, + Register, RegisteredRouter, + RegisteredRouterOf, + RouteScopeMarker, StrictOrFrom, ThrowConstraint, ThrowOrOptional, @@ -70,13 +74,17 @@ export interface UseMatchBaseOptions< TStructuralSharing extends boolean, > { select?: ( - match: MakeRouteMatch, + match: TRouter['routeTree'] extends RouteScopeMarker + ? TStrict extends true + ? MakeRouteMatch + : MakeRouteMatchUnion + : MakeRouteMatch, ) => ValidateSelected shouldThrow?: TThrow } -export type UseMatchRoute = < - TRouter extends AnyRouter = RegisteredRouter, +export type UseMatchRoute = < + TRouter extends AnyRouter = RegisteredRouterOf, TSelected = unknown, TStructuralSharing extends boolean = boolean, TThrow extends boolean = true, @@ -121,6 +129,28 @@ export type UseMatchResult< : MakeRouteMatchUnion : TSelected +/** + * The signature of `useMatch`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useMatch` of this type. + */ +export type UseMatchFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TFrom extends string | undefined = undefined, + TStrict extends boolean = true, + TThrow extends boolean = true, + TSelected = unknown, + TStructuralSharing extends boolean = boolean, +>( + opts: UseMatchOptions< + TRouter, + TFrom, + TStrict, + ThrowConstraint, + TSelected, + TStructuralSharing + >, +) => ThrowOrOptional, TThrow> + /** * Read and select the nearest or targeted route match. * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchHook @@ -143,11 +173,20 @@ export function useMatch< >, ): ThrowOrOptional, TThrow> { const router = useRouter() - const nearestRouteId = React.useContext( - opts.from ? dummyMatchContext : matchContext, + // `from` that is not a route of the router can be the module-local id of a + // module installed several times: it resolves through the nearest match. + const moduleFrom = + resolveRouteId && opts.from && !router.routesById[opts.from] + ? opts.from + : undefined + const nearestRouteId: string | undefined = React.useContext( + opts.from && !moduleFrom ? dummyMatchContext : matchContext, ) - const routeId = opts.from ?? nearestRouteId + const routeId = + resolveRouteId && moduleFrom + ? resolveRouteId(router, moduleFrom, nearestRouteId) + : (opts.from ?? nearestRouteId) const matchStore = router.stores.getMatchStore(routeId!) if (isServer ?? router.isServer) { diff --git a/packages/react-router/src/useNavigate.tsx b/packages/react-router/src/useNavigate.tsx index ce95e5b4c1..6e9d16950e 100644 --- a/packages/react-router/src/useNavigate.tsx +++ b/packages/react-router/src/useNavigate.tsx @@ -1,16 +1,34 @@ 'use client' import * as React from 'react' +import { isServer } from '@tanstack/router-core/isServer' +import { matchContext } from './matchContext' import { useLayoutEffect } from './utils' import { useRouter } from './useRouter' import type { AnyRouter, + CompatibleRouteScope, FromPathOption, NavigateOptions, + Register, RegisteredRouter, + RegisteredRouterOf, + RouteModuleScope, UseNavigateResult, } from '@tanstack/router-core' +/** + * The signature of `useNavigate`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useNavigate` of this type. + */ +export type UseNavigateFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TDefaultFrom extends string = string, +>(_defaultOpts?: { + from?: FromPathOption + _module?: RouteModuleScope> +}) => UseNavigateResult + /** * Imperative navigation hook. * @@ -30,20 +48,43 @@ export function useNavigate< TDefaultFrom extends string = string, >(_defaultOpts?: { from?: FromPathOption -}): UseNavigateResult { +}): UseNavigateResult { const router = useRouter() + // Route-module APIs also pass the internal `_module`/`_fromRoute` scope, + // which resolves to the installation of the nearest match. + const defaults = _defaultOpts as + | { from?: string; _module?: RouteModuleScope; _fromRoute?: string } + | undefined + const routeId = React.useContext(matchContext) return React.useCallback( (options: NavigateOptions) => { return router.navigate({ + _module: defaults?._module, + _fromRoute: defaults?._fromRoute, + _nearestRoute: routeId, ...options, - from: options.from ?? _defaultOpts?.from, + from: options.from ?? defaults?.from, }) }, - [_defaultOpts?.from, router], - ) as UseNavigateResult + [defaults?.from, defaults?._module, defaults?._fromRoute, routeId, router], + ) as UseNavigateResult } +/** + * The signature of `Navigate`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `Navigate` of this type. + */ +export type NavigateComponentFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TFrom extends string = string, + const TTo extends string | undefined = undefined, + const TMaskFrom extends string = TFrom, + const TMaskTo extends string = '', +>( + props: NavigateOptions, +) => null + /** * Component that triggers a navigation when rendered. Navigation executes * in an effect after mount/update. @@ -61,8 +102,13 @@ export function Navigate< const TMaskTo extends string = '', >(props: NavigateOptions): null { const router = useRouter() + if (isServer ?? router.isServer) { + return null + } + // eslint-disable-next-line react-hooks/rules-of-hooks -- the server condition is static const navigate = useNavigate() + // eslint-disable-next-line react-hooks/rules-of-hooks -- the server condition is static const previousPropsRef = React.useRef | null>(null) + // eslint-disable-next-line react-hooks/rules-of-hooks -- the server condition is static useLayoutEffect(() => { if (previousPropsRef.current !== props) { navigate(props) diff --git a/packages/react-router/src/useParams.tsx b/packages/react-router/src/useParams.tsx index 44a6e47f9d..6ea1c8711b 100644 --- a/packages/react-router/src/useParams.tsx +++ b/packages/react-router/src/useParams.tsx @@ -5,7 +5,9 @@ import type { } from './structuralSharing' import type { AnyRouter, + Register, RegisteredRouter, + RegisteredRouterOf, ResolveUseParams, StrictOrFrom, ThrowConstraint, @@ -45,8 +47,8 @@ export type UseParamsOptions< > & StructuralSharingOption -export type UseParamsRoute = < - TRouter extends AnyRouter = RegisteredRouter, +export type UseParamsRoute = < + TRouter extends AnyRouter = RegisteredRouterOf, TSelected = unknown, TStructuralSharing extends boolean = boolean, TThrow extends boolean = true, @@ -62,6 +64,31 @@ export type UseParamsRoute = < StructuralSharingOption, ) => ThrowOrOptional, TThrow> +/** + * The signature of `useParams`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useParams` of this type. + */ +export type UseParamsFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TFrom extends string | undefined = undefined, + TStrict extends boolean = true, + TThrow extends boolean = true, + TSelected = unknown, + TStructuralSharing extends boolean = boolean, +>( + opts: UseParamsOptions< + TRouter, + TFrom, + TStrict, + ThrowConstraint, + TSelected, + TStructuralSharing + >, +) => ThrowOrOptional< + UseParamsResult, + TThrow +> + /** * Access the current route's path parameters with type-safety. * diff --git a/packages/react-router/src/useRouteContext.ts b/packages/react-router/src/useRouteContext.ts index 0aed8720e6..3e5df91fc6 100644 --- a/packages/react-router/src/useRouteContext.ts +++ b/packages/react-router/src/useRouteContext.ts @@ -1,19 +1,34 @@ import { useMatch } from './useMatch' import type { AnyRouter, + Register, RegisteredRouter, + RegisteredRouterOf, UseRouteContextBaseOptions, UseRouteContextOptions, UseRouteContextResult, } from '@tanstack/router-core' -export type UseRouteContextRoute = < - TRouter extends AnyRouter = RegisteredRouter, +export type UseRouteContextRoute = < + TRouter extends AnyRouter = RegisteredRouterOf, TSelected = unknown, >( opts?: UseRouteContextBaseOptions, ) => UseRouteContextResult +/** + * The signature of `useRouteContext`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useRouteContext` of this type. + */ +export type UseRouteContextFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TFrom extends string | undefined = undefined, + TStrict extends boolean = true, + TSelected = unknown, +>( + opts: UseRouteContextOptions, +) => UseRouteContextResult + export function useRouteContext< TRouter extends AnyRouter = RegisteredRouter, const TFrom extends string | undefined = undefined, diff --git a/packages/react-router/src/useRouter.tsx b/packages/react-router/src/useRouter.tsx index 6708274c11..06785a1a43 100644 --- a/packages/react-router/src/useRouter.tsx +++ b/packages/react-router/src/useRouter.tsx @@ -2,7 +2,22 @@ import * as React from 'react' import { routerContext } from './routerContext' -import type { AnyRouter, RegisteredRouter } from '@tanstack/router-core' +import type { + AnyRouter, + Register, + RegisteredRouter, + RegisteredRouterOf, +} from '@tanstack/router-core' + +/** + * The signature of `useRouter`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useRouter` of this type. + */ +export type UseRouterFn = < + TRouter extends AnyRouter = RegisteredRouterOf, +>(opts?: { + warn?: boolean +}) => TRouter /** * Access the current TanStack Router instance from React context. diff --git a/packages/react-router/src/useRouterState.tsx b/packages/react-router/src/useRouterState.tsx index fa17ee9f59..afdd858a59 100644 --- a/packages/react-router/src/useRouterState.tsx +++ b/packages/react-router/src/useRouterState.tsx @@ -6,7 +6,9 @@ import { useRouter } from './useRouter' import { useStructuralSharing } from './useMatch' import type { AnyRouter, + Register, RegisteredRouter, + RegisteredRouterOf, RouterState, } from '@tanstack/router-core' import type { @@ -30,6 +32,18 @@ export type UseRouterStateResult< TSelected, > = unknown extends TSelected ? RouterState : TSelected +/** + * The signature of `useRouterState`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useRouterState` of this type. + */ +export type UseRouterStateFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TSelected = unknown, + TStructuralSharing extends boolean = boolean, +>( + opts?: UseRouterStateOptions, +) => UseRouterStateResult + /** * Subscribe to the router's state store with optional selection and * structural sharing for render optimization. @@ -59,7 +73,7 @@ export function useRouterState< // The expression must stay inlined in the `if` so bundlers fold the // browser-build constant `isServer = false` and drop this server block. if (isServer ?? router.isServer) { - const state = router.stores.__store.get() as RouterState< + const state = router.stores.__store.get() as unknown as RouterState< TRouter['routeTree'] > return (opts?.select ? opts.select(state) : state) as UseRouterStateResult< diff --git a/packages/react-router/src/useSearch.tsx b/packages/react-router/src/useSearch.tsx index 3979967d76..7a3398e999 100644 --- a/packages/react-router/src/useSearch.tsx +++ b/packages/react-router/src/useSearch.tsx @@ -5,7 +5,9 @@ import type { } from './structuralSharing' import type { AnyRouter, + Register, RegisteredRouter, + RegisteredRouterOf, ResolveUseSearch, StrictOrFrom, ThrowConstraint, @@ -45,8 +47,8 @@ export type UseSearchOptions< > & StructuralSharingOption -export type UseSearchRoute = < - TRouter extends AnyRouter = RegisteredRouter, +export type UseSearchRoute = < + TRouter extends AnyRouter = RegisteredRouterOf, TSelected = unknown, TStructuralSharing extends boolean = boolean, TThrow extends boolean = true, @@ -62,6 +64,31 @@ export type UseSearchRoute = < StructuralSharingOption, ) => ThrowOrOptional, TThrow> +/** + * The signature of `useSearch`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useSearch` of this type. + */ +export type UseSearchFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TFrom extends string | undefined = undefined, + TStrict extends boolean = true, + TThrow extends boolean = true, + TSelected = unknown, + TStructuralSharing extends boolean = boolean, +>( + opts: UseSearchOptions< + TRouter, + TFrom, + TStrict, + ThrowConstraint, + TSelected, + TStructuralSharing + >, +) => ThrowOrOptional< + UseSearchResult, + TThrow +> + /** * Read and select the current route's search parameters with type-safety. * diff --git a/packages/react-router/tests/blocker-server.test.tsx b/packages/react-router/tests/blocker-server.test.tsx new file mode 100644 index 0000000000..752e638fbf --- /dev/null +++ b/packages/react-router/tests/blocker-server.test.tsx @@ -0,0 +1,33 @@ +import * as React from 'react' +import { afterEach, expect, test, vi } from 'vitest' +import { cleanup, render, screen } from '@testing-library/react' +import { + RouterContextProvider, + createMemoryHistory, + createRootRoute, + createRouter, + useBlocker, +} from '../src' + +afterEach(cleanup) + +test('a server router does not register navigation blockers', async () => { + const history = createMemoryHistory({ initialEntries: ['/'] }) + const block = vi.spyOn(history, 'block') + const router = createRouter({ + routeTree: createRootRoute(), + history, + isServer: true, + }) + function Observer() { + const state = useBlocker({ shouldBlockFn: () => true, withResolver: true }) + return {state.status} + } + render( + + + , + ) + await screen.findByText('idle') + expect(block).not.toHaveBeenCalled() +}) diff --git a/packages/react-router/tests/navigate-options-parity.test.tsx b/packages/react-router/tests/navigate-options-parity.test.tsx new file mode 100644 index 0000000000..7217d0e07e --- /dev/null +++ b/packages/react-router/tests/navigate-options-parity.test.tsx @@ -0,0 +1,96 @@ +import * as React from 'react' +import { renderToString } from 'react-dom/server' +import { afterEach, expect, test, vi } from 'vitest' +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react' +import { + Navigate, + Outlet, + RouterContextProvider, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(cleanup) + +test('Navigate leaves the request location unchanged during server rendering', () => { + const root = createRootRoute() + const next = createRoute({ getParentRoute: () => root, path: '/next' }) + const router = createRouter({ + routeTree: root.addChildren([next]), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, + }) + const navigate = vi.spyOn(router, 'navigate') + const html = renderToString( + + + Request content + , + ) + expect(html).toContain('Request content') + expect(navigate).not.toHaveBeenCalled() + expect(router.state.location.href).toBe('/') +}) + +test('Navigate responds to option changes while mounted', async () => { + function TestRoot() { + const [id, setId] = React.useState('one') + const [q, setQ] = React.useState('first') + const [replace, setReplace] = React.useState(true) + return ( + <> + + + + + + ) + } + const root = createRootRoute({ component: TestRoot }) + const item = createRoute({ getParentRoute: () => root, path: '/items/$id' }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createRouter({ routeTree: root.addChildren([item]), history }) + render() + await waitFor(() => + expect(router.state.location.href).toBe('/items/one?q=first'), + ) + const initialLength = history.length + await fireEvent.click(screen.getByText('Change params')) + await waitFor(() => + expect(router.state.location.href).toBe('/items/two?q=first'), + ) + expect(history.length).toBe(initialLength + 1) + await fireEvent.click(screen.getByText('Change search')) + await waitFor(() => + expect(router.state.location.href).toBe('/items/two?q=second'), + ) + expect(history.length).toBe(initialLength + 1) +}) diff --git a/packages/react-router/tests/registered-router-cycle/app.tsx b/packages/react-router/tests/registered-router-cycle/app.tsx new file mode 100644 index 0000000000..0d0199c346 --- /dev/null +++ b/packages/react-router/tests/registered-router-cycle/app.tsx @@ -0,0 +1,95 @@ +// A code-based app that registers its router in the same program and uses +// route-bound APIs inside its own routes. Resolving any of them must not need +// the registered router while the routes are still being inferred. +import * as React from 'react' +import { + Link, + Outlet, + createRootRoute, + createRoute, + createRouteMask, + createRouter, + useNavigate, +} from '@tanstack/react-router' + +const rootRoute = createRootRoute({ component: Root }) + +const itemRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/items/$itemId', + // Contextual types of lifecycle options name the registered router. + beforeLoad: ({ buildLocation }) => { + void buildLocation + }, + loader: ({ params, navigate }) => { + if (params.itemId === 'old') { + throw itemRoute.redirect({ to: '.', params: { itemId: 'new' } }) + } + void navigate + return { name: `item ${params.itemId}` } + }, + component: Item, +}) + +const publicRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/public/$name', + component: PublicItem, +}) + +const routeTree = rootRoute.addChildren([itemRoute, publicRoute]) + +const mask = createRouteMask({ + routeTree, + from: '/items/$itemId', + to: '/public/$name', + params: (previous) => ({ name: previous.itemId }), +}) + +export const router = createRouter({ routeTree, routeMasks: [mask] }) + +declare module '@tanstack/react-router' { + interface Register { + router: typeof router + } +} + +function Root() { + const navigate = useNavigate() + return ( + <> + + Item + + + + + ) +} + +function itemLink(index: number) { + return ( + + {index} + + ) +} + +function Item() { + const data = itemRoute.useLoaderData() + const params = itemRoute.useParams() + const navigate = itemRoute.useNavigate() + return ( +
+

{data.name}

+

{params.itemId}

+ + {[1, 2].map(itemLink)} +
+ ) +} + +function PublicItem() { + const { name } = publicRoute.useParams() + return {name} +} diff --git a/packages/react-router/tests/registered-router-cycle/tsconfig.json b/packages/react-router/tests/registered-router-cycle/tsconfig.json new file mode 100644 index 0000000000..182dbe2d9a --- /dev/null +++ b/packages/react-router/tests/registered-router-cycle/tsconfig.json @@ -0,0 +1,6 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { "noEmit": true }, + "include": ["app.tsx"], + "exclude": [] +} diff --git a/packages/react-router/tests/routeApi.test-d.tsx b/packages/react-router/tests/routeApi.test-d.tsx index d0553a9e0b..55ecb7c233 100644 --- a/packages/react-router/tests/routeApi.test-d.tsx +++ b/packages/react-router/tests/routeApi.test-d.tsx @@ -122,7 +122,7 @@ describe('getRouteApi', () => { test('Link', () => { const Link = invoiceRouteApi.Link expectTypeOf(Link).toEqualTypeOf< - LinkComponentRoute<'/invoices/$invoiceId'> + LinkComponentRoute<'/invoices/$invoiceId', { router: DefaultRouter }> >() }) }) diff --git a/packages/react-router/tsconfig.json b/packages/react-router/tsconfig.json index f406bf1c09..47c29de602 100644 --- a/packages/react-router/tsconfig.json +++ b/packages/react-router/tsconfig.json @@ -5,5 +5,6 @@ "jsxImportSource": "react", "types": ["node"] }, - "include": ["src", "tests", "vite.config.ts", "eslint.config.ts"] + "include": ["src", "tests", "vite.config.ts", "eslint.config.ts"], + "exclude": ["tests/registered-router-cycle"] } diff --git a/packages/react-router/vite.config.ts b/packages/react-router/vite.config.ts index 798d9b74e4..10453fca6a 100644 --- a/packages/react-router/vite.config.ts +++ b/packages/react-router/vite.config.ts @@ -28,6 +28,7 @@ export default mergeConfig( tsconfigPath: './tsconfig.build.json', entry: [ './src/index.tsx', + './src/route-module-internal.ts', './src/index.rsc.ts', './src/index.dev.tsx', './src/ssr/client.ts', diff --git a/packages/react-start-rsc/eslint.config.js b/packages/react-start-rsc/eslint.config.js index daf1baa88a..9ee915f52a 100644 --- a/packages/react-start-rsc/eslint.config.js +++ b/packages/react-start-rsc/eslint.config.js @@ -2,7 +2,7 @@ import pluginReact from '@eslint-react/eslint-plugin' import pluginReactHooks from 'eslint-plugin-react-hooks' -import rootConfig from '../../eslint.config.js' +import rootConfig, { routerCoreAugmentation } from '../../eslint.config.js' export default [ ...rootConfig, @@ -46,6 +46,7 @@ export default [ message: 'Dynamically import a dedicated @tanstack/start-server-core subpath instead of the root barrel.', }, + routerCoreAugmentation, ], }, }, diff --git a/packages/react-start-rsc/package.json b/packages/react-start-rsc/package.json index 60a10e16ae..c86ce17800 100644 --- a/packages/react-start-rsc/package.json +++ b/packages/react-start-rsc/package.json @@ -94,7 +94,7 @@ "src" ], "engines": { - "node": ">=22.12.0" + "node": ">=22.22.0" }, "dependencies": { "@tanstack/react-router": "workspace:*", diff --git a/packages/react-start-rsc/src/ServerComponentTypes.ts b/packages/react-start-rsc/src/ServerComponentTypes.ts index 5e1fa32a52..96b24de444 100644 --- a/packages/react-start-rsc/src/ServerComponentTypes.ts +++ b/packages/react-start-rsc/src/ServerComponentTypes.ts @@ -203,7 +203,7 @@ export interface RenderableServerComponentAttributes { [RENDERABLE_RSC]: true } -declare module '@tanstack/router-core' { +declare module '@tanstack/router-core/extensions' { export interface SerializableExtensions { CompositeComponent: AnyCompositeComponent RenderableServerComponent: AnyRenderableServerComponent diff --git a/packages/react-start/package.json b/packages/react-start/package.json index 02718a80fb..5f72517935 100644 --- a/packages/react-start/package.json +++ b/packages/react-start/package.json @@ -146,7 +146,13 @@ "default": "./dist/esm/client-only.js" } }, - "./package.json": "./package.json" + "./package.json": "./package.json", + "./_internal/route-module": { + "import": { + "types": "./dist/esm/route-module-internal.d.ts", + "default": "./dist/esm/route-module-internal.js" + } + } }, "sideEffects": false, "files": [ @@ -157,7 +163,7 @@ "!skills/_artifacts" ], "engines": { - "node": ">=22.12.0" + "node": ">=22.22.0" }, "dependencies": { "@tanstack/react-router": "workspace:*", diff --git a/packages/react-start/src/index.ts b/packages/react-start/src/index.ts index 6ea839a967..ce402094dd 100644 --- a/packages/react-start/src/index.ts +++ b/packages/react-start/src/index.ts @@ -1,5 +1,6 @@ export { useServerFn } from './useServerFn' export * from '@tanstack/start-client-core' +export type { StartModuleRequirements } from '@tanstack/start-client-core' // Explicit re-exports shadow `export *` above so these public-API names are // registered on the namespace at link time (via Vite SSR's `defineExport` // at fileStartIndex), surviving the cold-start SSR cycle through user diff --git a/packages/react-start/src/route-module-internal.ts b/packages/react-start/src/route-module-internal.ts new file mode 100644 index 0000000000..8642a07276 --- /dev/null +++ b/packages/react-start/src/route-module-internal.ts @@ -0,0 +1 @@ +export { createStartModule } from '@tanstack/start-client-core/_internal/route-module' diff --git a/packages/react-start/vite.config.ts b/packages/react-start/vite.config.ts index 652e4ef842..e6dac9bf27 100644 --- a/packages/react-start/vite.config.ts +++ b/packages/react-start/vite.config.ts @@ -26,6 +26,7 @@ export default mergeConfig( exclude: ['./src/default-entry'], entry: [ './src/index.ts', + './src/route-module-internal.ts', './src/client.tsx', './src/hydration.ts', './src/client-rpc.ts', diff --git a/packages/router-cli/package.json b/packages/router-cli/package.json index 2eebdcd9ae..a6822d7e95 100644 --- a/packages/router-cli/package.json +++ b/packages/router-cli/package.json @@ -63,7 +63,7 @@ "bin/**" ], "engines": { - "node": ">=20.19" + "node": ">=22.22.0" }, "dependencies": { "@tanstack/router-generator": "workspace:*", diff --git a/packages/router-core/package.json b/packages/router-core/package.json index ed2b794278..36644cdafb 100644 --- a/packages/router-core/package.json +++ b/packages/router-core/package.json @@ -48,6 +48,16 @@ "default": "./dist/cjs/index.cjs" } }, + "./extensions": { + "import": { + "types": "./dist/esm/extensions.d.ts", + "default": "./dist/esm/extensions.js" + }, + "require": { + "types": "./dist/cjs/extensions.d.cts", + "default": "./dist/cjs/extensions.cjs" + } + }, "./ssr/server": { "import": { "types": "./dist/esm/ssr/server.d.ts", @@ -168,7 +178,17 @@ "default": "./dist/cjs/scroll-restoration-script/server.cjs" } }, - "./package.json": "./package.json" + "./package.json": "./package.json", + "./_internal/route-module": { + "import": { + "types": "./dist/esm/route-module-internal.d.ts", + "default": "./dist/esm/route-module-internal.js" + }, + "require": { + "types": "./dist/cjs/route-module-internal.d.cts", + "default": "./dist/cjs/route-module-internal.cjs" + } + } }, "sideEffects": false, "files": [ diff --git a/packages/router-core/src/Matches.ts b/packages/router-core/src/Matches.ts index 41fd4018b5..185dbdeb51 100644 --- a/packages/router-core/src/Matches.ts +++ b/packages/router-core/src/Matches.ts @@ -7,7 +7,9 @@ import type { ParseRoute, RouteById, RouteIds, + RoutesById, } from './routeInfo' +import type { RouteScopeMarker } from './route-module' import type { AnyRouter, RegisteredRouter, SSROption } from './router' import type { Constrain } from './utils' @@ -126,6 +128,8 @@ export interface RouteMatch< > extends RouteMatchExtensions { id: string routeId: TRouteId + /** The authored route ID for module matches, independent of installation. */ + localRouteId?: string fullPath: TFullPath index: number pathname: string @@ -186,29 +190,76 @@ export type MakePreValidationErrorHandlingRouteMatchUnion< > = TRoute extends any ? PreValidationErrorHandlingRouteMatch< TRoute['id'], - TRoute['fullPath'], + MatchFullPath, TRoute['types']['allParams'], TRoute['types']['fullSearchSchema'] > : never +type LocalRouteId = TRouteId extends `/${string}` + ? never + : TRouteId extends `${infer TNamespace}:${infer TPath}` + ? TNamespace extends `${infer TModule}#${string}` + ? `${TModule}:${TPath}` + : TRouteId + : never + +type NonModuleRouteId = TRouteId extends `/${string}` + ? TRouteId + : TRouteId extends `${string}:${string}` + ? never + : TRouteId + +type ModuleMatchIdentity = string extends TRouteId + ? {} + : [NonModuleRouteId] extends [never] + ? { localRouteId: LocalRouteId } + : {} + +type MatchFullPath = [LocalRouteId] extends [ + never, +] + ? TFullPath + : string + +type InstalledRouteId = TRouteId extends `/${string}` + ? TRouteId + : TRouteId extends `${infer TModule}:${infer TPath}` + ? TModule extends `${string}#${string}` + ? TRouteId + : TRouteId | `${TModule}#${string}:${TPath}` + : TRouteId + +type MatchRouteId = + TRouteTree extends RouteScopeMarker + ? TModuleId extends `${infer TModule}#${string}` + ? TRouteId extends `${TModule}:${infer TPath}` + ? `${TModuleId}:${TPath}` + : InstalledRouteId + : InstalledRouteId + : TRouteId + export type MakeRouteMatchFromRoute = RouteMatch< - TRoute['types']['id'], - TRoute['types']['fullPath'], + InstalledRouteId, + MatchFullPath, TRoute['types']['allParams'], TRoute['types']['fullSearchSchema'], TRoute['types']['loaderData'], TRoute['types']['allContext'], TRoute['types']['loaderDeps'] -> +> & + ModuleMatchIdentity export type MakeRouteMatch< TRouteTree extends AnyRoute = RegisteredRouter['routeTree'], TRouteId = RouteIds, TStrict extends boolean = true, > = RouteMatch< - TRouteId, - RouteById['types']['fullPath'], + MatchRouteId, + MatchFullPath< + RouteById['id'], + RouteById['types']['fullPath'] + >, TStrict extends false ? AllParams : RouteById['types']['allParams'], @@ -222,25 +273,51 @@ export type MakeRouteMatch< ? AllContext : RouteById['types']['allContext'], RouteById['types']['loaderDeps'] -> +> & + ModuleMatchIdentity['id']> export type AnyRouteMatch = RouteMatch -export type MakeRouteMatchUnion< +/** A full-chain match whose route-specific contract is unknown to a scope. */ +export type ForeignRouteMatch = RouteMatch< + string, + string, + unknown, + unknown, + unknown, + unknown, + unknown +> + +type MatchRoutes = + TRouteTree extends RouteScopeMarker + ? ParseRoute + : Extract[keyof RoutesById], AnyRoute> + +/** The known routes only, used by generated scope membership guards. */ +export type KnownRouteMatchUnion< TRouter extends AnyRouter = RegisteredRouter, - TRoute extends AnyRoute = ParseRoute, + TRoute extends AnyRoute = MatchRoutes, > = TRoute extends any ? RouteMatch< - TRoute['id'], - TRoute['fullPath'], + MatchRouteId, + MatchFullPath, TRoute['types']['allParams'], TRoute['types']['fullSearchSchema'], TRoute['types']['loaderData'], TRoute['types']['allContext'], TRoute['types']['loaderDeps'] - > + > & + ModuleMatchIdentity : never +export type MakeRouteMatchUnion< + TRouter extends AnyRouter = RegisteredRouter, + TRoute extends AnyRoute = MatchRoutes, +> = + | KnownRouteMatchUnion + | (TRouter['routeTree'] extends RouteScopeMarker ? ForeignRouteMatch : never) + /** * The `MatchRouteOptions` type is used to describe the options that can be used when matching a route. * diff --git a/packages/router-core/src/RouterProvider.ts b/packages/router-core/src/RouterProvider.ts index 52aeaffabb..d9af27c92a 100644 --- a/packages/router-core/src/RouterProvider.ts +++ b/packages/router-core/src/RouterProvider.ts @@ -1,7 +1,8 @@ import type { NavigateOptions, ToOptions } from './link' import type { ParsedLocation } from './location' import type { RoutePaths } from './routeInfo' -import type { RegisteredRouter, ViewTransitionOptions } from './router' +import type { AnyRouter, Register, ViewTransitionOptions } from './router' +import type { RegisteredRouterOf } from './route-module' export interface MatchLocation { to?: string | number | null @@ -22,9 +23,11 @@ export interface CommitLocationOptions { ignoreBlocker?: boolean } -export type NavigateFn = < - TRouter extends RegisteredRouter, - TTo extends string | undefined, +export type NavigateFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + // A default equal to the constraint keeps the inference of a destination-less + // call unchanged while allowing the router type to have a default. + TTo extends string | undefined = string | undefined, TFrom extends RoutePaths | string = string, TMaskFrom extends RoutePaths | string = TFrom, TMaskTo extends string = '', @@ -32,9 +35,11 @@ export type NavigateFn = < opts: NavigateOptions, ) => Promise -export type BuildLocationFn = < - TRouter extends RegisteredRouter, - TTo extends string | undefined, +export type BuildLocationFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + // A default equal to the constraint keeps the inference of a destination-less + // call unchanged while allowing the router type to have a default. + TTo extends string | undefined = string | undefined, TFrom extends RoutePaths | string = string, TMaskFrom extends RoutePaths | string = TFrom, TMaskTo extends string = '', diff --git a/packages/router-core/src/extensions.ts b/packages/router-core/src/extensions.ts new file mode 100644 index 0000000000..fb8cbc0896 --- /dev/null +++ b/packages/router-core/src/extensions.ts @@ -0,0 +1,32 @@ +// The interfaces that framework packages augment: +// +// declare module '@tanstack/router-core/extensions' { +// interface UpdatableRouteOptionsExtensions { component?: RouteComponent } +// } +// +// Augment this entry, never `@tanstack/router-core` itself. An augmentation +// gives its module a name that TypeScript prefers when it writes types into +// declaration files. Augmenting the main entry would make a route module's +// `.d.ts` say `import("@tanstack/router-core").Route` instead of +// `import("@tanstack/react-router").RouteCore`, although the module only +// depends on `@tanstack/react-router`. Under pnpm the module's consumers then +// cannot resolve that import, and with `skipLibCheck` the type silently +// becomes `any`. +export type { LazyRoute } from './fileRoute' +export type { RouteMatchExtensions } from './Matches' +export type { + BeforeLoadContextOptions, + ErrorBoundaryTypes, + FilebaseRouteOptionsInterface, + LoaderFnContext, + RootRouteOptionsExtensions, + RouteExtensions, + RouteTypes, + UpdatableRouteOptionsExtensions, +} from './route' +export type { RouterOptionsExtensions } from './router' +export type { RouterReadableStore, RouterStores } from './stores' +export type { + SerializableExtensions, + SerializerExtensions, +} from './ssr/serializer/transformer' diff --git a/packages/router-core/src/index.ts b/packages/router-core/src/index.ts index 9206ef60dd..1c33c3050e 100644 --- a/packages/router-core/src/index.ts +++ b/packages/router-core/src/index.ts @@ -1,4 +1,24 @@ export * from './global' +// Exported through `./extensions` so that loading router-core loads that entry +// too: TypeScript does not load a module just because something augments it, +// and it ignores augmentations of modules it has not loaded. +export type { + BeforeLoadContextOptions, + ErrorBoundaryTypes, + FilebaseRouteOptionsInterface, + LazyRoute, + LoaderFnContext, + RootRouteOptionsExtensions, + RouteExtensions, + RouteMatchExtensions, + RouteTypes, + RouterOptionsExtensions, + RouterReadableStore, + RouterStores, + SerializableExtensions, + SerializerExtensions, + UpdatableRouteOptionsExtensions, +} from './extensions' export { TSR_DEFERRED_PROMISE, defer } from './defer' export type { DeferredPromiseState, DeferredPromise } from './defer' @@ -62,7 +82,6 @@ export type { FileRouteTypes, FileRoutesByPath, CreateFileRoute, - LazyRoute, LazyRouteOptions, CreateLazyFileRoute, } from './fileRoute' @@ -121,8 +140,9 @@ export type { IsMatchParse, IsMatch, RouteMatch, - RouteMatchExtensions, MakeRouteMatchUnion, + KnownRouteMatchUnion, + ForeignRouteMatch, MakeRouteMatch, AnyRouteMatch, MakeRouteMatchFromRoute, @@ -171,7 +191,6 @@ export type { ErrorRouteProps, ErrorComponentProps, DefaultErrorBoundaryTypes, - ErrorBoundaryTypes, NotFoundRouteProps, ResolveParams, ParseParamsFn, @@ -198,7 +217,6 @@ export type { ResolveAllParamsFromParent, AnyRoute, Route, - RouteTypes, FullSearchSchemaOption, RemountDepsOptions, MakeRemountDepsOptionsUnion, @@ -211,19 +229,14 @@ export type { LoaderStaleReloadMode, RouteLoaderFn, RouteLoaderEntry, - LoaderFnContext, RouteContextFn, ContextOptions, RouteContextOptions, SsrContextOptions, - BeforeLoadContextOptions, RootRouteOptions, - RootRouteOptionsExtensions, - UpdatableRouteOptionsExtensions, RouteConstraints, RouteTypesById, RouteMask, - RouteExtensions, RouteLazyFn, RouteAddChildrenFn, RouteAddFileChildrenFn, @@ -231,7 +244,6 @@ export type { ResolveOptionalParams, ResolveRequiredParams, RootRoute, - FilebaseRouteOptionsInterface, } from './route' export { createNonReactiveMutableStore, @@ -239,9 +251,7 @@ export { } from './stores' export type { RouterBatchFn, - RouterReadableStore, GetStoreConfig, - RouterStores, RouterWritableStore, } from './stores' export { @@ -269,7 +279,6 @@ export type { ListenerFn, RouterEvents, MatchRoutesOpts, - RouterOptionsExtensions, DefaultRemountDepsFn, PreloadRouteFn, MatchRouteFn, @@ -412,6 +421,7 @@ export type { UseLoaderDataResult, ResolveUseLoaderData } from './useLoaderData' export type { Redirect, + RedirectFn, RedirectOptions, RedirectOptionsRoute, RedirectFnRoute, @@ -419,6 +429,25 @@ export type { AnyRedirect, } from './redirect' +export type { + HostedRouter, + InstallationRoutesById, + MountedRoutesById, + ModuleRootRoute, + ModuleRootRouteOptions, + MountRouteModuleOptions, + RegisteredRouterOf, + ScopeRouter, + ScopedRouter, + CompatibleRouteScope, + ScopedRouteOptions, + RouteScopeMarker, + RouteModuleScope, + ScopedRouterView, + ValidateRouteModuleMount, + ValidateRouteModuleMountPath, +} from './route-module' + export { redirect, isRedirect, @@ -466,10 +495,8 @@ export type { AnySerializationAdapter, SerializationAdapter, ValidateSerializableInput, - SerializerExtensions, ValidateSerializable, RegisteredSerializableInput, - SerializableExtensions, DefaultSerializable, Serializable, TSR_SERIALIZABLE, diff --git a/packages/router-core/src/link.ts b/packages/router-core/src/link.ts index 799ae50811..bb68c10723 100644 --- a/packages/router-core/src/link.ts +++ b/packages/router-core/src/link.ts @@ -1,3 +1,4 @@ +import type { CompatibleRouteScope, RouteModuleScope } from './route-module' import type { HistoryState, ParsedHistoryState } from '@tanstack/history' import type { AllParams, @@ -18,6 +19,7 @@ import type { ViewTransitionOptions, } from './router' import type { + Assign, ConstrainLiteral, Expand, MakeDifferenceOptional, @@ -371,6 +373,22 @@ export interface MaskOptions< in out TMaskTo extends string, > { _fromLocation?: ParsedLocation + /** + * Internal: absolute `to`/`from` are local to this route module. Set by the + * scoped APIs of a route module; do not set it manually. + */ + _module?: RouteModuleScope> + /** + * Internal: resolve `from` as the current full path of the route with this + * id. Set by route-bound APIs of route-module routes. + */ + _fromRoute?: string + /** + * Internal: the route id of the caller's nearest match. `_module` and + * `_fromRoute` of a module installed several times resolve to the + * installation it belongs to. Set by the framework bindings. + */ + _nearestRoute?: string mask?: ToMaskOptions } @@ -379,6 +397,7 @@ export type ToMaskOptions< TMaskFrom extends string = string, TMaskTo extends string = '.', > = ToSubOptions & { + _module?: RouteModuleScope> unmaskOnReload?: boolean } @@ -503,11 +522,33 @@ type ResolveAllToParams< ? AllParams : FullSearchSchemaInput +/** + * The path params of a destination, with the host params of a route module + * installation for its `HostedRouter`. + */ +type WithHostParams = TRouter extends { + '~hostParams': infer THostParams +} + ? Assign + : TParams + export type ResolveToParams< TRouter extends AnyRouter, TParamVariant extends ParamVariant, TFrom, TTo, +> = TParamVariant extends 'PATH' + ? WithHostParams< + TRouter, + ResolveDestinationParams + > + : ResolveDestinationParams + +type ResolveDestinationParams< + TRouter extends AnyRouter, + TParamVariant extends ParamVariant, + TFrom, + TTo, > = ResolveRelativePath extends infer TPath ? undefined extends TPath diff --git a/packages/router-core/src/load-client.ts b/packages/router-core/src/load-client.ts index e84bb8fba5..b9ac22e335 100644 --- a/packages/router-core/src/load-client.ts +++ b/packages/router-core/src/load-client.ts @@ -8,6 +8,7 @@ import { runRouteLifecycle, } from './router' import { dehydrateSsrMatchId } from './ssr/ssr-match-id' +import { resolveRouteId } from './route-id' import type { GLOBAL_SEROVAL, GLOBAL_TSR } from './ssr/constants' import type { TsrSsrGlobal } from './ssr/types' import type { ParsedLocation } from './location' @@ -998,8 +999,18 @@ async function getNotFoundBoundary( const cause = indexed?.[1 /* outcome */][1 /* error or redirect */] as | NotFoundError | undefined - let index = cause?.routeId - ? matches.findIndex((match) => match.routeId === cause.routeId) + let routeId = cause?.routeId + // Module-local ids of a route module installed several times resolve in + // the installation of the match that threw. + if (resolveRouteId && routeId) { + routeId = resolveRouteId( + router, + routeId, + matches[indexed![0 /* index */]]?.routeId, + ) + } + let index = routeId + ? matches.findIndex((match) => match.routeId === routeId) : (indexed?.[0 /* index */] ?? matches.length - 1) if (index < 0) { index = 0 @@ -1092,6 +1103,11 @@ function materializeRedirect( while (outcome[0 /* kind */] === REDIRECTED) { const redirect = outcome[1 /* redirect */] const redirectOptions = redirect.options + // Module redirects resolve in the installation of the route that threw. + // Only route modules, which install `resolveRouteId`, read it. + if (resolveRouteId) { + redirectOptions._nearestRoute ??= route.id + } try { if (redirectOptions.href || redirect.headers.has('Location')) { router.resolveRedirect(redirect) diff --git a/packages/router-core/src/load-server.ts b/packages/router-core/src/load-server.ts index 325f8d63f7..15dbd3eadc 100644 --- a/packages/router-core/src/load-server.ts +++ b/packages/router-core/src/load-server.ts @@ -10,6 +10,7 @@ import { lifecycleEnd, runRouteLifecycle, } from './router' +import { resolveRouteId } from './route-id' import type { ParsedLocation } from './location' import type { AnyRouteMatch } from './Matches' import type { NotFoundError } from './not-found' @@ -132,6 +133,11 @@ function materializeRedirect( signal?.throwIfAborted() try { outcome[1].options._fromLocation = lane.location + // Module redirects resolve in the installation of the route that threw. + // Only route modules, which install `resolveRouteId`, read it. + if (resolveRouteId) { + outcome[1].options._nearestRoute ??= route.id + } router.resolveRedirect(outcome[1]) signal?.throwIfAborted() return outcome @@ -505,8 +511,14 @@ async function getNotFoundBoundary( fallback = 0, ): Promise { const cause = indexed?.[1][1] as NotFoundError | undefined - let index = cause?.routeId - ? matches.findIndex((match) => match.routeId === cause.routeId) + let routeId = cause?.routeId + // Module-local ids of a route module installed several times resolve in + // the installation of the match that threw. + if (resolveRouteId && routeId) { + routeId = resolveRouteId(router, routeId, matches[indexed![0]]?.routeId) + } + let index = routeId + ? matches.findIndex((match) => match.routeId === routeId) : (indexed?.[0] ?? matches.length - 1) if (index < 0) { index = 0 diff --git a/packages/router-core/src/redirect.ts b/packages/router-core/src/redirect.ts index dc6551d174..0065cf7a2b 100644 --- a/packages/router-core/src/redirect.ts +++ b/packages/router-core/src/redirect.ts @@ -1,5 +1,6 @@ import type { NavigateOptions } from './link' -import type { AnyRouter, RegisteredRouter } from './router' +import type { AnyRouter, Register, RegisteredRouter } from './router' +import type { RegisteredRouterOf } from './route-module' export type AnyRedirect = Redirect @@ -72,9 +73,12 @@ export type RedirectOptionsRoute< * This enables relative redirects like `Route.redirect({ to: './overview' })`. * @link [API Docs](https://tanstack.com/router/latest/docs/framework/react/api/router/RedirectType) */ -export interface RedirectFnRoute { +export interface RedirectFnRoute< + in out TDefaultFrom extends string = string, + in out TDefaultRegister = Register, +> { < - TRouter extends AnyRouter = RegisteredRouter, + TRouter extends AnyRouter = RegisteredRouterOf, const TTo extends string | undefined = undefined, const TMaskTo extends string = '', >( @@ -82,6 +86,20 @@ export interface RedirectFnRoute { ): Redirect } +/** + * The signature of `redirect`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `redirect` of this type. + */ +export type RedirectFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TTo extends string | undefined = '.', + const TFrom extends string = string, + const TMaskFrom extends string = TFrom, + const TMaskTo extends string = '', +>( + opts: RedirectOptions, +) => Redirect + /** * Create a redirect Response understood by TanStack Router. * diff --git a/packages/router-core/src/route-id.ts b/packages/router-core/src/route-id.ts new file mode 100644 index 0000000000..1395e6ae86 --- /dev/null +++ b/packages/router-core/src/route-id.ts @@ -0,0 +1,27 @@ +import type { AnyRouter } from './router' + +/** + * Resolves the id of the route whose matches the caller reads. Route modules + * address their routes by module-local ids such as `@acme/settings:/profile`; + * when the route tree installs the module several times, such an id resolves + * to the route of the installation of the caller's nearest match + * (`nearestRouteId`). Every other id is returned as it is. + * + * `mountRouteModule` installs it. It stays `undefined` in applications + * without route modules, so their bundles drop the code that resolves ids. + * Used by the framework bindings and route loading. + */ +export let resolveRouteId: + | (( + router: AnyRouter, + routeId: string, + nearestRouteId: string | undefined, + ) => string) + | undefined + +/** Called by `mountRouteModule`. */ +export function setResolveRouteId( + resolve: NonNullable, +): void { + resolveRouteId = resolve +} diff --git a/packages/router-core/src/route-module-internal.ts b/packages/router-core/src/route-module-internal.ts new file mode 100644 index 0000000000..41113f797a --- /dev/null +++ b/packages/router-core/src/route-module-internal.ts @@ -0,0 +1,4 @@ +// Internal generated/framework wiring; use generated scopes to author modules. +export * from './route-module' +export { resolveRouteId } from './route-id' +export { getParamNames, parseSegments } from './new-process-route-tree' diff --git a/packages/router-core/src/route-module.ts b/packages/router-core/src/route-module.ts new file mode 100644 index 0000000000..981fb25755 --- /dev/null +++ b/packages/router-core/src/route-module.ts @@ -0,0 +1,820 @@ +import { invariant } from './invariant' +import { redirect } from './redirect' +import { rootRouteId } from './root' +import { setResolveRouteId } from './route-id' +import { setScopeLocationOptions } from './router' +import type { RedirectFn } from './redirect' +import type { BuildLocationFn, NavigateFn } from './RouterProvider' +import type { AnyContext, AnyRoute, Route, RouteOptions } from './route' +import type { + AnyRouter, + Register, + RegisteredRouter, + RegisteredSsr, + RouterCore, +} from './router' +import type { ParseRoute } from './routeInfo' +import type { + RegisteredSSROption, + ValidateSerializableInput, +} from './ssr/serializer/transformer' +import type { LooseReturnType } from './utils' + +/** + * The router a route scope is typed against. + * + * A scope register (`{ router: TRouter }`) selects its router. Any other + * register, including `unknown` from code-based routes, falls back to the + * application's registered router. + */ +export type RegisteredRouterOf = TRegister extends { + router: infer TRouter extends AnyRouter +} + ? TRouter + : RegisteredRouter + +/** + * The router type of a route scope: the router of a route tree that contains + * the scope's routes, typed independently of the application that mounts it. + */ +export type ScopeRouter< + TRouteTree extends AnyRoute, + TModuleId extends string = string, +> = RouterCore, 'never', false> + +declare const routeScopeMarker: unique symbol + +/** Internal generated/framework wiring: An erased distinction between a provider scope and a host router. */ +export interface RouteScopeMarker { + [routeScopeMarker]: TModuleId +} + +/** Internal generated/framework wiring: Selects an installation without changing the provider's route types. */ +export type ScopedRouter = + Omit< + TRouter['routeTree'], + typeof routeScopeMarker + > extends infer TTree extends AnyRoute + ? ScopeRouter & + Pick> + : never + +/** Internal generated/framework wiring: The scope stamp accepted by a destination's consuming API. */ +export type CompatibleRouteScope = + TRouter['routeTree'] extends RouteScopeMarker + ? TModuleId extends `${infer TModule}#${string}` + ? TModuleId | TModule + : TModuleId | `${TModuleId}#${string}` + : string + +/** Internal generated/framework wiring: A receiver constraint is deferred only until an origin is available. */ +export type RouteModuleScope = + | TModuleId + | { + receiver: TModuleId + target: TModuleId + } + +type BoundScope = TOptions extends { + _module: infer TScope +} + ? TScope extends { receiver: string; target: string } + ? TScope + : TScope extends `${string}#${string}` + ? TModuleId extends `${string}#${string}` + ? TModuleId + : { receiver: TModuleId; target: TScope } + : TModuleId + : TModuleId + +/** Internal generated/framework wiring: Preserve scope identity through reusable options and spreads. */ +export type ScopedRouteOptions = + TRouter['routeTree'] extends RouteScopeMarker + ? TOptions extends ReadonlyArray + ? { + [TKey in keyof TOptions]: ScopedRouteOptions + } + : Omit & { + readonly _module: BoundScope + } + : TOptions + +/** + * The router of a route module as seen from where it is mounted: links into + * the module also take the path params of the routes above it (`THostParams`). + * Code inside the module uses its own router, which never has them. + */ +export type HostedRouter = TRouter & { + '~hostParams': THostParams +} + +/** + * Application route maps cannot infer final paths from a provider's local + * templates. Keep own identity and data precise; raw parent/child links point + * into the application graph rather than the provider's template graph. + */ +export type MountedRoutesById = { + [TId in keyof TRoutesById]: TRoutesById[TId] extends { + types: infer TTypes + options: infer TOptions + } + ? Omit< + TRoutesById[TId], + | 'path' + | 'fullPath' + | 'to' + | 'parentRoute' + | 'children' + | 'options' + | 'types' + > & { + readonly path: string | undefined + readonly fullPath: string + readonly to: string + parentRoute: AnyRoute + children?: Array + options: Omit & { + path: string | undefined + getParentRoute: () => AnyRoute + } + types: Omit< + TTypes, + 'path' | 'fullPath' | 'to' | 'parentRoute' | 'children' + > & { + path: string | undefined + fullPath: string + to: string + parentRoute: AnyRoute + children: Array | undefined + } + } + : TRoutesById[TId] +} + +/** + * The routes of one installation of a route module installed several times, + * by id: `#:/…` for each `:/…` of `TRoutesById`. + */ +export type InstallationRoutesById< + TRoutesById, + TModuleId extends string, + TAs extends string, +> = { + [TId in keyof TRoutesById as TId extends `${TModuleId}:${infer TPath}` + ? `${TModuleId}#${TAs}:${TPath}` + : TId]: TId extends `${TModuleId}:${infer TPath}` + ? InstallationRoute + : TRoutesById[TId] +} + +type InstallationRoute = TRoute extends { + types: infer TTypes +} + ? Omit & { + readonly id: TId + types: Omit & { id: TId } + } + : TRoute + +/** + * Options of a route module's root route (`createModuleRoot`). + * + * The root has no path or id of its own: the module id determines its id and + * the including route tree chooses where it is mounted. + */ +export interface ModuleRootRouteOptions< + TModuleId extends string, + TRegister, + TSearchValidator = undefined, + TRouterContext = {}, + TRouteContextFn = AnyContext, + TBeforeLoadFn = AnyContext, + TLoaderDeps extends Record = {}, + TLoaderFn = undefined, + TSSR = unknown, + TServerMiddlewares = unknown, + THandlers = undefined, +> extends Omit< + RouteOptions< + TRegister, + any, // TParentRoute: provided by the including tree + `${TModuleId}:`, // TId + `${TModuleId}:`, // TCustomId + '/', // TFullPath: module-local + '/', // TPath + TSearchValidator, + {}, // TParams + TLoaderDeps, + TLoaderFn, + TRouterContext, + TRouteContextFn, + TBeforeLoadFn, + TSSR, + TServerMiddlewares, + THandlers + >, + | 'path' + | 'id' + | 'getParentRoute' + | 'caseSensitive' + | 'parseParams' + | 'stringifyParams' + | 'params' + | '_module' + | '_uses' +> {} + +/** + * The root route of a route module. Its router context (`TRouterContext`) is + * the context the module requires from the route it is mounted under. + */ +export type ModuleRootRoute< + TModuleId extends string, + TRegister, + TSearchValidator = undefined, + TRouterContext = {}, + TRouteContextFn = AnyContext, + TBeforeLoadFn = AnyContext, + TLoaderDeps extends Record = {}, + TLoaderFn = undefined, + TChildren = unknown, + TFileRouteTypes = unknown, + TSSR = unknown, + TServerMiddlewares = unknown, + THandlers = undefined, +> = Route< + TRegister, + any, // TParentRoute + '/', // TPath + '/', // TFullPath + `${TModuleId}:`, // TCustomId + `${TModuleId}:`, // TId + TSearchValidator, + {}, // TParams + TRouterContext, + TRouteContextFn, + TBeforeLoadFn, + TLoaderDeps, + TLoaderFn, + TChildren, + TFileRouteTypes, + TSSR, + TServerMiddlewares, + THandlers +> + +/** + * Returns the id of the route module that owns a route, or `undefined` for + * routes that do not belong to a route module. + * + * Route-module routes have qualified ids such as `@acme/products:/$productId`; + * the module root's id is `@acme/products:`. Package names cannot contain + * `:`, and application route ids start with `/` (or are `__root__`). + */ +export function getRouteModuleId(routeId: string): string | undefined { + const index = routeId.indexOf(':') + return index > 0 && routeId[0] !== '/' ? routeId.slice(0, index) : undefined +} + +/** + * The route ids of a namespace of one installation of a module installed + * several times (`#`): the namespace takes the module's own + * ids (`:/…`) and addresses the routes of its installation. + * Returns `undefined` for the namespace of a module installed once. + */ +export function getInstallationRouteIdMapper( + namespaceId: string, +): ((routeId: T) => T) | undefined { + const separator = namespaceId.indexOf('#') + if (separator < 0) { + return undefined + } + const prefix = `${namespaceId.slice(0, separator)}:` + return (routeId) => + typeof routeId === 'string' && routeId.startsWith(prefix) + ? ((namespaceId + routeId.slice(separator)) as typeof routeId) + : routeId +} + +/** + * Navigation options that resolve a route-bound navigation from `route`. + * + * Application routes resolve relative destinations from their full path. + * Route-module routes resolve absolute destinations in their module and take + * `from` from the route's current full path, which depends on the mount. + */ +export function getRouteNavigationScope( + routeId: string, + fullPath: string | undefined, +): { from?: string; _module?: string; _fromRoute?: string } { + // The module id of a qualified route id (see `getRouteModuleId`), inlined: + // this runs in every route-bound API of every application. + const index = routeId.indexOf(':') + return index > 0 && routeId[0] !== '/' + ? { _module: routeId.slice(0, index), _fromRoute: routeId } + : { from: fullPath } +} + +type MissingKeys = Exclude & string + +type RouteModuleName = + TRoot['id'] extends `${infer TModuleId}:` ? TModuleId : TRoot['id'] + +/** + * Validates the mount path of a route module: it must be static, since links + * into the module could not provide path params of the mount path. + */ +export type ValidateRouteModuleMountPath< + TRoot extends AnyRoute, + TAt extends string, +> = TAt extends `${string}$${string}` + ? `Route module '${RouteModuleName}' must be mounted at a static path without path params` + : TAt + +type ValidateMountSearch< + TRoot extends AnyRoute, + TParent extends AnyRoute, +> = {} extends TParent['types']['fullSearchSchemaInput'] + ? {} + : { + '~mountSearchError': `Route module '${RouteModuleName}' cannot be mounted under '${TParent['id']}', which requires search params. Links into the module could not provide them.` + } + +type ValidateMountContext< + TRoot extends AnyRoute, + TParent extends AnyRoute, +> = TParent['types']['allContext'] extends TRoot['types']['routerContext'] + ? {} + : { + '~mountContextError': [ + MissingKeys< + TParent['types']['allContext'], + TRoot['types']['routerContext'] + >, + ] extends [never] + ? `Route module '${RouteModuleName}' requires router context that '${TParent['id']}' does not provide with compatible types` + : `Route module '${RouteModuleName}' requires router context '${MissingKeys< + TParent['types']['allContext'], + TRoot['types']['routerContext'] + >}' that '${TParent['id']}' does not provide` + } + +type ModuleParamKeys = + ParseRoute extends infer TRoute + ? TRoute extends AnyRoute + ? keyof TRoute['types']['params'] + : never + : never + +type ConflictingHostParams< + TRoot extends AnyRoute, + TParent extends AnyRoute, +> = Extract> & + string + +type ValidateMountParams = [ + ConflictingHostParams, +] extends [never] + ? {} + : { + '~mountParamsError': `Route module '${RouteModuleName}' cannot be mounted under '${TParent['id']}' because its routes overwrite host params '${ConflictingHostParams}'` + } + +type IsSerializableResult = [T] extends [ + ValidateSerializableInput, +] + ? true + : false + +/** The ids of a module's server-rendered routes with unserializable results. */ +type UnserializableRouteIds = + ParseRoute extends infer TRoute + ? TRoute extends AnyRoute + ? TRoute['types']['allSsr'] extends false + ? never + : IsSerializableResult extends false + ? TRoute['id'] + : IsSerializableResult< + LooseReturnType + > extends false + ? TRoute['id'] + : never + : never + : never + +/** + * In a server-rendering application (`Register['ssr']`), the loader and + * `beforeLoad` results of a module's server-rendered routes are serialized + * with the application's serialization adapters. The module is typed without + * them, so the mount checks every route. + */ +type ValidateMountLifecycle = + false extends RegisteredSsr + ? {} + : RegisteredSSROption extends false + ? {} + : [UnserializableRouteIds] extends [never] + ? {} + : { + '~mountSerializationError': `Route module '${RouteModuleName}' returns loader or beforeLoad results from '${UnserializableRouteIds & string}' that the application cannot serialize` + } + +/** + * Validates that a route module can be mounted under `TParent`. + * + * A module is checked against its own module-local types. Path params of the + * host chain carry over into the module's own links, and links from where the + * module is mounted pass them (`HostedRouter`). Required search params would + * not carry over, so the host chain must not have any. The host must provide + * the router context the module root requires, and a server-rendering + * application must be able to serialize the module's lifecycle results. + */ +export type ValidateRouteModuleMount< + TRoot extends AnyRoute, + TParent extends AnyRoute, +> = ValidateMountSearch & + ValidateMountContext & + ValidateMountParams & + ValidateMountLifecycle + +export interface MountRouteModuleOptions< + TRoot extends AnyRoute, + TParent extends AnyRoute, + TAt extends string, +> { + /** + * The host route the module root is mounted under. It must satisfy the + * module's requirements (see `ValidateRouteModuleMount`). + */ + // Validating on this property instead of the options object keeps the + // inference of `TAt` precise. + parent: (() => TParent) & ValidateRouteModuleMount + /** + * The static path of the module root relative to `parent`. Omit it (or use + * `'/'`) to mount the module without a path segment. + */ + at?: ValidateRouteModuleMountPath + /** + * The name of this installation when the route tree installs the module + * several times. The installation gets copies of the module's routes with + * ids `#:/…`; module code keeps addressing them by its own + * ids, which resolve to the installation it renders under. + */ + as?: string + /** + * The installations of modules installed several times that this + * installation links to, keyed by module id. + */ + uses?: Record +} + +/** + * Resolves a module-local route id of a module installed several times + * (`@acme/settings:/profile`) to the route of an installation + * (`@acme/settings#orgSettings:/profile`): the installation of the caller's + * nearest match, or the installation its module uses (`uses`). A route tree + * never matches two installations of one module at once, so the caller's + * match chain determines the installation. Every other id, including those of + * the router's routes, is returned as it is. + */ +function resolveModuleRouteId( + router: AnyRouter, + routeId: string, + nearestRouteId: string | undefined, +): string { + const index = routeId.indexOf(':') + const nearestIndex = nearestRouteId?.indexOf(':') ?? -1 + if ( + router.routesById[routeId] || + index <= 0 || + routeId[0] === '/' || + nearestIndex <= 0 || + nearestRouteId![0] === '/' + ) { + return routeId + } + const moduleId = routeId.slice(0, index) + const caller = nearestRouteId!.slice(0, nearestIndex) + const installation = caller.startsWith(`${moduleId}#`) + ? caller + : (router.routesById[`${caller}:`] as AnyRoute | undefined)?.options + ._uses?.[moduleId] + return installation === undefined + ? routeId + : installation + routeId.slice(index) +} + +/** + * Resolves the internal route-module options of a location build: + * - `_module`: absolute `to`/`from` (and mask `to`/`from`) are local to the + * module whose root has the id `<_module>:`; + * - `_fromRoute`: without an explicit `from`, resolve from the current full + * path of the route with this id; + * - `_nearestRoute`: both resolve to the installation of the caller (see + * `resolveModuleRouteId`). + */ +function scopeLocationOptions< + TOptions extends { + to?: unknown + from?: string + mask?: { to?: unknown; from?: string; _module?: RouteModuleScope } + _module?: RouteModuleScope + _fromRoute?: string + _nearestRoute?: string + }, +>(router: AnyRouter, opts: TOptions): TOptions { + // Only called with `_module` set (see `RouterCore.buildLocation`). + // Route/RouteApi consumers retain their authored origin even when reusable + // options supply a destination stamp. + if (opts._fromRoute) { + const index = opts._fromRoute.indexOf(':') + if (index > 0 && opts._fromRoute[0] !== '/') { + opts = bindRouteScopeOptions( + opts._fromRoute.slice(0, index), + opts, + router, + opts._nearestRoute, + ) as TOptions + } + } + const moduleId = + typeof opts._module === 'object' + ? resolveRouteScopeConstraint(router, opts._module, opts._nearestRoute) + : opts._module + const rootId = resolveModuleRouteId( + router, + `${moduleId}:`, + opts._nearestRoute, + ) + const root = router.routesById[rootId] as AnyRoute | undefined + if (!root) { + if (process.env.NODE_ENV !== 'production') { + throw new Error( + Object.keys(router.routesById).some((id) => + id.startsWith(`${moduleId}#`), + ) + ? `Invariant failed: Route module "${moduleId}" is installed several times in this router. Address one installation through its namespace.` + : `Invariant failed: Route module "${moduleId}" is not installed in this router. Mount it with mountRouteModule() in the route tree of the app.`, + ) + } + invariant() + } + if (opts.mask?._module !== undefined) { + bindRouteScopeOptions( + rootId.slice(0, -1), + opts.mask, + router, + opts._nearestRoute, + ) + } + const prefix = root.fullPath === '/' ? '' : root.fullPath + const localize = (path: T): T => + prefix && typeof path === 'string' && path[0] === '/' + ? ((prefix + path) as T) + : path + return { + ...opts, + to: localize(opts.to), + from: + opts.from === undefined && opts._fromRoute !== undefined + ? ( + router.routesById[ + resolveModuleRouteId(router, opts._fromRoute, opts._nearestRoute) + ] as AnyRoute | undefined + )?.fullPath + : localize(opts.from), + mask: opts.mask && { + ...opts.mask, + to: localize(opts.mask.to), + from: localize(opts.mask.from), + }, + } +} + +/** + * Mounts a route module's root under a host route. + * + * Generated route trees call this for every installed module. The module's + * routes keep their qualified ids; their paths become the mount path followed + * by their module-local paths. A module installed several times is mounted + * once per installation (`as`): each installation gets its own copies of the + * module's routes, and the module's route objects stay templates with their + * module-local ids and paths. + * + * @experimental Route modules are experimental and may change in any release. + */ +export function mountRouteModule< + TRoot extends AnyRoute, + TParent extends AnyRoute, + const TAt extends string = '/', +>(root: TRoot, options: MountRouteModuleOptions): TRoot { + const moduleId = root.options._module + if (moduleId === undefined) { + if (process.env.NODE_ENV !== 'production') { + throw new Error( + 'Invariant failed: mountRouteModule() expects the root route of a route module, created with createModuleRoot().', + ) + } + invariant() + } + const at = options.at + const mount = { + getParentRoute: options.parent, + path: at && at !== '/' ? at : undefined, + _uses: options.uses, + } + setScopeLocationOptions(scopeLocationOptions) + setResolveRouteId(resolveModuleRouteId) + if (options.as === undefined) { + root.update(mount as any) + ;(root as { isRoot: boolean }).isRoot = false + return root + } + if (root.id === undefined) { + initTemplates(root, () => templateHost) + } + return copyRoute(root, { + ...mount, + _module: `${moduleId}#${options.as}`, + }) as TRoot +} + +/** + * The stand-in parent of an unmounted module root: module code addresses the + * module's routes by their module-local ids and paths. + */ +const templateHost = { id: rootRouteId, fullPath: '/' } as AnyRoute + +function initTemplates(route: AnyRoute, getParentRoute: () => AnyRoute) { + route.update({ getParentRoute } as any) + route.init(0) + route.children?.forEach((child: AnyRoute) => + initTemplates(child, () => route), + ) +} + +/** + * Copies a module route and its subtree for one installation. Copies share + * the template's options, so components, loaders and code-split chunks are + * the same for every installation; `lazyFn` loads into each copy. + */ +function copyRoute(template: AnyRoute, options: object): AnyRoute { + const copy = new (template.constructor as new () => AnyRoute)() + copy.options = { ...template.options, ...options } + ;(copy as { isRoot: boolean }).isRoot = false + copy.lazyFn = template.lazyFn + ;(copy as { _template?: AnyRoute })._template = template + copy.children = template.children?.map((child: AnyRoute) => + copyRoute(child, { getParentRoute: () => copy }), + ) + return copy +} + +function assertRouteScope( + compatible: boolean, + incoming: string, + moduleId: string, +) { + if (!compatible) { + if (process.env.NODE_ENV !== 'production') { + throw new Error( + `Cannot use route scope "${incoming}" options in route scope "${moduleId}".`, + ) + } + invariant() + } +} + +function resolveRouteScopeConstraint( + router: AnyRouter, + scope: { receiver: string; target: string }, + nearestRouteId?: string, +): string { + assertRouteScope( + resolveModuleRouteId(router, `${scope.receiver}:`, nearestRouteId) === + `${scope.target}:`, + scope.target, + scope.receiver, + ) + return scope.target +} + +/** Internal generated/framework wiring: Bind options without silently replacing an incompatible scope. */ +export function bindRouteScopeOptions( + moduleId: string, + options: T, + router?: AnyRouter, + nearestRouteId?: string, +): Omit & { _module: RouteModuleScope } { + let scope = options._module + if (typeof scope === 'object' && router) { + const target = resolveRouteScopeConstraint( + router, + scope, + moduleId.includes('#') ? `${moduleId}:` : nearestRouteId, + ) + // The deferred receiver is already this API's scope, so the resolved + // constraint has also established its installation ownership. + if (scope.receiver === moduleId) { + return { ...options, _module: target } + } + scope = target + } + const incoming = typeof scope === 'object' ? scope.target : scope + if (incoming && incoming !== moduleId) { + const incomingInstallation = incoming.indexOf('#') + const installation = moduleId.indexOf('#') + assertRouteScope( + incomingInstallation < 0 + ? moduleId.startsWith(`${incoming}#`) + : installation < 0 && incoming.startsWith(`${moduleId}#`), + incoming, + moduleId, + ) + if (incomingInstallation >= 0) { + scope = { receiver: moduleId, target: incoming } + if (router) { + scope = resolveRouteScopeConstraint(router, scope, nearestRouteId) + } + } + } + return { + ...options, + _module: + typeof scope === 'object' + ? scope + : incoming?.includes('#') + ? incoming + : moduleId, + } +} + +/** + * Creates the `redirect` of a route module: absolute destinations are local to + * the module, wherever it is mounted. + */ +export function createScopedRedirect( + moduleId: string, +): RedirectFn<{ router: TRouter }> { + return (opts) => redirect(bindRouteScopeOptions(moduleId, opts) as any) as any +} + +/** + * The router as seen from a route module: `navigate` and `buildLocation` take + * the module's local paths and are typed against the module router + * (`TRouter`). `preloadRoute` and `matchRoute` are already typed by the route + * tree of `TRouter`. + */ +export type ScopedRouterView = Omit< + TRouter, + 'navigate' | 'buildLocation' | 'routeTree' | 'routesById' | 'routesByPath' +> & { + navigate: NavigateFn<{ router: TRouter }> + buildLocation: BuildLocationFn<{ router: TRouter }> + /** Raw application routes retain their final installed IDs and paths. */ + routeTree: AnyRoute + routesById: Record + routesByPath: Record +} + +const scopedRouterViews = new WeakMap>() + +/** + * Returns a view of `router` whose path-based navigation methods address the + * routes of a route module in module-local coordinates. Everything else is + * read from the router itself. A module installed several times is addressed + * in the installation of the caller's nearest match (`nearestRouteId`). + */ +export function getScopedRouterView( + router: AnyRouter, + moduleId: string, + nearestRouteId?: string, +): ScopedRouterView { + const namespace = resolveModuleRouteId( + router, + `${moduleId}:`, + nearestRouteId, + ).slice(0, -1) + let views = scopedRouterViews.get(router) + if (!views) { + views = Object.create(null) as Record + scopedRouterViews.set(router, views) + } + return (views[namespace] ??= createScopedRouterView(router, namespace)) as any +} + +function createScopedRouterView( + router: AnyRouter, + moduleId: string, +): AnyRouter { + const view: AnyRouter = Object.create(router) + view.navigate = (opts: any) => + router.navigate(bindRouteScopeOptions(moduleId, opts, router)) + view.buildLocation = (opts: any) => + router.buildLocation(bindRouteScopeOptions(moduleId, opts, router)) + view.preloadRoute = (opts: any) => + router.preloadRoute(bindRouteScopeOptions(moduleId, opts, router) as any) + view.matchRoute = (location: any, opts: any) => + router.matchRoute(bindRouteScopeOptions(moduleId, location, router), opts) + return view +} diff --git a/packages/router-core/src/route.ts b/packages/router-core/src/route.ts index 089369b454..30a50a84f2 100644 --- a/packages/router-core/src/route.ts +++ b/packages/router-core/src/route.ts @@ -3,6 +3,7 @@ import { cleanPath, trimPathLeft, trimPathRight } from './path' import { notFound } from './not-found' import { redirect } from './redirect' import { rootRouteId } from './root' +import { getRouteNavigationScope } from './route-module' import type { LazyRoute } from './fileRoute' import type { RouteInterpolation } from './path' import type { NotFoundError } from './not-found' @@ -506,7 +507,17 @@ export type ResolveFullPath< TPrefixed = RoutePrefix, > = TPrefixed extends RootRouteId ? '/' : TPrefixed -export interface RouteExtensions { +/** + * Framework adapters augment this interface with route-bound hooks and + * components. `TRegister` is the route's scope: `RegisteredRouterOf` + * is the router those APIs are typed against (the registered router for + * application routes, the route module's router for module routes). + */ +export interface RouteExtensions< + in out TId, + in out TFullPath, + in out TRegister, +> { id: TId fullPath: TFullPath } @@ -658,7 +669,7 @@ export interface Route< in out TSSR, in out TServerMiddlewares, in out THandlers, -> extends RouteExtensions { +> extends RouteExtensions { path: TPath parentRoute: TParentRoute children?: TChildren @@ -834,7 +845,7 @@ export interface Route< * @returns A redirect Response that can be thrown from loaders/beforeLoad * @link https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction */ - redirect: RedirectFnRoute + redirect: RedirectFnRoute } export type AnyRoute = Route< @@ -1267,6 +1278,18 @@ export interface UpdatableRouteOptions< in out TBeforeLoadFn, > extends UpdatableStaticRouteOption, UpdatableRouteOptionsExtensions { + /** + * Internal: the id of the route module whose root this route is. Set by + * `createModuleRoot`; do not set it manually. The root of an installation + * of a module installed several times has `#`. + */ + _module?: string + /** + * Internal: the installations that this module root's module uses of + * modules installed several times, keyed by module id. Set by + * `mountRouteModule`. + */ + _uses?: Record /** * If true, this route will be matched as case-sensitive * @@ -1797,7 +1820,10 @@ export class BaseRoute< RoutePathOptionsIntersection) | undefined - const isRoot = !options?.path && !options?.id + // A route module's root (`options._module`) is never the tree root: it is + // mounted under a host route and qualifies the ids of its subtree. + const moduleId = options?._module + const isRoot = !options?.path && !options?.id && moduleId === undefined this.parentRoute = this.options.getParentRoute?.() @@ -1822,14 +1848,18 @@ export class BaseRoute< const customId = options?.id || path - // Strip the parentId prefix from the first level of children + // Strip the parentId prefix from the first level of children. A module + // root's id is `:`, so its descendants get qualified ids such as + // `@acme/products:/$productId` wherever the module is mounted. const id = isRoot ? rootRouteId - : cleanPath( - (this.parentRoute.id === rootRouteId ? '' : this.parentRoute.id) + - '/' + - (customId ?? ''), - ) + : moduleId !== undefined + ? `${moduleId}:` + : cleanPath( + (this.parentRoute.id === rootRouteId ? '' : this.parentRoute.id) + + '/' + + (customId ?? ''), + ) if (path === rootRouteId) { path = '/' @@ -2011,8 +2041,11 @@ export class BaseRoute< * @returns A redirect Response that can be thrown from loaders/beforeLoad * @link https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction */ - redirect: RedirectFnRoute = (opts) => - redirect({ from: this.fullPath, ...opts } as any) + redirect: RedirectFnRoute = (opts) => + redirect({ + ...getRouteNavigationScope(this.id, this.fullPath), + ...opts, + } as any) } export class BaseRouteApi { @@ -2033,9 +2066,14 @@ export class BaseRouteApi { * @returns A redirect Response that can be thrown from loaders/beforeLoad * @link https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction */ - redirect: RedirectFnRoute['fullPath']> = ( - opts, - ) => redirect({ from: this.id as string, ...opts } as any) + redirect: RedirectFnRoute< + RouteTypesById['fullPath'], + { router: TRouter } + > = (opts) => + redirect({ + ...getRouteNavigationScope(this.id as string, this.id as string), + ...opts, + } as any) } export interface RootRoute< diff --git a/packages/router-core/src/router.ts b/packages/router-core/src/router.ts index ecf443168d..32fcbd3531 100644 --- a/packages/router-core/src/router.ts +++ b/packages/router-core/src/router.ts @@ -38,7 +38,9 @@ import { trimPathRight, } from './path' import { createSieveCache } from './sieve-cache' +import { invariant } from './invariant' import { isNotFound } from './not-found' +import { resolveRouteId } from './route-id' import { setupScrollRestoration } from './scroll-restoration' import { defaultParseSearch, defaultStringifySearch } from './searchParams' import { rootRouteId } from './root' @@ -106,7 +108,6 @@ import type { } from './routeInfo' import type { AnyRouteMatch, - MakeRouteMatch, MakeRouteMatchUnion, MatchRouteOptions, } from './Matches' @@ -127,6 +128,7 @@ import type { InitialHydrationScriptTags, } from './ssr/hydrationScripts' import type { GetStoreConfig, RouterStores } from './stores' +import type { RouteModuleScope, RouteScopeMarker } from './route-module' function isExternalUrl(url: URL, origin: string) { return ( @@ -574,13 +576,23 @@ export type LocationRewriteFunction = ({ export interface RouterState< in out TRouteTree extends AnyRoute = AnyRoute, - in out TRouteMatch = MakeRouteMatchUnion, + in out TRouteMatch = TRouteTree extends RouteScopeMarker + ? MakeRouteMatchUnion> + : MakeRouteMatchUnion, > { status: 'pending' | 'idle' isLoading: boolean matches: Array - location: ParsedLocation> - resolvedLocation?: ParsedLocation> + location: ParsedLocation< + TRouteTree extends RouteScopeMarker + ? Record + : FullSearchSchema + > + resolvedLocation?: ParsedLocation< + TRouteTree extends RouteScopeMarker + ? Record + : FullSearchSchema + > } export interface BuildNextOptions { @@ -600,6 +612,9 @@ export interface BuildNextOptions { from?: string href?: string _fromLocation?: ParsedLocation + _module?: RouteModuleScope + _fromRoute?: string + _nearestRoute?: string unsafeRelative?: 'path' _isNavigate?: boolean } @@ -1366,7 +1381,10 @@ export class RouterCore< if (this.latestLocation) { const config = this.getStoreConfig(this) this.batch = config.batch - this.stores = createRouterStores(this.latestLocation, config) + this.stores = createRouterStores( + this.latestLocation, + config, + ) if (!(isServer ?? this.isServer)) { setupScrollRestoration(this) @@ -1758,6 +1776,18 @@ export class RouterCore< staticData: route.options.staticData || {}, fullPath: route.fullPath, } + // The resolver is installed only by route-module composition, so an + // application without modules can eliminate this identity work. + if (resolveRouteId && route.id[0] !== '/') { + const separator = route.id.indexOf(':') + if (separator > 0) { + const installation = route.id.indexOf('#') + match.localRouteId = + installation > 0 && installation < separator + ? route.id.slice(0, installation) + route.id.slice(separator) + : route.id + } + } } // If we have a global not found, mark the right match as global not found @@ -2179,12 +2209,27 @@ export class RouterCore< } } - const next = build(opts) + // Route-module APIs pass module-local destinations (`_fromRoute` always + // comes with `_module`); translate them once so the destination, its mask + // and route masks all see final paths. + let dest = opts + if (opts._module !== undefined) { + if (!scopeLocationOptions) { + if (process.env.NODE_ENV !== 'production') { + throw new Error( + `Invariant failed: Route module "${opts._module}" is not installed in this router. Mount it with mountRouteModule() in the route tree of the app.`, + ) + } + invariant() + } + dest = scopeLocationOptions(this, opts) + } + const next = build(dest) - if (opts.mask) { + if (dest.mask) { next.maskedLocation = build({ - from: opts.from, - ...opts.mask, + from: dest.from, + ...dest.mask, }) } else if (this.options.routeMasks) { const match = findFlatMatch>( @@ -2200,7 +2245,7 @@ export class RouterCore< const nextParams = resolveNextParams(maskParams, params) next.maskedLocation = build({ - from: opts.from, + from: dest.from, ...maskProps, params: nextParams, }) @@ -2521,7 +2566,7 @@ export class RouterCore< abort.push(controller) } } - const invalidate = (d: MakeRouteMatch) => { + const invalidate = (d: AnyRouteMatch) => { if (invalidIds.has(d.id)) { const route = this.routesById[d.routeId] as AnyRoute const next = { @@ -2741,6 +2786,24 @@ export class RouterCore< serverSsrLifecycle?: RouterSsrLifecycle } +/** + * Translates the module-local options of route-module APIs. `mountRouteModule` + * installs it, so applications without route modules do not ship it. + */ +let scopeLocationOptions: + | (( + router: AnyRouter, + opts: TOptions, + ) => TOptions) + | undefined + +/** @internal Called by `mountRouteModule`. */ +export function setScopeLocationOptions( + scope: NonNullable, +): void { + scopeLocationOptions = scope +} + async function documentNavigation( router: AnyRouter, href: string, diff --git a/packages/router-core/src/stores.ts b/packages/router-core/src/stores.ts index 8c2beeb2e7..59012159dc 100644 --- a/packages/router-core/src/stores.ts +++ b/packages/router-core/src/stores.ts @@ -176,5 +176,7 @@ export function createRouterStores( }) } - return store + // Internally every lane stores the same runtime match shape; the public + // router view projects the route-tree-specific match union over those values. + return store as unknown as RouterStores } diff --git a/packages/router-core/src/useNavigate.ts b/packages/router-core/src/useNavigate.ts index ca0282bcce..b56ac5dd80 100644 --- a/packages/router-core/src/useNavigate.ts +++ b/packages/router-core/src/useNavigate.ts @@ -1,9 +1,15 @@ import type { NavigateOptions } from './link' -import type { RegisteredRouter } from './router' +import type { AnyRouter, Register } from './router' +import type { RegisteredRouterOf } from './route-module' -export type UseNavigateResult = < - TRouter extends RegisteredRouter, - TTo extends string | undefined, +export type UseNavigateResult< + TDefaultFrom extends string, + TDefaultRegister = Register, +> = < + TRouter extends AnyRouter = RegisteredRouterOf, + // A default equal to the constraint keeps the inference of a destination-less + // call unchanged while allowing the router type to have a default. + TTo extends string | undefined = string | undefined, TFrom extends string = TDefaultFrom, TMaskFrom extends string = TFrom, TMaskTo extends string = '', diff --git a/packages/router-core/tests/route-module-unmounted.test.ts b/packages/router-core/tests/route-module-unmounted.test.ts new file mode 100644 index 0000000000..53aaf65127 --- /dev/null +++ b/packages/router-core/tests/route-module-unmounted.test.ts @@ -0,0 +1,44 @@ +import { afterEach, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { createTestRouter } from './routerTestUtils' + +// Its own file: nothing in this module graph has mounted a route module, so +// the router has no route-module translation installed. +test('navigating into a route module without any mounted module fails', () => { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([indexRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + expect(() => + router.buildLocation({ to: '/', _module: '@acme/products' } as any), + ).toThrow( + 'Route module "@acme/products" is not installed in this router. Mount it with mountRouteModule() in the route tree of the app.', + ) + expect(router.buildLocation({ to: '/' }).pathname).toBe('/') +}) + +afterEach(() => { + vi.unstubAllEnvs() +}) + +test('in production the failure is a compact invariant', () => { + vi.stubEnv('NODE_ENV', 'production') + const rootRoute = new BaseRootRoute({}) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([ + new BaseRoute({ getParentRoute: () => rootRoute, path: '/' }), + ]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + expect(() => + router.buildLocation({ to: '/', _module: '@acme/products' } as any), + ).toThrow('Invariant failed') +}) diff --git a/packages/router-core/tests/route-module.test.ts b/packages/router-core/tests/route-module.test.ts new file mode 100644 index 0000000000..82234f51f5 --- /dev/null +++ b/packages/router-core/tests/route-module.test.ts @@ -0,0 +1,853 @@ +import { describe, expect, test } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, notFound } from '../src' +import { + createScopedRedirect, + getRouteModuleId, + getRouteNavigationScope, + getScopedRouterView, + mountRouteModule, + resolveRouteId, +} from '../src/route-module-internal' +import { createTestRouter, loadServerResponse } from './routerTestUtils' +import type { AnyRoute } from '../src' + +function createModuleRoot(moduleId: string, options: object = {}) { + return new BaseRoute({ ...options, _module: moduleId } as any) as AnyRoute +} + +/** + * root + * ├── / (app index) + * └── /shop (app layout) + * └── @acme/products (module root, mounted at /products) + * ├── / (module index) + * ├── /$productId + * └── /_layout (pathless) + * └── /reviews + */ +function setup(initialEntry = '/', routerOptions: object = {}) { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const shopRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/shop', + }) + + const productsRoot = createModuleRoot('@acme/products') + const productsIndex = new BaseRoute({ + getParentRoute: () => productsRoot, + path: '/', + }) + const productRoute = new BaseRoute({ + getParentRoute: () => productsRoot, + path: '/$productId', + }) + const layoutRoute = new BaseRoute({ + getParentRoute: () => productsRoot, + id: '/_layout', + }) + const reviewsRoute = new BaseRoute({ + getParentRoute: () => layoutRoute, + path: '/reviews', + }) + productsRoot.addChildren([ + productsIndex, + productRoute, + layoutRoute.addChildren([reviewsRoute]), + ]) + + mountRouteModule(productsRoot, { + parent: () => shopRoute as AnyRoute, + at: '/products', + } as any) + + const routeTree = rootRoute.addChildren([ + indexRoute, + shopRoute.addChildren([productsRoot]), + ]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: [initialEntry] }), + ...routerOptions, + }) + return { router, productsRoot, productRoute, reviewsRoute } +} + +describe('route module ids and paths', () => { + test('module routes get qualified ids and mounted full paths', () => { + const { router } = setup() + + expect( + Object.fromEntries( + Object.values(router.routesById).map((route: AnyRoute) => [ + route.id, + route.fullPath, + ]), + ), + ).toEqual({ + __root__: '/', + '/': '/', + '/shop': '/shop', + '@acme/products:': '/shop/products', + '@acme/products:/': '/shop/products/', + '@acme/products:/$productId': '/shop/products/$productId', + '@acme/products:/_layout': '/shop/products', + '@acme/products:/_layout/reviews': '/shop/products/reviews', + }) + }) + + test('mounted module routes match by their final paths', () => { + const { router } = setup() + + expect( + router.matchRoutes('/shop/products/42').map((match) => match.routeId), + ).toEqual([ + '__root__', + '/shop', + '@acme/products:', + '@acme/products:/$productId', + ]) + expect( + router.matchRoutes('/shop/products').map((match) => match.routeId), + ).toEqual(['__root__', '/shop', '@acme/products:', '@acme/products:/']) + }) + + test('a module mounted without a path adds no path segment', () => { + const rootRoute = new BaseRootRoute({}) + const moduleRoot = createModuleRoot('account') + const settingsRoute = new BaseRoute({ + getParentRoute: () => moduleRoot, + path: '/settings', + }) + moduleRoot.addChildren([settingsRoute]) + mountRouteModule(moduleRoot, { parent: () => rootRoute } as any) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([moduleRoot]), + history: createMemoryHistory(), + }) + + expect(router.routesById['account:']!.fullPath).toBe('/') + expect(router.routesById['account:/settings']!.fullPath).toBe('/settings') + expect( + router.matchRoutes('/settings').map((match) => match.routeId), + ).toEqual(['__root__', 'account:', 'account:/settings']) + }) + + test('nested modules keep their own qualified ids', () => { + const rootRoute = new BaseRootRoute({}) + const storefrontRoot = createModuleRoot('@acme/storefront') + const cartRoute = new BaseRoute({ + getParentRoute: () => storefrontRoot, + path: '/cart', + }) + const productsRoot = createModuleRoot('@acme/products') + const productRoute = new BaseRoute({ + getParentRoute: () => productsRoot, + path: '/$productId', + }) + productsRoot.addChildren([productRoute]) + mountRouteModule(productsRoot, { + parent: () => storefrontRoot, + at: '/products', + } as any) + storefrontRoot.addChildren([cartRoute, productsRoot]) + mountRouteModule(storefrontRoot, { + parent: () => rootRoute, + at: '/shop', + } as any) + const router = createTestRouter({ + routeTree: rootRoute.addChildren([storefrontRoot]), + history: createMemoryHistory(), + }) + + expect(router.routesById['@acme/storefront:/cart']!.fullPath).toBe( + '/shop/cart', + ) + expect(router.routesById['@acme/products:/$productId']!.fullPath).toBe( + '/shop/products/$productId', + ) + }) + + test('mountRouteModule rejects a route that is not a module root', () => { + const rootRoute = new BaseRootRoute({}) + const route = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/x', + }) + expect(() => + mountRouteModule(route as AnyRoute, { parent: () => rootRoute } as any), + ).toThrow(/createModuleRoot/) + }) +}) + +describe('getRouteModuleId', () => { + const cases = [ + ['@acme/products:/$productId', '@acme/products'], + ['@acme/products:', '@acme/products'], + ['account:/settings', 'account'], + ['/posts', undefined], + ['/a:b', undefined], + [':/x', undefined], + ['__root__', undefined], + ['404', undefined], + ] as const + + test.each(cases)('%s -> %s', (routeId, moduleId) => { + expect(getRouteModuleId(routeId)).toBe(moduleId) + }) + + test.each(cases)( + 'getRouteNavigationScope agrees for %s', + (routeId, moduleId) => { + expect(getRouteNavigationScope(routeId, '/full')).toEqual( + moduleId === undefined + ? { from: '/full' } + : { _module: moduleId, _fromRoute: routeId }, + ) + }, + ) +}) + +describe('application route ids', () => { + // Application ids always start with `/`, even when a custom id or a path + // contains `:`, so route-bound APIs never treat them as module routes. + test('ids with ":" stay application routes', () => { + const rootRoute = new BaseRootRoute({}) + const customIdRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + id: 'foo:bar', + }) + const downloadRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: 'files/{$id}:download', + }) + createTestRouter({ + routeTree: rootRoute.addChildren([customIdRoute, downloadRoute]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + expect(customIdRoute.id).toBe('/foo:bar') + expect(downloadRoute.id).toBe('/files/{$id}:download') + for (const route of [customIdRoute, downloadRoute]) { + const { options } = route.redirect({ to: './x' } as any) as any + expect(options.from).toBe(route.fullPath) + expect(options._module).toBeUndefined() + } + }) +}) + +describe('module-local navigation', () => { + test('absolute destinations resolve inside the module', () => { + const { router } = setup() + + expect( + router.buildLocation({ + _module: '@acme/products', + to: '/$productId', + params: { productId: '42' }, + } as any).pathname, + ).toBe('/shop/products/42') + expect( + router.buildLocation({ _module: '@acme/products', to: '/' } as any) + .pathname, + ).toBe('/shop/products') + expect( + router.buildLocation({ + _module: '@acme/products', + to: '/reviews', + } as any).pathname, + ).toBe('/shop/products/reviews') + }) + + test('application destinations are unchanged', () => { + const { router } = setup() + + expect(router.buildLocation({ to: '/shop' } as any).pathname).toBe('/shop') + }) + + test('a module-local from resolves relative destinations', () => { + const { router } = setup('/shop/products/42') + + expect( + router.buildLocation({ + _module: '@acme/products', + from: '/$productId', + to: '..', + } as any).pathname, + ).toBe('/shop/products') + }) + + test('_fromRoute resolves from the route full path unless from is given', () => { + const { router } = setup('/shop/products/42') + + expect( + router.buildLocation({ + _module: '@acme/products', + _fromRoute: '@acme/products:/$productId', + to: './', + params: { productId: '7' }, + } as any).pathname, + ).toBe('/shop/products/7') + expect( + router.buildLocation({ + _module: '@acme/products', + _fromRoute: '@acme/products:/$productId', + from: '/reviews', + to: '..', + } as any).pathname, + ).toBe('/shop/products') + }) + + test('masks are module-local too', () => { + const { router } = setup() + + const location = router.buildLocation({ + _module: '@acme/products', + to: '/$productId', + params: { productId: '42' }, + mask: { to: '/' }, + } as any) + expect(location.pathname).toBe('/shop/products/42') + expect(location.maskedLocation?.pathname).toBe('/shop/products') + }) + + test('navigating to a module that is not installed fails', () => { + const { router } = setup() + + expect(() => + router.buildLocation({ _module: '@acme/unknown', to: '/' } as any), + ).toThrow(/@acme\/unknown/) + }) + + test('the scoped router view navigates in module coordinates', async () => { + const { router } = setup() + await router.load() + const view = getScopedRouterView(router, '@acme/products') + + expect(getScopedRouterView(router, '@acme/products')).toBe(view) + expect(view.state.location.pathname).toBe('/') + + await view.navigate({ + to: '/$productId', + params: { productId: '3' }, + } as any) + expect(router.state.location.pathname).toBe('/shop/products/3') + expect(view.buildLocation({ to: '/' } as any).pathname).toBe( + '/shop/products', + ) + }) +}) + +describe('module-local redirects', () => { + test('the scoped redirect resolves inside the module', async () => { + const { router, reviewsRoute } = setup('/shop/products/reviews') + const redirect = createScopedRedirect('@acme/products') + reviewsRoute.update({ + beforeLoad: () => { + throw redirect({ to: '/$productId', params: { productId: '9' } } as any) + }, + } as any) + + await router.load() + expect(router.state.location.pathname).toBe('/shop/products/9') + }) + + test('Route.redirect resolves absolute and relative destinations', async () => { + const { router, productRoute, reviewsRoute } = setup( + '/shop/products/reviews', + ) + reviewsRoute.update({ + beforeLoad: () => { + throw reviewsRoute.redirect({ to: '/' } as any) + }, + } as any) + await router.load() + expect(router.state.location.pathname).toBe('/shop/products') + + productRoute.update({ + beforeLoad: ({ params }: any) => { + if (params.productId === 'old') { + throw productRoute.redirect({ + to: '.', + params: { productId: 'new' }, + } as any) + } + }, + } as any) + await router.navigate({ to: '/shop/products/old' } as any) + expect(router.state.location.pathname).toBe('/shop/products/new') + }) +}) + +describe('module navigation paths', () => { + test('the scoped view preloads module routes', async () => { + const { router } = setup() + await router.load() + const view = getScopedRouterView(router, '@acme/products') + + const matches = await view.preloadRoute({ + to: '/$productId', + params: { productId: '9' }, + } as any) + expect(matches?.map((match) => match.routeId).at(-1)).toBe( + '@acme/products:/$productId', + ) + expect(matches?.at(-1)?.params).toEqual({ productId: '9' }) + }) + + test('matchRoute of the scoped view takes module-local paths', async () => { + const { router } = setup('/shop/products/3') + await router.load() + const view = getScopedRouterView(router, '@acme/products') + + expect(view.matchRoute({ to: '/$productId' } as any)).toEqual({ + productId: '3', + }) + expect(router.matchRoute({ to: '/$productId' } as any)).toBe(false) + }) + + test('a scoped redirect resolves to the final path without changing it', () => { + const { router } = setup() + const thrown = createScopedRedirect('@acme/products')({ + to: '/$productId', + params: { productId: '9' }, + } as any) + + const resolved = router.resolveRedirect(thrown) + expect(resolved.options.href).toBe('/shop/products/9') + expect(thrown.options.to).toBe('/$productId') + }) + + test('route masks apply to module destinations', () => { + const { router } = setup('/', { + routeMasks: [{ from: '/shop/products/$productId', to: '/shop' }], + }) + + const location = router.buildLocation({ + _module: '@acme/products', + to: '/$productId', + params: { productId: '42' }, + } as any) + expect(location.pathname).toBe('/shop/products/42') + expect(location.maskedLocation?.pathname).toBe('/shop') + }) + + test('routers in one process navigate to their own mount of a module', () => { + const { router } = setup() + const rootRoute = new BaseRootRoute({}) + const productsRoot = createModuleRoot('@acme/products') + productsRoot.addChildren([ + new BaseRoute({ + getParentRoute: () => productsRoot, + path: '/$productId', + }), + ]) + mountRouteModule(productsRoot, { + parent: () => rootRoute as AnyRoute, + at: '/catalog', + } as any) + const other = createTestRouter({ + routeTree: rootRoute.addChildren([productsRoot]), + history: createMemoryHistory({ initialEntries: ['/'] }), + }) + + const build = (target: typeof router | typeof other) => + target.buildLocation({ + _module: '@acme/products', + to: '/$productId', + params: { productId: '42' }, + } as any).pathname + expect(build(router)).toBe('/shop/products/42') + expect(build(other)).toBe('/catalog/42') + }) +}) + +/** + * root + * ├── / + * └── /orgs/$orgId + * └── @acme/settings (module root, mounted at /settings) + * ├── / + * ├── /profile + * └── /members/$memberId + */ +function setupUnderParams(initialEntry = '/') { + const rootRoute = new BaseRootRoute({}) + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + const orgRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/orgs/$orgId', + }) + const settingsRoot = createModuleRoot('@acme/settings') + settingsRoot.addChildren([ + new BaseRoute({ getParentRoute: () => settingsRoot, path: '/' }), + new BaseRoute({ getParentRoute: () => settingsRoot, path: '/profile' }), + new BaseRoute({ + getParentRoute: () => settingsRoot, + path: '/members/$memberId', + }), + ]) + mountRouteModule(settingsRoot, { + parent: () => orgRoute as AnyRoute, + at: '/settings', + } as any) + const routeTree = rootRoute.addChildren([ + indexRoute, + orgRoute.addChildren([settingsRoot]), + ]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: [initialEntry] }), + }) + return { router } +} + +describe('a module mounted under path params', () => { + test('module routes match with the host params', () => { + const { router } = setupUnderParams() + + const matches = router.matchRoutes('/orgs/7/settings/members/3', {}) + const leaf = matches[matches.length - 1]! + expect(leaf.routeId).toBe('@acme/settings:/members/$memberId') + expect(leaf.params).toEqual({ orgId: '7', memberId: '3' }) + }) + + test('module-local destinations keep the host params of the location', async () => { + const { router } = setupUnderParams('/orgs/7/settings') + await router.load() + + expect( + router.buildLocation({ _module: '@acme/settings', to: '/profile' } as any) + .pathname, + ).toBe('/orgs/7/settings/profile') + expect( + router.buildLocation({ + _module: '@acme/settings', + to: '/members/$memberId', + params: { memberId: '3' }, + } as any).pathname, + ).toBe('/orgs/7/settings/members/3') + }) + + test('destinations from outside the installation pass the host params', async () => { + const { router } = setupUnderParams('/') + await router.load() + + expect( + router.buildLocation({ + _module: '@acme/settings', + to: '/members/$memberId', + params: { orgId: '9', memberId: '3' }, + } as any).pathname, + ).toBe('/orgs/9/settings/members/3') + }) +}) + +/** + * root + * ├── /orgs/$orgId + * │ ├── @acme/settings#orgSettings (mounted at /settings) + * │ └── @acme/billing (mounted at /billing, uses orgSettings) + * └── /users/$userId + * └── @acme/settings#userSettings (mounted at /settings) + * + * @acme/settings: /, /profile, /members/$memberId + */ +function setupInstallations( + initialEntry = '/', + settingsOptions: { + members?: object + root?: object + } = {}, + routerOptions: object = {}, +) { + const rootRoute = new BaseRootRoute({}) + const orgRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/orgs/$orgId', + }) + const userRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/users/$userId', + }) + + const settingsRoot = createModuleRoot('@acme/settings', settingsOptions.root) + const settingsIndex = new BaseRoute({ + getParentRoute: () => settingsRoot, + path: '/', + }) + const profileRoute = new BaseRoute({ + getParentRoute: () => settingsRoot, + path: '/profile', + loader: () => 'profile', + }) + const membersRoute = new BaseRoute({ + getParentRoute: () => settingsRoot, + path: '/members/$memberId', + ...settingsOptions.members, + }) + settingsRoot.addChildren([settingsIndex, profileRoute, membersRoute]) + + const billingRoot = createModuleRoot('@acme/billing') + billingRoot.addChildren([ + new BaseRoute({ getParentRoute: () => billingRoot, path: '/' }), + ]) + + const orgSettings = mountRouteModule(settingsRoot, { + parent: () => orgRoute as AnyRoute, + at: '/settings', + as: 'orgSettings', + } as any) + const userSettings = mountRouteModule(settingsRoot, { + parent: () => userRoute as AnyRoute, + at: '/settings', + as: 'userSettings', + } as any) + mountRouteModule(billingRoot, { + parent: () => orgRoute as AnyRoute, + at: '/billing', + uses: { '@acme/settings': '@acme/settings#orgSettings' }, + } as any) + + const routeTree = rootRoute.addChildren([ + orgRoute.addChildren([orgSettings, billingRoot]), + userRoute.addChildren([userSettings]), + ]) + const router = createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: [initialEntry] }), + ...routerOptions, + }) + return { router, settingsRoot, profileRoute, membersRoute } +} + +describe('a module installed several times', () => { + test('each installation has its own routes', () => { + const { router } = setupInstallations() + + expect( + Object.fromEntries( + Object.values(router.routesById) + .filter((route: AnyRoute) => route.id.startsWith('@acme/settings')) + .map((route: AnyRoute) => [route.id, route.fullPath]), + ), + ).toEqual({ + '@acme/settings#orgSettings:': '/orgs/$orgId/settings', + '@acme/settings#orgSettings:/': '/orgs/$orgId/settings/', + '@acme/settings#orgSettings:/profile': '/orgs/$orgId/settings/profile', + '@acme/settings#orgSettings:/members/$memberId': + '/orgs/$orgId/settings/members/$memberId', + '@acme/settings#userSettings:': '/users/$userId/settings', + '@acme/settings#userSettings:/': '/users/$userId/settings/', + '@acme/settings#userSettings:/profile': '/users/$userId/settings/profile', + '@acme/settings#userSettings:/members/$memberId': + '/users/$userId/settings/members/$memberId', + }) + expect( + router.matchRoutes('/users/u1/settings/profile').map((m) => m.routeId), + ).toEqual([ + '__root__', + '/users/$userId', + '@acme/settings#userSettings:', + '@acme/settings#userSettings:/profile', + ]) + }) + + test("the module's routes stay templates with module-local ids and paths", () => { + const { router, settingsRoot, profileRoute } = setupInstallations() + + expect([settingsRoot.id, settingsRoot.fullPath]).toEqual([ + '@acme/settings:', + '/', + ]) + expect([profileRoute.id, profileRoute.fullPath]).toEqual([ + '@acme/settings:/profile', + '/profile', + ]) + const copy = router.routesById['@acme/settings#orgSettings:/profile'] + expect(copy).not.toBe(profileRoute) + expect(copy!.options.loader).toBe(profileRoute.options.loader) + expect(router.routesById['@acme/settings:/profile']).toBeUndefined() + }) + + test('module ids resolve to the installation of the nearest match', () => { + const { router } = setupInstallations() + + expect( + resolveRouteId!( + router, + '@acme/settings:/profile', + '@acme/settings#userSettings:/', + ), + ).toBe('@acme/settings#userSettings:/profile') + expect( + resolveRouteId!(router, '@acme/settings:/profile', '@acme/billing:/'), + ).toBe('@acme/settings#orgSettings:/profile') + expect( + resolveRouteId!(router, '@acme/settings:/profile', '/orgs/$orgId'), + ).toBe('@acme/settings:/profile') + expect(resolveRouteId!(router, '/orgs/$orgId', '@acme/billing:/')).toBe( + '/orgs/$orgId', + ) + }) + + test('module-local destinations stay in the installation of the caller', async () => { + const { router } = setupInstallations('/users/u1/settings/profile') + await router.load() + + const build = (options: object) => + router.buildLocation({ _module: '@acme/settings', ...options } as any) + .pathname + expect( + build({ to: '/profile', _nearestRoute: '@acme/settings#userSettings:/' }), + ).toBe('/users/u1/settings/profile') + // Route-bound APIs resolve from their route in the caller's installation. + expect( + build({ + to: '.', + params: { memberId: '4' }, + _fromRoute: '@acme/settings:/members/$memberId', + _nearestRoute: '@acme/settings#userSettings:/members/$memberId', + }), + ).toBe('/users/u1/settings/members/4') + }) + + test('a module that uses the module links to the installation it uses', async () => { + const { router } = setupInstallations('/orgs/7/billing') + await router.load() + + expect( + router.buildLocation({ + _module: '@acme/settings', + to: '/profile', + _nearestRoute: '@acme/billing:/', + } as any).pathname, + ).toBe('/orgs/7/settings/profile') + }) + + test('code outside the module addresses one installation', async () => { + const { router } = setupInstallations('/') + await router.load() + + expect( + router.buildLocation({ + _module: '@acme/settings#userSettings', + to: '/profile', + params: { userId: 'u2' }, + } as any).pathname, + ).toBe('/users/u2/settings/profile') + expect(() => + router.buildLocation({ + _module: '@acme/settings', + to: '/profile', + } as any), + ).toThrow('installed several times') + }) + + test('redirects resolve in the installation of the route that threw', async () => { + const redirect = createScopedRedirect('@acme/settings') + const { router } = setupInstallations('/users/u1/settings/members/3', { + members: { + beforeLoad: () => { + throw redirect({ to: '/profile' } as any) + }, + }, + }) + + await router.load() + expect(router.state.location.pathname).toBe('/users/u1/settings/profile') + + await router.navigate({ to: '/orgs/7/settings/members/3' } as any) + expect(router.state.location.pathname).toBe('/orgs/7/settings/profile') + }) + + test('not-found errors target the installation of the route that threw', async () => { + const { router } = setupInstallations('/orgs/7/settings/members/3', { + root: { notFoundComponent: () => null }, + members: { + loader: () => { + throw notFound({ routeId: '@acme/settings:' as never }) + }, + }, + }) + + await router.load() + expect( + router.state.matches.find((match) => match.status === 'notFound') + ?.routeId, + ).toBe('@acme/settings#orgSettings:') + }) + + test('not-found errors with an application route id ignore installations', async () => { + const { router } = setupInstallations('/users/u1/settings/members/3', { + members: { + loader: () => { + throw notFound({ routeId: '/users/$userId' as never }) + }, + }, + }) + + await router.load() + expect( + router.state.matches.find((match) => match.status === 'notFound') + ?.routeId, + ).toBe('/users/$userId') + }) + + test.each([ + ['/users/u1/settings/members/3', '/users/u1/settings/profile'], + ['/orgs/7/settings/members/3', '/orgs/7/settings/profile'], + ])( + 'server redirects from %s resolve in its installation', + async (path, location) => { + const redirect = createScopedRedirect('@acme/settings') + const { router } = setupInstallations( + '/', + { + members: { + loader: () => { + throw redirect({ to: '/profile' } as any) + }, + }, + }, + { isServer: true }, + ) + + const response = await loadServerResponse(router, path) + expect(response.status).toBe(307) + expect(response.headers.get('Location')).toBe(location) + }, + ) + + test('server not-found errors target the installation of the route that threw', async () => { + const { router } = setupInstallations( + '/', + { + root: { notFoundComponent: () => null }, + members: { + beforeLoad: () => { + throw notFound({ routeId: '@acme/settings:' as never }) + }, + }, + }, + { isServer: true }, + ) + + const response = await loadServerResponse( + router, + '/users/u1/settings/members/3', + ) + expect(response.status).toBe(404) + expect( + router.state.matches.find((match) => match.status === 'notFound') + ?.routeId, + ).toBe('@acme/settings#userSettings:') + }) +}) diff --git a/packages/router-core/tests/route-modules.bench.ts b/packages/router-core/tests/route-modules.bench.ts new file mode 100644 index 0000000000..7744d8343d --- /dev/null +++ b/packages/router-core/tests/route-modules.bench.ts @@ -0,0 +1,342 @@ +import { createRequire } from 'node:module' +import { describe, expect, test } from 'vitest' +import type { AnyRoute, AnyRouter, GetStoreConfig } from '../src' + +// Keep this file identical in baseline/candidate checkouts. Nx must build each +// revision first. Native modules avoid Vitest's instrumented export getters +// inside the timed routing code. The build paths also predate _internal exports. +const require = createRequire(import.meta.url) +const { + BaseRootRoute, + BaseRoute, + RouterCore, + createNonReactiveMutableStore, + createNonReactiveReadonlyStore, +} = require('../dist/cjs/index.cjs') as typeof import('../src') +const moduleWiring = + require('../dist/cjs/route-module.cjs') as typeof import('../src/route-module') +const { createMemoryHistory } = + require('@tanstack/history') as typeof import('@tanstack/history') + +const getStoreConfig: GetStoreConfig = () => ({ + createMutableStore: createNonReactiveMutableStore, + createReadonlyStore: createNonReactiveReadonlyStore, + batch: (fn) => fn(), +}) + +const BATCH = 64 +const MODULE = '@bench/catalog' + +type LocationOptions = { + to: string + params: Record + _module?: string + _nearestRoute?: string +} + +function createModuleTree() { + // This is the core half of generated createModuleRoot: the namespace enters + // through construction options, never by mutating initialized route metadata. + const root = new BaseRoute({ _module: MODULE } as any) as AnyRoute + return root.addChildren([ + new BaseRoute({ getParentRoute: () => root, path: '/$itemId' }), + ]) as AnyRoute +} + +function createRouter(kind: 'ordinary' | 'singleton' | 'repeated') { + const root = new BaseRootRoute({}) + const org = new BaseRoute({ + getParentRoute: () => root, + path: '/orgs/$orgId', + }) + const user = new BaseRoute({ + getParentRoute: () => root, + path: '/users/$userId', + }) + let children: Array + if (kind === 'ordinary') { + children = [ + org.addChildren([ + new BaseRoute({ getParentRoute: () => org, path: '/catalog/$itemId' }), + ]), + ] + } else { + const module = createModuleTree() + const orgCatalog = moduleWiring.mountRouteModule(module, { + parent: () => org, + at: '/catalog', + ...(kind === 'repeated' ? { as: 'orgCatalog' } : {}), + } as any) + children = [org.addChildren([orgCatalog])] + if (kind === 'repeated') { + children.push( + user.addChildren([ + moduleWiring.mountRouteModule(module, { + parent: () => user, + at: '/catalog', + as: 'userCatalog', + } as any), + ]), + ) + } + } + const history = createMemoryHistory({ + initialEntries: ['/orgs/acme/catalog/0'], + }) + const router = new RouterCore( + { + routeTree: root.addChildren(children), + history, + scrollRestoration: false, + isServer: true, + }, + getStoreConfig, + ) + history.destroy() + return router +} + +const ordinary = createRouter('ordinary') +const singleton = createRouter('singleton') +const repeated = createRouter('repeated') +const orgView = moduleWiring.getScopedRouterView( + repeated, + `${MODULE}#orgCatalog`, +) +const userView = moduleWiring.getScopedRouterView( + repeated, + `${MODULE}#userCatalog`, +) + +const ordinaryOptions: Array = Array.from( + { length: BATCH }, + (_, index) => ({ + to: '/orgs/$orgId/catalog/$itemId', + params: { orgId: 'acme', itemId: String(index) }, + }), +) +const singletonOptions = ordinaryOptions.map((options) => ({ + ...options, + to: '/$itemId', + _module: MODULE, +})) +const repeatedOptions = singletonOptions.map((options, index) => ({ + ...options, + params: { orgId: 'acme', userId: 'alex', itemId: String(index) }, + _nearestRoute: `${MODULE}#${index % 2 ? 'userCatalog' : 'orgCatalog'}:/$itemId`, +})) +const reusableOptions = repeatedOptions.map((options, index) => ({ + ...options, + _module: `${MODULE}#${index % 2 ? 'userCatalog' : 'orgCatalog'}`, +})) + +// Use the same factories that back generated redirect exports on both +// revisions. The nested call creates the candidate's deferred constraint; +// no private constraint object is constructed or injected by the benchmark. +const moduleRedirect = moduleWiring.createScopedRedirect(MODULE) +const installationRedirects = [ + moduleWiring.createScopedRedirect(`${MODULE}#orgCatalog`), + moduleWiring.createScopedRedirect(`${MODULE}#userCatalog`), +] +const deferredRedirectOptions = repeatedOptions.map( + (options, index) => + moduleRedirect( + installationRedirects[index % 2]!({ + to: '/$itemId', + params: options.params, + } as any).options as any, + ).options, +) + +// Route.redirect supplies its authored origin itself. Resolve these actual +// redirect options through buildLocation, as a router does for navigation. +const routeBoundRedirectOptions = repeatedOptions.map((options, index) => { + const installation = index % 2 ? 'userCatalog' : 'orgCatalog' + const route = repeated.routesById[ + `${MODULE}#${installation}:/$itemId` + ] as AnyRoute + return route.redirect({ to: '.', params: options.params } as any).options +}) + +const orgHref = (index: number) => `/orgs/acme/catalog/${index}` +const repeatedHref = (index: number) => + index % 2 ? `/users/alex/catalog/${index}` : orgHref(index) + +function defineCase( + name: string, + operation: (index: number) => string, + expected: (index: number) => string, +) { + let expectedChecksum = 0 + for (let index = 0; index < BATCH; index++) { + expect(operation(index)).toBe(expected(index)) + expectedChecksum += expected(index).length + } + let checksum = 0 + test(name, async ({ bench }) => { + await bench( + name, + { + afterAll: () => { + expect(checksum).toBe(expectedChecksum) + }, + }, + () => { + checksum = 0 + for (let index = 0; index < BATCH; index++) { + checksum += operation(index).length + } + }, + ).run({ time: 1500, warmupTime: 500, throws: true }) + }) +} + +// This accepted bug fix deliberately differs from the baseline. Validate it +// outside timing when that implementation is present; all measured operations +// below are identical valid public API workloads on both revisions. +if ('bindRouteScopeOptions' in moduleWiring) { + expect(() => orgView.buildLocation(reusableOptions[1] as any)).toThrow() +} + +const build = (router: Pick, options: object) => + router.buildLocation(options as any).href + +describe(`route-module location resolution (${BATCH} calls)`, () => { + defineCase( + 'ordinary application destinations', + (index) => build(ordinary, ordinaryOptions[index]!), + orgHref, + ) + defineCase( + 'singleton module-local destinations', + (index) => build(singleton, singletonOptions[index]!), + orgHref, + ) + defineCase( + 'repeated module-local destinations from alternating callers', + (index) => build(repeated, repeatedOptions[index]!), + repeatedHref, + ) + defineCase( + 'same-scope reusable options through explicit router views', + (index) => build(index % 2 ? userView : orgView, reusableOptions[index]!), + repeatedHref, + ) + defineCase( + 'deferred redirect scope constraints through explicit router views', + (index) => + build(index % 2 ? userView : orgView, deferredRedirectOptions[index]!), + repeatedHref, + ) + defineCase( + 'route-bound redirect origin rebinding', + (index) => build(repeated, routeBoundRedirectOptions[index]!), + repeatedHref, + ) + defineCase( + 'mixed ordinary, singleton, repeated, and reusable destinations', + (index) => { + switch (index % 4) { + case 0: + return build(ordinary, ordinaryOptions[index]!) + case 1: + return build(singleton, singletonOptions[index]!) + case 2: + return build(repeated, repeatedOptions[index]!) + default: + return build(userView, reusableOptions[index]!) + } + }, + (index) => (index % 4 === 3 ? repeatedHref(index) : orgHref(index)), + ) + defineCase( + 'mixed application, scoped, deferred, and route-bound destinations', + (index) => { + switch (index % 6) { + case 0: + return build(ordinary, ordinaryOptions[index]!) + case 1: + return build(singleton, singletonOptions[index]!) + case 2: + return build(repeated, repeatedOptions[index]!) + case 3: + return build(userView, reusableOptions[index]!) + case 4: + return build(orgView, deferredRedirectOptions[index]!) + default: + return build(repeated, routeBoundRedirectOptions[index]!) + } + }, + (index) => (index % 6 >= 2 ? repeatedHref(index) : orgHref(index)), + ) +}) + +describe(`route-module match construction (${BATCH} calls)`, () => { + defineCase( + 'ordinary application matches', + (index) => ordinary.matchRoutes(orgHref(index)).at(-1)!.routeId, + () => '/orgs/$orgId/catalog/$itemId', + ) + defineCase( + 'repeated installation matches', + (index) => repeated.matchRoutes(repeatedHref(index)).at(-1)!.routeId, + (index) => `${MODULE}#${index % 2 ? 'userCatalog' : 'orgCatalog'}:/$itemId`, + ) +}) + +// These focused cases compare the accepted implementation with an optional +// optimization. The original baseline has no binder, so retain the ten shared +// workloads above and omit this group there. +if ('bindRouteScopeOptions' in moduleWiring) { + const bind = moduleWiring.bindRouteScopeOptions as ( + moduleId: string, + options: object, + router: AnyRouter, + nearestRouteId: string, + ) => { _module: unknown } + const installation = (index: number) => + `${MODULE}#${index % 2 ? 'userCatalog' : 'orgCatalog'}` + // Resolve callers from actual matches, as the framework bindings do. Keep + // match construction outside timing to isolate the binding operation. + const nearestRouteIds = Array.from({ length: BATCH }, (_, index) => { + const routeId = repeated.matchRoutes(repeatedHref(index)).at(-1)!.routeId + expect(routeId).toBe(`${installation(index)}:/$itemId`) + return routeId + }) + const localOptions = repeatedOptions.map(({ params }) => ({ + to: '/$itemId', + params, + })) + const installedRedirectOptions = localOptions.map( + (options, index) => + installationRedirects[index % 2]!(options as any).options, + ) + const bindScope = (moduleId: string, options: object, index: number) => + bind(moduleId, options, repeated, nearestRouteIds[index]!)._module as string + + describe(`route-module scope binding (${BATCH} calls, candidate only)`, () => { + // defineCase asserts each concrete returned installation before timing, + // then checksums the same returned value during every timed batch. + defineCase( + 'deferred redirect constraints through module receivers', + (index) => bindScope(MODULE, deferredRedirectOptions[index]!, index), + installation, + ) + defineCase( + 'deferred redirect constraints through named receivers', + (index) => + bindScope(installation(index), deferredRedirectOptions[index]!, index), + installation, + ) + defineCase( + 'installed redirect options through module receivers', + (index) => bindScope(MODULE, installedRedirectOptions[index]!, index), + installation, + ) + defineCase( + 'module-local options through module receivers', + (index) => bindScope(MODULE, localOptions[index]!, index), + () => MODULE, + ) + }) +} diff --git a/packages/router-core/vite.config.ts b/packages/router-core/vite.config.ts index 97859dda97..a76be3c7de 100644 --- a/packages/router-core/vite.config.ts +++ b/packages/router-core/vite.config.ts @@ -42,6 +42,8 @@ export default mergeConfig( tanstackViteConfig({ entry: [ './src/index.ts', + './src/route-module-internal.ts', + './src/extensions.ts', './src/ssr/client.ts', './src/ssr/server.ts', './src/scroll-restoration-script/client.ts', diff --git a/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx b/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx index 7efcaffca2..3330579087 100644 --- a/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx +++ b/packages/router-devtools-core/src/BaseTanStackRouterDevtoolsPanel.tsx @@ -7,6 +7,7 @@ import { rootRouteId, trimPath, } from '@tanstack/router-core' +import { getRouteModuleId } from '@tanstack/router-core/_internal/route-module' import { For, Match, @@ -27,6 +28,14 @@ import { AgeTicker } from './AgeTicker' // import type { DevtoolsPanelOptions } from './TanStackRouterDevtoolsPanel' import { NavigateButton } from './NavigateButton' +import { + getModuleIds, + getModuleLocalPath, + getModuleRoot, + getModuleRootId, + getModuleRoutes, + getParentModuleId, +} from './routeModules' import type { AnyContext, AnyRoute, @@ -106,6 +115,33 @@ function NavigateLink(props: { ) } +/** How the panel shows route modules: collapsed groups and module details. */ +interface ModuleControls { + isCollapsed: (moduleId: string) => boolean + toggle: (moduleId: string) => void + open: (moduleId: string) => void +} + +function ModuleBadge(props: { + moduleId: string + open: (moduleId: string) => void +}) { + const styles = useStyles() + return ( + + ) +} + function RouteComp({ routerState, pendingMatches, @@ -114,6 +150,7 @@ function RouteComp({ isRoot, activeId, setActiveId, + modules, }: { routerState: Accessor< RouterState< @@ -146,8 +183,13 @@ function RouteComp({ isRoot?: boolean activeId: Accessor setActiveId: (id: string) => void + modules: ModuleControls }) { const styles = useStyles() + // A route module's root heads a collapsible group of the module's routes. + const moduleId = getModuleRootId(route) + const collapsed = () => + moduleId !== undefined && modules.isCollapsed(moduleId) const matches = createMemo(() => pendingMatches().length ? pendingMatches() : routerState().matches, ) @@ -197,7 +239,12 @@ function RouteComp({ }) return ( -
+
} > + + {(id) => ( + + )} + {isRoot ? rootRouteId : route.path || trimPath(route.id)}{' '} {param()} + + {(id) => } +
- {route.children?.length ? ( -
+ {route.children?.length && !collapsed() ? ( +
{[...(route.children as Array)] .sort((a, b) => { return a.rank - b.rank @@ -244,6 +315,7 @@ function RouteComp({ route={r} activeId={activeId} setActiveId={setActiveId} + modules={modules} /> ))}
@@ -281,6 +353,46 @@ export const BaseTanStackRouterDevtoolsPanel = '', ) + // Route modules: collapsed groups, the module shown in the details pane, + // and the module the route tree is narrowed to. + const [collapsedModules, setCollapsedModules] = useLocalStorage< + Array + >('tanstackRouterDevtoolsCollapsedModules', []) + const [activeModuleId, setActiveModuleId] = useLocalStorage( + 'tanstackRouterDevtoolsActiveModuleId', + '', + ) + const [moduleFilter, setModuleFilter] = createSignal('') + const moduleIds = createMemo(() => getModuleIds(router())) + const selectMatch = (id: string) => { + setActiveModuleId('') + setActiveId(id) + } + const modules: ModuleControls = { + isCollapsed: (moduleId) => (collapsedModules() ?? []).includes(moduleId), + toggle: (moduleId) => + setCollapsedModules((previous = []) => + previous.includes(moduleId) + ? previous.filter((id) => id !== moduleId) + : [...previous, moduleId], + ), + open: (moduleId) => { + setActiveId('') + setActiveModuleId(moduleId) + }, + } + const activeModule = createMemo(() => { + const moduleId = activeModuleId() + return moduleId && getModuleRoot(router(), moduleId) + ? moduleId + : undefined + }) + const routeTreeRoot = createMemo( + () => + (moduleFilter() && getModuleRoot(router(), moduleFilter())) || + router().routeTree, + ) + const [history, setHistory] = createSignal>([]) const [hasHistoryOverflowed, setHasHistoryOverflowed] = createSignal(false) @@ -397,6 +509,12 @@ export const BaseTanStackRouterDevtoolsPanel = ), ), ) + const activeMatchModuleRoute = createMemo(() => { + const routeId = activeMatch()?.routeId + return routeId !== undefined && getRouteModuleId(routeId) !== undefined + ? (router().routesById[routeId] as AnyRoute | undefined) + : undefined + }) const activeMatchLoaderData = createMemo(() => activeMatch()?.loaderData) const activeMatchValue = createMemo(() => activeMatch()) const locationSearchValue = createMemo(() => routerState().location.search) @@ -544,15 +662,36 @@ export const BaseTanStackRouterDevtoolsPanel =
- + +
+ +
+
+ + {(route) => ( + + )} +
@@ -565,7 +704,7 @@ export const BaseTanStackRouterDevtoolsPanel = role="button" aria-label={`Open match details for ${match.id}`} onClick={() => - setActiveId(activeId() === match.id ? '' : match.id) + selectMatch(activeId() === match.id ? '' : match.id) } class={cx(styles().matchRow(match === activeMatch()))} > @@ -588,6 +727,14 @@ export const BaseTanStackRouterDevtoolsPanel = {`${match.routeId === rootRouteId ? rootRouteId : match.pathname}`} + + {(moduleId) => ( + + )} +
) @@ -658,7 +805,7 @@ export const BaseTanStackRouterDevtoolsPanel = role="button" aria-label={`Open match details for ${match.id}`} onClick={() => - setActiveId(activeId() === match.id ? '' : match.id) + selectMatch(activeId() === match.id ? '' : match.id) } class={cx(styles().matchRow(match === activeMatch()))} > @@ -687,7 +834,15 @@ export const BaseTanStackRouterDevtoolsPanel =
) : null}
- {activeMatch() && activeMatch()?.status ? ( + {activeModule() ? ( + + ) : activeMatch() && activeMatch()?.status ? (
Match Details
@@ -711,6 +866,33 @@ export const BaseTanStackRouterDevtoolsPanel = {activeMatch()?.id}
+ + {(route) => ( + <> +
+
Module:
+
+ +
+
+
+
Local path:
+
+ {getModuleLocalPath(router(), route())} +
+
+
+
Path:
+
+ {route().fullPath} +
+
+ + )} +
State:
@@ -789,6 +971,81 @@ export const BaseTanStackRouterDevtoolsPanel = ) } +function ModuleDetails(props: { + moduleId: string + router: Accessor + routerState: Accessor + open: (moduleId: string) => void + selectMatch: (id: string) => void +}) { + const styles = useStyles() + const root = () => getModuleRoot(props.router(), props.moduleId)! + const parentModuleId = () => getParentModuleId(props.router(), props.moduleId) + const routes = () => getModuleRoutes(props.router(), props.moduleId) + const matches = () => + (props.routerState().matches as Array).filter( + (match) => getRouteModuleId(match.routeId) === props.moduleId, + ) + return ( +
+
Module Details
+
+
+
Module:
+
+ {props.moduleId} +
+
+
+
Mount path:
+
+ {root().fullPath} +
+
+
+
Parent module:
+
+ + {(id) => } + +
+
+
+
Routes (local / final path)
+ + {(route) => ( +
+ {getModuleLocalPath(props.router(), route)} + {route.fullPath} +
+ )} +
+
Active Matches
+ None
} + > + + {(match) => ( +
props.selectMatch(match.id)} + > + {match.pathname} +
+ )} +
+ +
+ ) +} + function CopyButton({ getValue }: { getValue: () => string }) { const [copied, setCopied] = createSignal(false) diff --git a/packages/router-devtools-core/src/routeModules.ts b/packages/router-devtools-core/src/routeModules.ts new file mode 100644 index 0000000000..b010e43b26 --- /dev/null +++ b/packages/router-devtools-core/src/routeModules.ts @@ -0,0 +1,75 @@ +import { getRouteModuleId } from '@tanstack/router-core/_internal/route-module' +import type { AnyRoute, AnyRouter } from '@tanstack/router-core' + +/** The module id when `route` is the root route of a mounted route module. */ +export function getModuleRootId(route: AnyRoute): string | undefined { + const moduleId = getRouteModuleId(route.id) + return moduleId !== undefined && route.id === `${moduleId}:` + ? moduleId + : undefined +} + +export function getModuleRoot( + router: AnyRouter, + moduleId: string, +): AnyRoute | undefined { + return router.routesById[`${moduleId}:`] as AnyRoute | undefined +} + +/** The ids of the route modules mounted in the router, in tree order. */ +export function getModuleIds(router: AnyRouter): Array { + const ids: Array = [] + for (const route of Object.values(router.routesById) as Array) { + const moduleId = getModuleRootId(route) + if (moduleId !== undefined) { + ids.push(moduleId) + } + } + return ids +} + +/** The module that mounts `moduleId`, or `undefined` for the application. */ +export function getParentModuleId( + router: AnyRouter, + moduleId: string, +): string | undefined { + let route = getModuleRoot(router, moduleId)?.parentRoute as + | AnyRoute + | undefined + while (route) { + const parentModuleId = getRouteModuleId(route.id) + if (parentModuleId !== undefined) { + return parentModuleId + } + route = route.parentRoute as AnyRoute | undefined + } + return undefined +} + +/** The routes a module owns, without those of modules it mounts. */ +export function getModuleRoutes( + router: AnyRouter, + moduleId: string, +): Array { + return (Object.values(router.routesById) as Array).filter( + (route) => getRouteModuleId(route.id) === moduleId, + ) +} + +/** + * The path module code uses for a module route: its full path below the + * module root, wherever the module is mounted. + */ +export function getModuleLocalPath( + router: AnyRouter, + route: AnyRoute, +): string | undefined { + const moduleId = getRouteModuleId(route.id) + const root = + moduleId === undefined ? undefined : getModuleRoot(router, moduleId) + if (!root) { + return undefined + } + const base = root.fullPath.replace(/\/$/, '') + return route.fullPath.slice(base.length) || '/' +} diff --git a/packages/router-devtools-core/src/useStyles.tsx b/packages/router-devtools-core/src/useStyles.tsx index 32908c524d..e2478b9ffa 100644 --- a/packages/router-devtools-core/src/useStyles.tsx +++ b/packages/router-devtools-core/src/useStyles.tsx @@ -381,6 +381,54 @@ const stylesFactory = (shadowDOMTarget?: ShadowRoot) => { font-size: ${fontSize.xs}; line-height: ${lineHeight['xs']}; `, + moduleBadge: css` + background: ${colors.purple[900]}${alpha[70]}; + color: ${colors.purple[300]}; + display: inline-block; + padding: 0 ${tokens.size[1.5]}; + margin-left: ${size[1]}; + border-radius: ${border.radius.full}; + border: 1px solid ${colors.purple[400]}; + font-size: ${font.size.xs}; + line-height: ${lineHeight['xs']}; + white-space: nowrap; + cursor: pointer; + `, + moduleToggle: css` + background: none; + border: none; + padding: 0; + margin-right: ${size[1]}; + color: ${colors.gray[400]}; + font-size: ${font.size.xs}; + cursor: pointer; + `, + moduleChildren: css` + border-left-color: ${colors.purple[700]}; + `, + moduleFilter: css` + display: flex; + padding: ${size[1]} ${size[2]}; + border-bottom: 1px solid ${colors.darkGray[400]}; + & > select { + background: ${colors.darkGray[700]}; + color: ${colors.gray[300]}; + border: 1px solid ${colors.gray[700]}; + border-radius: ${border.radius.sm}; + font-size: ${font.size.xs}; + } + `, + moduleRouteRow: css` + display: flex; + justify-content: space-between; + gap: ${size[2]}; + padding: ${size[1]} ${size[2]}; + border-bottom: 1px solid ${colors.darkGray[400]}; + font-size: ${font.size.xs}; + & > code:last-child { + color: ${colors.gray[400]}; + } + `, nestedRouteRow: (isRoot: boolean) => { const base = css` margin-left: ${isRoot ? 0 : size[3.5]}; diff --git a/packages/router-devtools-core/tests/route-modules.test.ts b/packages/router-devtools-core/tests/route-modules.test.ts new file mode 100644 index 0000000000..2fe731c4b1 --- /dev/null +++ b/packages/router-devtools-core/tests/route-modules.test.ts @@ -0,0 +1,198 @@ +import { afterEach, beforeAll, expect, test, vi } from 'vitest' +import { + BaseRootRoute, + BaseRoute, + RouterCore, + createNonReactiveMutableStore, + createNonReactiveReadonlyStore, +} from '@tanstack/router-core' +import { mountRouteModule } from '@tanstack/router-core/_internal/route-module' +import { TanStackRouterDevtoolsPanelCore } from '../src/TanStackRouterDevtoolsPanelCore' +import type { AnyRoute } from '@tanstack/router-core' + +beforeAll(async () => { + // Browsers expose elements with an id as window properties, and goober + // finds its style sheet as `window._goober`. jsdom does not, so without + // this every style rule adds a style element and later tests slow down. + Object.defineProperty(window, '_goober', { + configurable: true, + get: () => document.getElementById('_goober'), + }) + await import('../src/BaseTanStackRouterDevtoolsPanel') +}, 30_000) + +const panels: Array = [] + +afterEach(() => { + // Unmounting stops the panel's timers and reactive roots. + panels.splice(0).forEach((panel) => panel.unmount()) + document.body.innerHTML = '' + localStorage.clear() +}) + +function createModuleRoot(moduleId: string) { + return new BaseRoute({ _module: moduleId } as any) as AnyRoute +} + +/** + * root + * └── /shop + * └── @acme/products (mounted at /products) + * ├── / + * ├── /$productId + * └── @acme/reviews (mounted at /reviews) + * └── / + */ +function setup(pathname: string) { + const root = new BaseRootRoute({}) + const shop = new BaseRoute({ getParentRoute: () => root, path: '/shop' }) + const products = createModuleRoot('@acme/products') + const reviews = createModuleRoot('@acme/reviews') + reviews.addChildren([ + new BaseRoute({ getParentRoute: () => reviews, path: '/' }), + ]) + products.addChildren([ + new BaseRoute({ getParentRoute: () => products, path: '/' }), + new BaseRoute({ getParentRoute: () => products, path: '/$productId' }), + reviews, + ]) + mountRouteModule(reviews, { parent: () => products, at: '/reviews' } as any) + mountRouteModule(products, { + parent: () => shop as AnyRoute, + at: '/products', + } as any) + const routeTree = root.addChildren([shop.addChildren([products])]) + const router = new RouterCore({ routeTree, isServer: false }, () => ({ + createMutableStore: createNonReactiveMutableStore, + createReadonlyStore: createNonReactiveReadonlyStore, + batch: (fn) => fn(), + })) + const panel = new TanStackRouterDevtoolsPanelCore({ + router, + routerState: { ...router.state, matches: router.matchRoutes(pathname, {}) }, + }) + const container = document.createElement('div') + document.body.append(container) + panel.mount(container) + panels.push(panel) + return container +} + +function find(container: HTMLElement, label: string) { + return container.querySelector(`[aria-label="${label}"]`) +} + +async function waitFor(container: HTMLElement, label: string) { + await vi.waitFor(() => expect(find(container, label)).not.toBeNull()) + return find(container, label)! +} + +/** The element whose own text is `text` (tab buttons, section headers). */ +async function waitForText(container: HTMLElement, text: string) { + const lookup = () => + [...container.querySelectorAll('*')].find( + (element) => + element.childElementCount === 0 && element.textContent === text, + ) + await vi.waitFor(() => expect(lookup()).toBeDefined()) + return lookup()! +} + +test('groups module routes, nested where their module is mounted', async () => { + const container = setup('/shop/products/7') + const products = await waitFor(container, 'Route module @acme/products') + + expect( + products.querySelector('[aria-label="Route module @acme/reviews"]'), + ).not.toBeNull() + expect( + products.querySelector( + '[aria-label="Open match details for @acme/products:/$productId"]', + ), + ).not.toBeNull() +}) + +test('collapses a module group and remembers it', async () => { + const container = setup('/shop/products/7') + ;(await waitFor(container, 'Collapse @acme/products')).click() + + await vi.waitFor(() => + expect( + find(container, 'Open match details for @acme/products:/$productId'), + ).toBeNull(), + ) + expect( + JSON.parse(localStorage.getItem('tanstackRouterDevtoolsCollapsedModules')!), + ).toEqual(['@acme/products']) + ;(await waitFor(container, 'Expand @acme/products')).click() + await waitFor(container, 'Open match details for @acme/products:/$productId') +}) + +test('filters the route tree to one module', async () => { + const container = setup('/shop/products/7') + const filter = (await waitFor( + container, + 'Show routes of', + )) as HTMLSelectElement + filter.value = '@acme/reviews' + filter.dispatchEvent(new Event('change')) + + await vi.waitFor(() => + expect( + find(container, 'Open match details for @acme/products:/$productId'), + ).toBeNull(), + ) + expect(find(container, 'Route module @acme/reviews')).not.toBeNull() + expect( + find(container, 'Open match details for @acme/reviews:/'), + ).not.toBeNull() +}) + +test('shows a module with its mount, parent module, routes and matches', async () => { + const container = setup('/shop/products/reviews') + ;(await waitFor(container, 'Open module details for @acme/reviews')).click() + + const details = await waitFor(container, 'Module details') + const text = details.textContent + expect(text).toContain('@acme/reviews') + expect(text).toContain('Mount path:/shop/products/reviews') + expect(text).toContain('Parent module:@acme/products') + // The module's own routes, with the local and the final path. + const route = details.querySelector('[title="@acme/reviews:/"]')! + expect( + [...route.querySelectorAll('code')].map((code) => code.textContent), + ).toEqual(['/', '/shop/products/reviews/']) + expect(text).not.toContain('/$productId') + expect( + details.querySelector( + '[aria-label^="Open match details for @acme/reviews:/"]', + ), + ).not.toBeNull() +}) + +test('badges matches with their module and shows local and final paths', async () => { + const container = setup('/shop/products/7') + ;(await waitForText(container, 'Matches')).click() + await vi.waitFor(() => + expect( + container.querySelector( + '[aria-label^="Open match details for @acme/products:/$productId"] [aria-label="Open module details for @acme/products"]', + ), + ).not.toBeNull(), + ) + ;(await waitForText(container, 'Routes')).click() + ;( + await waitFor( + container, + 'Open match details for @acme/products:/$productId', + ) + ).click() + const details = (await waitForText(container, 'Match Details')).parentElement! + expect(details.textContent).toContain('Local path:/$productId') + expect(details.textContent).toContain('Path:/shop/products/$productId') + expect( + details.querySelector( + '[aria-label="Open module details for @acme/products"]', + ), + ).not.toBeNull() +}) diff --git a/packages/router-generator/src/config.ts b/packages/router-generator/src/config.ts index 5c719183db..2e7b70fca0 100644 --- a/packages/router-generator/src/config.ts +++ b/packages/router-generator/src/config.ts @@ -2,8 +2,15 @@ import path from 'node:path' import { existsSync, readFileSync } from 'node:fs' import { z } from 'zod' import { virtualRootRouteSchema } from './filesystem/virtual/config' +import { routeModulesOptionSchema } from './route-module/declaration' import type { GeneratorPlugin } from './plugin/types' +export const DEFAULT_ROUTE_TREE_FILE_HEADER = [ + '/* eslint-disable */', + '// @ts-nocheck', + '// noinspection JSUnusedGlobalSymbols', +] as const + const tokenJsonRegexSchema = z.object({ regex: z.string(), flags: z.string().optional(), @@ -32,11 +39,7 @@ export const baseConfigSchema = z.object({ routeTreeFileHeader: z .array(z.string()) .optional() - .default([ - '/* eslint-disable */', - '// @ts-nocheck', - '// noinspection JSUnusedGlobalSymbols', - ]), + .default([...DEFAULT_ROUTE_TREE_FILE_HEADER]), indexToken: tokenMatcherSchema.optional().default('index'), routeToken: tokenMatcherSchema.optional().default('route'), pathParamsAllowedCharacters: z @@ -79,6 +82,12 @@ export const configSchema = baseConfigSchema.extend({ plugins: z.array(z.custom()).optional(), tmpDir: z.string().optional().default(''), importRoutesUsingAbsolutePaths: z.boolean().optional().default(false), + /** + * Route modules this application installs (`includes`) or references + * (`uses`). Route modules themselves declare these in their package.json + * (`tanstack.router.module`). + */ + routeModules: routeModulesOptionSchema.optional(), }) export type Config = z.infer @@ -175,6 +184,12 @@ export function getConfig( } function validateConfig(config: Config) { + if (config.disableTypes && config.routeModules) { + throw new Error( + `Route modules require TypeScript: "routeModules" cannot be used with "disableTypes".`, + ) + } + if (typeof config.experimental?.enableCodeSplitting !== 'undefined') { const message = ` ------ diff --git a/packages/router-generator/src/generated-names.ts b/packages/router-generator/src/generated-names.ts new file mode 100644 index 0000000000..82431dc744 --- /dev/null +++ b/packages/router-generator/src/generated-names.ts @@ -0,0 +1,120 @@ +/** A binding family emitted from one canonical route/package identity. */ +export interface GeneratedName { + key: string + preferred: string + suffixes: ReadonlyArray +} + +/** + * Allocate complete binding families together. Sorting canonical identities + * makes allocations independent of directory order, checkout paths and caches. + */ +export function allocateGeneratedNames( + entries: ReadonlyArray, + reserved: Iterable, +): Map { + const occupied = new Set(reserved) + const names = new Map() + for (const entry of [...entries].sort((a, b) => + a.key < b.key ? -1 : a.key > b.key ? 1 : 0, + )) { + if (names.has(entry.key)) { + continue + } + let candidate = entry.preferred + let index = 1 + while (entry.suffixes.some((suffix) => occupied.has(candidate + suffix))) { + candidate = `${entry.preferred}_${++index}` + } + for (const suffix of entry.suffixes) { + occupied.add(candidate + suffix) + } + names.set(entry.key, candidate) + } + return names +} + +export const routeBindingSuffixes = [ + 'RouteImport', + 'Route', + 'RouteChildren', + 'RouteWithChildren', +] as const + +export const moduleBindingSuffixes = [ + 'Router', + 'InstalledRouters', + 'InstalledRoutesById', + 'InstalledHostParams', + 'HostedRouter', + 'RouteModule', + 'StartModules', + ...routeBindingSuffixes.map((suffix) => `Module${suffix}`), +] as const + +export const generatedPublicNames = [ + 'Link', + 'createLink', + 'linkOptions', + 'Navigate', + 'useNavigate', + 'redirect', + 'MatchRoute', + 'useMatchRoute', + 'useRouter', + 'getRouteApi', + 'useMatch', + 'useMatches', + 'useParentMatches', + 'useChildMatches', + 'useLoaderData', + 'useLoaderDeps', + 'useSearch', + 'useParams', + 'useRouteContext', + 'useLocation', + 'useRouterState', + 'useLinkProps', + 'useBlocker', + 'notFound', + 'isScopedMatch', + 'createFileRoute', + 'createModuleRoot', + 'createServerFn', + 'createMiddleware', + 'createStartModule', + 'ValidateLinkOptions', + 'ValidateLinkOptionsArray', + 'ValidateNavigateOptions', + 'ValidateNavigateOptionsArray', + 'ValidateRedirectOptions', + 'ValidateRedirectOptionsArray', + 'ValidateFromPath', + 'ValidateToPath', + 'ValidateSearch', + 'ValidateParams', + 'ValidateId', + 'ValidateUseSearchOptions', + 'ValidateUseParamsOptions', + 'RouteModuleRouter', + 'RouteModuleRegister', + 'rootRouteImport', + 'routeTree', + 'FileRoutesByPath', + 'FileRoutesByFullPath', + 'FileRoutesByTo', + 'FileRoutesById', + 'FileRouteTypes', + 'RootRouteChildren', + 'rootRouteChildren', + 'MountedModuleHostParams', + 'RouteModuleRoutesById', + 'mountRouteModule', + 'lazyFn', + 'lazyRouteComponent', + 'InstallationRoutesById', + 'ScopeRouter', + 'ScopedRouter', + 'RouteScope', + 'HostedRouter', +] as const diff --git a/packages/router-generator/src/generator.ts b/packages/router-generator/src/generator.ts index 91f87dadda..d40354318c 100644 --- a/packages/router-generator/src/generator.ts +++ b/packages/router-generator/src/generator.ts @@ -1,8 +1,12 @@ import path from 'node:path' import * as fsp from 'node:fs/promises' -import { existsSync, mkdirSync } from 'node:fs' +import { existsSync, mkdirSync, realpathSync } from 'node:fs' import crypto from 'node:crypto' import { rootRouteId } from '@tanstack/router-core' +import { + getParamNames, + parseSegments, +} from '@tanstack/router-core/_internal/route-module' import { logging } from './logger' import { isVirtualConfigFile, @@ -29,6 +33,7 @@ import { getImportForRouteNode, getResolvedRouteNodeVariableName, hasParentRoute, + inferFullPath, isSegmentPathless, mergeImportDeclarations, multiSortBy, @@ -42,8 +47,48 @@ import { trimPathLeft, } from './utils' import { fillTemplate, getTargetTemplate } from './template' +import { + getHostPath, + getInstallationRouteId, + resolveRouteModuleContext, +} from './route-module/context' +import { + ROUTE_CONTRACT_FILE, + ROUTE_MODULE_FILE, + ROUTE_SCOPE_FILE, + START_MODULES_FILE, + buildRouteContractSource, + buildRouteModuleSource, + buildRouteNamespaceSource, + buildRouteScopeSource, + buildStartModulesSource, + getModuleIdentifier, + getMountVariableName, + getRouteNamespaceFile, +} from './route-module/emit' +import { + ROUTE_MODULE_MANIFEST_VERSION, + computeTopologyToken, + writeManifest, +} from './route-module/manifest' +import { findPackageRoot } from './route-module/declaration' +import { pruneServerOnlySubtrees } from './pruneServerOnlySubtrees' +import { isPrerenderableRoute } from './routeClassification' import { transform } from './transform/transform' import { validateRouteParams } from './validate-route-params' +import { + allocateGeneratedNames, + generatedPublicNames, + moduleBindingSuffixes, + routeBindingSuffixes, +} from './generated-names' +import { DEFAULT_ROUTE_TREE_FILE_HEADER } from './config' +import type { RouteModuleContext } from './route-module/context' +import type { + ManifestInstalledModule, + ManifestRoute, + RouteModuleManifest, +} from './route-module/manifest' import type { GeneratorPlugin } from './plugin/types' import type { TargetTemplate } from './template' import type { @@ -219,6 +264,11 @@ export class Generator { private plugins: Array = [] private static routeGroupPatternRegex = /\(.+\)/ private physicalDirectories: Array = [] + /** Route-module role of this package, refreshed on every run. */ + private routeModuleContext: RouteModuleContext | undefined + private originalRouteNames = new WeakMap() + /** Files that change the route-module context (package.json, manifests). */ + private routeModuleFiles: Array = [] /** * Token regexes are pre-compiled once here and reused throughout route processing. @@ -295,13 +345,134 @@ export class Generator { : path.resolve(this.root, this.config.routesDirectory) } + /** + * The route files of the route tree by path, with their route ids: the + * package's own files and the files of the route modules it mounts. + */ public getRoutesByFileMap(): GetRoutesByFileMapResult { - return new Map( + const moduleId = + this.routeModuleContext?.declaration.mode === 'module' + ? this.routeModuleContext.declaration.moduleId + : undefined + const map: GetRoutesByFileMapResult = new Map( [...this.routeNodeCache.entries()].map(([filePath, cacheEntry]) => [ filePath, - { routeId: cacheEntry.routeId }, + { + routeId: + moduleId === undefined + ? cacheEntry.routeId + : cacheEntry.routeId === `/${rootPathId}` + ? `${moduleId}:` + : `${moduleId}:${cacheEntry.routeId}`, + }, ]), ) + for (const mount of this.routeModuleContext?.mounts ?? []) { + for (const { file, routeId } of mount.routeFiles) { + map.set(file, { routeId }) + } + } + return map + } + + /** + * The routes of the route modules mounted by this package, with their files + * and parent ids in this package's route tree (for integrations that index + * routes by id, such as Start's asset manifest). + */ + public getMountedRouteModuleRoutes(): Array<{ + id: string + parent: string + filePath: string | undefined + fullPath: string + prerender?: boolean + }> { + const context = this.routeModuleContext + const crawlingResult = this.crawlingResult + if (!context || !crawlingResult) { + return [] + } + const ownModuleId = + context.declaration.mode === 'module' + ? context.declaration.moduleId + : undefined + const hostId = (node: RouteNode | undefined) => + ownModuleId === undefined + ? (node?.routePath ?? rootRouteId) + : node + ? `${ownModuleId}:${node.routePath ?? ''}` + : `${ownModuleId}:` + const routes: Array<{ + id: string + parent: string + filePath: string | undefined + fullPath: string + prerender?: boolean + }> = [] + for (const mount of context.mounts) { + const mountNode = this.findMountNode(crawlingResult.acc, mount.key) + const files = new Map( + mount.routeFiles.map(({ file, routeId }) => [routeId, file]), + ) + for (const route of mount.manifest.routes) { + routes.push({ + id: getInstallationRouteId(mount, route.id), + parent: route.parent + ? getInstallationRouteId(mount, route.parent) + : hostId(mountNode.parent), + filePath: files.get(route.id), + fullPath: + `${mountNode.parent ? inferFullPath(mountNode.parent).replace(/\/$/, '') : ''}${mount.at ?? ''}${route.fullPath}` || + '/', + prerender: route.prerender, + }) + } + } + return routes + } + + /** + * Files outside the routes directory that change the generated route tree: + * the package.json and the manifests of mounted and used route modules. + * Bundler integrations add them to their watchers. + */ + /** Current provider tree paths used by client-only bundler resolution. */ + public getRouteModuleClientTrees(): Array<{ + filePath: string + clientFilePath: string + }> { + return [ + ...new Map( + (this.routeModuleContext?.mounts ?? []).flatMap((mount) => + mount.clientTrees.map((entry) => [entry.filePath, entry] as const), + ), + ).values(), + ] + } + + /** Same page predicate for ordinary routes and installed module routes. */ + public getPrerenderableRoutePaths(): Array { + const own = + this.crawlingResult?.acc.routeNodes + .filter(isPrerenderableRoute) + .map(inferFullPath) ?? [] + const mounted = this.getMountedRouteModuleRoutes() + .filter((route) => route.prerender) + .map((route) => route.fullPath) + return [ + ...new Set( + [...own, ...mounted].filter((fullPath) => !fullPath.includes('$')), + ), + ] + } + + private getClientRouteTreePath() { + const parsed = path.parse(this.generatedRouteTreePath) + return path.join(parsed.dir, `${parsed.name}.client${parsed.ext}`) + } + + public getRouteModuleWatchFiles(): Array { + return [...this.routeModuleFiles] } public async run(event?: GeneratorEvent): Promise { @@ -385,6 +556,54 @@ export class Generator { private async generatorInternal() { let writeRouteTreeFile: boolean | 'force' = false + // The route-module context depends on package.json and on the manifests + // of other packages: a change there regenerates the outputs even when no + // route file changed. + const previousRouteModuleHash = this.routeModuleContext?.hash + const packageRoot = findPackageRoot(this.root) + const candidateWatchFiles = new Set( + packageRoot ? [path.join(packageRoot, 'package.json')] : [], + ) + this.routeModuleFiles = [...candidateWatchFiles] + this.routeModuleContext = resolveRouteModuleContext({ + root: this.root, + routeModules: this.config.routeModules, + onWatchFile: (file) => { + candidateWatchFiles.add(file) + this.routeModuleFiles = [...candidateWatchFiles] + }, + start: { + package: `@tanstack/${this.config.target}-start`, + generatedDirectory: path.dirname(this.generatedRouteTreePath), + }, + }) + if (this.routeModuleContext) { + if (this.config.disableTypes) { + throw new Error( + `[route modules] ${this.routeModuleContext.declaration.packageName}: route modules require TypeScript; "disableTypes" is not supported.`, + ) + } + this.routeModuleFiles = [ + ...new Set([ + ...candidateWatchFiles, + path.join( + this.routeModuleContext.declaration.packageRoot, + 'package.json', + ), + ...this.routeModuleContext.dependencyFiles, + ...this.routeModuleContext.watchFiles, + ]), + ] + } else { + const packageRoot = findPackageRoot(this.root) + this.routeModuleFiles = packageRoot + ? [path.join(packageRoot, 'package.json')] + : [] + } + if (this.routeModuleContext?.hash !== previousRouteModuleHash) { + writeRouteTreeFile = true + } + let getRouteNodesResult: GetRouteNodesResult if (this.config.virtualRouteConfig) { @@ -485,6 +704,8 @@ export class Generator { Generator.handleNode(node, acc, prefixMap, this.config) } + this.addRouteModuleMounts(acc) + this.crawlingResult = { rootRouteNode, routeFileResult, acc } // this is the first time the generator runs, so read in the route tree file if it exists yet @@ -585,6 +806,8 @@ export class Generator { } } + await this.writeRouteModuleFiles(rootRouteNode, acc) + this.plugins.map((plugin) => { return plugin.onRouteTreeChanged?.({ routeTree: buildResult.routeTree, @@ -596,6 +819,316 @@ export class Generator { this.swapCaches() } + /** + * Writes the generated files of route modules (scope, contract, runtime + * entry) and applications that mount them (scope), and the module manifest. + */ + private async writeRouteModuleFiles( + rootRouteNode: RouteNode, + acc: HandleNodeAccumulator, + ) { + const context = this.routeModuleContext + if (!context) { + return + } + const header = this.getGeneratedFileHeader(this.config) + const importFrom = (from: string, baseName: string) => + this.getRouteModuleImport(this.getRouteModuleFilePath(from), baseName) + const routeTreeImport = replaceBackslash( + removeExt( + `./${path.basename(this.generatedRouteTreePath)}`, + this.config.addExtensions, + ), + ) + + // Generated files live next to the Start file. + const startImport = replaceBackslash( + removeExt( + `./${path.basename(context.start?.file ?? 'start.ts')}`, + this.config.addExtensions, + ), + ) + + const files: Array<[string, string]> = [ + [ + ROUTE_SCOPE_FILE, + buildRouteScopeSource({ + context, + frameworkPackage: this.targetTemplate.fullPkg, + routeTreeImport, + startImport, + header, + ownRouteIds: + context.declaration.mode === 'module' + ? [ + `${context.declaration.moduleId}:`, + ...acc.routeNodes.map( + (node) => + `${context.declaration.moduleId}:${node.routePath ?? ''}`, + ), + ...context.mounts.flatMap((mount) => + mount.manifest.routes.map((route) => + getInstallationRouteId(mount, route.id), + ), + ), + ] + : [], + namespaceImport: (module) => + importFrom( + ROUTE_SCOPE_FILE, + getRouteNamespaceFile(module, context), + ), + }), + ], + ...context.scope.map((module): [string, string] => [ + getRouteNamespaceFile(module, context), + buildRouteNamespaceSource({ + context, + module, + frameworkPackage: this.targetTemplate.fullPkg, + routeTreeImport, + header, + }), + ]), + ] + if (context.declaration.mode === 'module') { + files.push( + [ + ROUTE_CONTRACT_FILE, + buildRouteContractSource({ + context, + frameworkPackage: this.targetTemplate.fullPkg, + routeTreeImport, + routeScopeImport: importFrom(ROUTE_CONTRACT_FILE, ROUTE_SCOPE_FILE), + header, + }), + ], + [ + ROUTE_MODULE_FILE, + buildRouteModuleSource({ + context, + routeTreeImport, + startImport, + header, + }), + ], + ) + } else { + const startModulesFile = this.getRouteModuleFilePath(START_MODULES_FILE) + if (context.start && context.mounts.length > 0) { + files.push([ + START_MODULES_FILE, + buildStartModulesSource({ context, startImport, header }), + ]) + } else if (existsSync(startModulesFile)) { + await fsp.rm(startModulesFile, { force: true }) + } + } + + if (context.declaration.mode === 'module') { + const pruned = pruneServerOnlySubtrees({ rootRouteNode, acc }) + const client = this.buildRouteTree({ + rootRouteNode, + routeFileResult: this.crawlingResult!.routeFileResult, + acc: { ...acc, ...pruned }, + config: { + ...this.config, + disableTypes: true, + // This runtime view omits the full tree's declarations and assertions. + // Keep it in ordinary TypeScript builds so they emit its JavaScript. + routeTreeFileHeader: [ + ...this.config.routeTreeFileHeader.filter( + (line) => line !== '// @ts-nocheck', + ), + '// @ts-nocheck', + ], + }, + }) + const filePath = this.getClientRouteTreePath() + // This runtime-only view has no public route contract. Give its incidental + // declaration a portable name instead of inferring dependency internals. + const source = /\.(?:[cm]?ts|tsx)$/.test(filePath) + ? client.routeTreeContent.replace( + /^export const routeTree = /m, + `export const routeTree: import('${this.targetTemplate.fullPkg}').AnyRoute = `, + ) + : client.routeTreeContent + const content = this.config.enableRouteTreeFormatting + ? await format(source, this.config) + : source + const existing = await this.fs.readFile(filePath) + if ( + existing === 'file-not-existing' || + existing.fileContent !== content + ) { + await this.safeFileWrite({ + filePath, + newContent: content, + strategy: + existing === 'file-not-existing' + ? { type: 'new-file' } + : { type: 'mtime', expectedMtimeMs: existing.stat.mtimeMs }, + }) + } + } + const namespaceNames = new Set( + context.scope.map((module) => + path.basename( + this.getRouteModuleFilePath(getRouteNamespaceFile(module, context)), + ), + ), + ) + for (const entry of await fsp.readdir( + path.dirname(this.generatedRouteTreePath), + )) { + if ( + /^routeScope\.gen\.namespace\d+\.ts$/.test(entry) && + !namespaceNames.has(entry) + ) { + await fsp.rm( + path.join(path.dirname(this.generatedRouteTreePath), entry), + ) + } + } + + for (const [baseName, source] of files) { + const content = this.config.enableRouteTreeFormatting + ? await format(source, this.config) + : source + const filePath = this.getRouteModuleFilePath(baseName) + const existing = await this.fs.readFile(filePath) + if ( + existing === 'file-not-existing' || + existing.fileContent !== content + ) { + await this.fs.writeFile(filePath, content) + } + } + + if (context.declaration.mode === 'module') { + await writeManifest( + context.declaration.packageRoot, + this.buildRouteModuleManifest(context, rootRouteNode, acc), + ) + } + } + + private buildRouteModuleManifest( + context: RouteModuleContext, + rootRouteNode: RouteNode, + acc: HandleNodeAccumulator, + ): RouteModuleManifest { + const { declaration } = context + const moduleId = declaration.moduleId! + const joinPath = (prefix: string, local: string) => + prefix === '' ? local : local === '/' ? `${prefix}/` : `${prefix}${local}` + const routeId = (node: RouteNode | undefined) => + node ? `${moduleId}:${node.routePath ?? ''}` : `${moduleId}:` + const routes: Array = [ + { id: `${moduleId}:`, parent: null, fullPath: '/', leaf: false }, + ...acc.routeNodes.map((node) => ({ + id: routeId(node), + parent: routeId(node.parent), + fullPath: inferFullPath(node), + leaf: !node.children?.length, + ...(isPrerenderableRoute(node) ? { prerender: true } : {}), + })), + ] + const routeFiles = [rootRouteNode, ...acc.routeNodes] + .filter((node) => node.fullPath && !node.isVirtual) + .map((node) => ({ + owner: [] as Array, + file: replaceBackslash( + path.relative(declaration.packageRoot, realpathSync(node.fullPath)), + ), + routeId: + node === rootRouteNode + ? `${moduleId}:` + : `${moduleId}:${node.routePath ?? ''}`, + })) + const modules: Array = [ + { + id: moduleId, + key: moduleId, + uses: context.scope + .filter( + (module) => + module.source.installedBy === null && + !context.mounts.some( + (mount) => mount.moduleId === module.moduleId, + ), + ) + .map((module) => module.moduleId), + mountPath: '/', + includedBy: null, + }, + ] + + for (const mount of context.mounts) { + const mountNode = this.findMountNode(acc, mount.key) + const parentPath = mountNode.parent + ? inferFullPath(mountNode.parent).replace(/\/$/, '') + : '' + const prefix = `${parentPath}${mount.at ?? ''}` + routes.push( + ...mount.manifest.routes.map((route) => ({ + ...route, + id: getInstallationRouteId(mount, route.id), + parent: route.parent + ? getInstallationRouteId(mount, route.parent) + : routeId(mountNode.parent), + fullPath: joinPath(prefix, route.fullPath), + })), + ) + routeFiles.push( + ...mount.manifest.routeFiles.map((entry) => ({ + ...entry, + owner: [mount.moduleId, ...entry.owner], + routeId: getInstallationRouteId(mount, entry.routeId), + })), + ) + modules.push( + ...mount.manifest.modules.map((installed) => ({ + ...installed, + key: installed.key === mount.moduleId ? mount.key : installed.key, + mountPath: joinPath(prefix, installed.mountPath), + includedBy: installed.includedBy ?? declaration.packageName, + })), + ) + } + + const topology: Omit = { + version: ROUTE_MODULE_MANIFEST_VERSION, + id: moduleId, + packageName: declaration.packageName, + routes, + routeFiles, + clientTrees: [ + { + owner: [], + file: replaceBackslash( + path.relative(declaration.packageRoot, this.generatedRouteTreePath), + ), + clientFile: replaceBackslash( + path.relative( + declaration.packageRoot, + this.getClientRouteTreePath(), + ), + ), + }, + ...context.mounts.flatMap((mount) => + mount.manifest.clientTrees.map((entry) => ({ + ...entry, + owner: [mount.moduleId, ...entry.owner], + })), + ), + ], + modules, + startModules: context.exportsStartModules, + } + return { ...topology, topologyToken: computeTopologyToken(topology) } + } + private swapCaches() { this.routeNodeCache = this.routeNodeShadowCache this.routeNodeShadowCache = new Map() @@ -609,7 +1142,70 @@ export class Generator { }) { const config = { ...this.config, ...(opts.config || {}) } - const { rootRouteNode, acc } = opts + const { rootRouteNode } = opts + // Mounted module roots only appear as children; integrations that rebuild + // the node list from the tree (e.g. Start's server-only pruning) may + // collect them, so they never count as route nodes of this package. + const acc: HandleNodeAccumulator = { + ...opts.acc, + routeNodes: opts.acc.routeNodes.filter((node) => !node._routeModuleMount), + } + + // Reserve names from the complete crawl even when Start rebuilds a pruned + // client tree. Repeated builds must not rename the surviving routes. + const namingNodes = this.crawlingResult?.acc.routeNodes ?? acc.routeNodes + const context = this.routeModuleContext + const moduleIds = new Set([ + ...(context?.visibleContracts ?? []), + ...(context?.mounts.flatMap((mount) => [mount.moduleId, mount.key]) ?? + []), + ...(context?.scope.flatMap((module) => [ + module.key, + module.source.contractPackage, + ...(module.hostedThrough ? [module.hostedThrough] : []), + ]) ?? []), + ]) + const nodeKey = (node: RouteNode) => + `route:${node.routePath ?? ''}:${node.filePath}:${node._fsRouteType}` + const names = allocateGeneratedNames( + [ + ...namingNodes.map((node) => { + let preferred = this.originalRouteNames.get(node) + if (preferred === undefined) { + preferred = node.variableName + this.originalRouteNames.set(node, preferred) + } + return { + key: nodeKey(node), + preferred, + suffixes: routeBindingSuffixes, + } + }), + ...[...moduleIds].map((id) => ({ + key: `module:${id}`, + preferred: getModuleIdentifier(id), + suffixes: moduleBindingSuffixes, + })), + ], + [ + ...generatedPublicNames, + ...(context?.scope.map((module) => module.namespace) ?? []), + ], + ) + for (const node of namingNodes) { + node.variableName = names.get(nodeKey(node))! + } + if (context) { + context.identifiers = new Map( + [...moduleIds].map((id) => [id, names.get(`module:${id}`)!]), + ) + for (const mount of context.mounts) { + this.findMountNode(acc, mount.key).variableName = getMountVariableName( + mount.key, + context.identifiers, + ) + } + } // Use pre-compiled regex if config hasn't been overridden, otherwise create new one const indexTokenSegmentRegex = @@ -622,13 +1218,23 @@ export class Generator { indexTokenSegmentRegex, ) + const routeModule = this.routeModuleContext + const moduleId = + routeModule?.declaration.mode === 'module' + ? routeModule.declaration.moduleId! + : undefined + // Route modules qualify their route ids with the module id. + const qualifyId = (id: string) => + moduleId === undefined ? id : `${moduleId}:${id}` + const rootId = moduleId === undefined ? rootRouteId : `${moduleId}:` + const routeImports: Array = [] const virtualRouteNodes: Array = [] for (const node of sortedRouteNodes) { if (node.isVirtual) { virtualRouteNodes.push( - `const ${node.variableName}RouteImport = createFileRoute('${node.routePath}')()`, + `const ${node.variableName}RouteImport = createFileRoute('${qualifyId(node.routePath ?? '')}')()`, ) } else { routeImports.push( @@ -646,9 +1252,94 @@ export class Generator { if (virtualRouteNodes.length > 0) { imports.push({ specifiers: [{ imported: 'createFileRoute' }], - source: this.targetTemplate.fullPkg, + source: + moduleId === undefined + ? this.targetTemplate.fullPkg + : this.getRouteModuleImport( + this.generatedRouteTreePath, + ROUTE_SCOPE_FILE, + ), }) } + // Mounted modules are validated before their mounts are emitted: the + // installations used modules link into assume valid host params. + this.checkRouteModuleFullPaths(acc) + this.checkRouteModuleHostParams(acc) + const mountStatements: Array = [] + const mountHostParams: Array = [] + if (routeModule && routeModule.mounts.length > 0) { + imports.push({ + specifiers: [{ imported: 'mountRouteModule' }], + source: `${this.targetTemplate.fullPkg}/_internal/route-module`, + }) + const moduleUses = this.getRouteModuleUses(acc) + const importedModules = new Set() + for (const mount of routeModule.mounts) { + const importName = `${getModuleIdentifier(mount.moduleId, routeModule.identifiers)}RouteModule` + if (!importedModules.has(mount.moduleId)) { + importedModules.add(mount.moduleId) + imports.push({ + specifiers: [{ imported: 'routeModule', local: importName }], + source: `${mount.moduleId}/route-module`, + }) + } + const mountNode = this.findMountNode(acc, mount.key) + const parentVariable = mountNode.parent + ? `${mountNode.parent.variableName}Route` + : 'rootRouteImport' + const uses = moduleUses.get(mount.key) + mountStatements.push( + `const ${getMountVariableName(mount.key, routeModule.identifiers)}Route${config.disableTypes ? '' : `: typeof ${importName}`} = mountRouteModule(${importName}, { + parent: () => ${parentVariable},${mount.at === undefined ? '' : `\n at: '${mount.at}',`}${mount.as === undefined ? '' : `\n as: '${mount.as}',`}${ + uses + ? `\n uses: { ${Object.entries(uses) + .map(([used, installation]) => `'${used}': '${installation}'`) + .join(', ')} },` + : '' + } +})`, + ) + mountHostParams.push( + ` '${mount.key}': (typeof ${parentVariable})['types']['allParams']`, + ) + } + if (!config.disableTypes) { + mountStatements.push( + `/** The path params of the routes above each mounted route module. */ +export interface MountedModuleHostParams { +${mountHostParams.join('\n')} +}`, + ) + } + } + if (routeModule && !config.disableTypes) { + if (routeModule.visibleContracts.length > 0) { + imports.push({ + specifiers: [{ imported: 'MountedRoutesById' }], + source: this.targetTemplate.fullPkg, + importKind: 'type', + }) + } + if (routeModule.mounts.some((mount) => mount.as !== undefined)) { + imports.push({ + specifiers: [{ imported: 'InstallationRoutesById' }], + source: this.targetTemplate.fullPkg, + importKind: 'type', + }) + } + for (const contractPackage of routeModule.visibleContracts) { + imports.push({ + specifiers: [ + { + imported: 'InstalledRoutesById', + local: `${getModuleIdentifier(contractPackage, routeModule.identifiers)}InstalledRoutesById`, + }, + ], + source: `${contractPackage}/route-types`, + importKind: 'type', + }) + } + } // Add lazyRouteComponent import if there are component pieces let hasComponentPieces = false let hasLoaderPieces = false @@ -884,11 +1575,36 @@ ${[...routeNodesByTo.entries()] })} }`, `export interface FileRoutesById { -'${rootRouteId}': typeof rootRouteImport, +'${rootId}': typeof rootRouteImport, ${[...routeNodesById.entries()].map(([id, routeNode]) => { - return `'${id}': typeof ${getResolvedRouteNodeVariableName(routeNode)}` + return `'${qualifyId(id)}': typeof ${getResolvedRouteNodeVariableName(routeNode)}` })} }`, + // Route modules see the routes of the modules in their scope by id; + // the interface references their declarations instead of copying them. + ...(routeModule + ? [ + `interface RouteModuleRoutesById extends FileRoutesById${routeModule.visibleContracts + .flatMap((contractPackage) => { + const installedRoutes = `${getModuleIdentifier(contractPackage, routeModule.identifiers)}InstalledRoutesById` + // A module installed several times has the routes of each + // installation, by `#:/…` ids. + return routeModule.mounts.some( + (mount) => + mount.moduleId === contractPackage && + mount.as !== undefined, + ) + ? routeModule.mounts + .filter((mount) => mount.moduleId === contractPackage) + .map( + (mount) => + `, MountedRoutesById>`, + ) + : [`, MountedRoutesById<${installedRoutes}>`] + }) + .join('')} {}`, + ] + : []), `export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath fullPaths: ${ @@ -908,8 +1624,15 @@ to: ${ .join('|') : 'never' } -id: ${[`'${rootRouteId}'`, ...[...routeNodesById.keys()].map((id) => `'${id}'`)].join('|')} -fileRoutesById: FileRoutesById +id: ${ + routeModule + ? 'keyof RouteModuleRoutesById' + : [ + `'${rootRouteId}'`, + ...[...routeNodesById.keys()].map((id) => `'${id}'`), + ].join('|') + } +fileRoutesById: ${routeModule ? 'RouteModuleRoutesById' : 'FileRoutesById'} }`, `export interface RootRouteChildren { ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolvedRouteNodeVariableName(child)}`).join(',')} @@ -917,10 +1640,13 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved ].join('\n') fileRoutesByPathInterface = buildFileRoutesByPathInterface({ - module: this.targetTemplate.fullPkg, + // Route modules keep their file routes local: no global augmentation. + module: + moduleId === undefined ? this.targetTemplate.fullPkg : undefined, interfaceName: 'FileRoutesByPath', routeNodes: sortedRouteNodes, config, + qualifyId, }) } @@ -972,7 +1698,15 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved } } const routeTreeContent = [ - ...config.routeTreeFileHeader, + ...this.getGeneratedFileHeader(config), + ...(routeModule?.declaration.mode === 'host' && + routeModule.start && + routeModule.mounts.length > 0 && + !config.disableTypes + ? [ + `export type { StartModulesCheck } from '${this.getRouteModuleImport(this.generatedRouteTreePath, START_MODULES_FILE)}'`, + ] + : []), `// This file was automatically generated by TanStack Router. // You should NOT make any changes in this file as it will be overwritten. // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.`, @@ -980,6 +1714,7 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved mergeImportDeclarations(routeImports).map(buildImportString).join('\n'), virtualRouteNodes.join('\n'), createUpdateRoutes.join('\n'), + mountStatements.join('\n\n'), fileRoutesByFullPath, fileRoutesByPathInterface, routeTreeConfig.join('\n'), @@ -1028,7 +1763,15 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved node, } - const escapedRoutePath = node.routePath?.replaceAll('$', '$$') ?? '' + const routeModule = this.getRouteFileModuleScope(node) + if (routeModule && node._fsRouteType === 'lazy') { + throw new Error( + `[route modules] ${node.fullPath}: lazy route files (".lazy" files and createLazyFileRoute) are not supported in route modules. Use automatic code splitting instead.`, + ) + } + const escapedRoutePath = routeModule + ? routeModule.routeId + : (node.routePath?.replaceAll('$', '$$') ?? '') let shouldWriteRouteFile = false let shouldWriteTree = false @@ -1075,7 +1818,9 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved this.config.customScaffolding?.routeTemplate ?? tRouteTemplate.template(), { - tsrImports: tRouteTemplate.imports.tsrImports(), + tsrImports: routeModule + ? `import { createFileRoute } from '${routeModule.importSource}';` + : tRouteTemplate.imports.tsrImports(), tsrPath: escapedRoutePath.replaceAll(/\{(.+?)\}/gm, '$1'), tsrExportStart: tRouteTemplate.imports.tsrExportStart(escapedRoutePath), @@ -1100,6 +1845,7 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved target: this.config.target, routeId: escapedRoutePath, lazy: node._fsRouteType === 'lazy', + routeImportSource: routeModule?.importSource, }, node, }) @@ -1134,6 +1880,14 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved } } + const previousProps = previousCacheEntry?.node.createFileRouteProps + const props = node.createFileRouteProps + if ( + previousProps?.size !== props?.size || + [...(props ?? [])].some((prop) => !previousProps?.has(prop)) + ) { + shouldWriteTree = true + } for (const plugin of this.plugins) { plugin.afterTransform?.({ node, prevNode: previousCacheEntry?.node }) } @@ -1370,15 +2124,25 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved // scaffold the root route if (!rootNodeFile.fileContent) { const rootTemplate = this.targetTemplate.rootRoute + const routeModule = this.getRouteFileModuleScope(node) const rootRouteContent = await fillTemplate( this.config, rootTemplate.template(), - { - tsrImports: rootTemplate.imports.tsrImports(), - tsrPath: rootPathId, - tsrExportStart: rootTemplate.imports.tsrExportStart(), - tsrExportEnd: rootTemplate.imports.tsrExportEnd(), - }, + routeModule + ? { + // A route module's root declares the router context it + // requires: `createModuleRoot<{ queryClient: QueryClient }>()`. + tsrImports: `import { Outlet } from '${this.targetTemplate.fullPkg}';\nimport { createModuleRoot } from '${routeModule.importSource}';`, + tsrPath: routeModule.routeId, + tsrExportStart: 'export const Route = createModuleRoot()(', + tsrExportEnd: rootTemplate.imports.tsrExportEnd(), + } + : { + tsrImports: rootTemplate.imports.tsrImports(), + tsrPath: rootPathId, + tsrExportStart: rootTemplate.imports.tsrExportStart(), + tsrExportEnd: rootTemplate.imports.tsrExportEnd(), + }, ) this.logger.log(`🟡 Creating ${node.fullPath}`) @@ -1398,6 +2162,322 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved this.routeNodeShadowCache.set(node.fullPath, updatedCacheEntry) } + /** + * Adds the roots of mounted route modules as children of their host routes. + * They appear only in the children of the route tree; their routes are + * described by the modules' own declarations. + */ + private addRouteModuleMounts(acc: HandleNodeAccumulator) { + const context = this.routeModuleContext + if (!context) { + return + } + const moduleId = context.declaration.moduleId + for (const mount of context.mounts) { + let parentId = mount.include.parent + if (moduleId && parentId?.startsWith(`${moduleId}:`)) { + parentId = parentId.slice(moduleId.length + 1) + } + const parent = + parentId === undefined || parentId === rootRouteId + ? undefined + : acc.routeNodesByPath.get(parentId) + if (parentId !== undefined && parentId !== rootRouteId && !parent) { + throw new Error( + `[route modules] ${context.declaration.packageName}: the parent route "${mount.include.parent}" of "${mount.moduleId}" does not exist.`, + ) + } + const mountNode: RouteNode = { + filePath: '', + fullPath: '', + variableName: getMountVariableName(mount.key), + _fsRouteType: 'static', + parent, + _routeModuleMount: { + moduleId: mount.moduleId, + installation: mount.key, + at: mount.at, + }, + } + if (parent) { + parent.children = parent.children ?? [] + parent.children.push(mountNode) + } else { + acc.routeTree.push(mountNode) + } + } + } + + /** + * Rejects mounted module routes whose final full paths collide with routes + * of this package or of other mounted modules. + */ + private checkRouteModuleFullPaths(acc: HandleNodeAccumulator) { + const context = this.routeModuleContext + if (!context || context.mounts.length === 0) { + return + } + const owners = new Map() + const claim = (fullPath: string, owner: string) => { + const key = fullPath === '/' ? '/' : fullPath.replace(/\/$/, '') + const previous = owners.get(key) + if (previous !== undefined && previous !== owner) { + throw new Error( + `[route modules] ${context.declaration.packageName}: the full path "${fullPath}" is used by both ${previous} and ${owner}. Mount the module at another path.`, + ) + } + owners.set(key, owner) + } + for (const node of acc.routeNodes) { + if (!node.children?.length && node._fsRouteType !== 'lazy') { + claim(inferFullPath(node), `"${node.filePath}"`) + } + } + for (const mount of context.mounts) { + const mountNode = this.findMountNode(acc, mount.key) + const parentPath = mountNode.parent + ? inferFullPath(mountNode.parent).replace(/\/$/, '') + : '' + const prefix = `${parentPath}${mount.at ?? ''}` + for (const route of mount.manifest.routes) { + if (!route.leaf) { + continue + } + const local = route.fullPath + claim( + prefix === '' + ? local + : local === '/' + ? `${prefix}/` + : `${prefix}${local}`, + `"${getInstallationRouteId(mount, route.id)}" (module "${mount.key}")`, + ) + } + } + } + + /** + * A module that uses another one without mounting it links into it through + * a namespace typed without the path params above it: they are filled from + * the current location. That always works only when the routes declaring + * them are above the using module too. + */ + private checkRouteModuleHostParams(acc: HandleNodeAccumulator) { + const context = this.routeModuleContext + if (!context || context.mounts.length === 0) { + return + } + const mountPaths = this.getRouteModuleMountPaths(acc) + for (const mount of context.mounts) { + const host = this.findMountNode(acc, mount.key).parent + const hostParams = new Set( + getParamNames( + parseSegments(false, { from: host ? inferFullPath(host) : '' }, 0), + ), + ) + for (const route of mount.manifest.routes) { + const overlap = getParamNames( + parseSegments(false, { from: route.fullPath }, 0), + ).find((param) => hostParams.has(param)) + if (overlap) { + throw new Error( + `[route modules] ${context.declaration.packageName}: parameter "${overlap}" appears both above "${mount.key}" and in its route "${route.id}". Choose distinct host and module parameter names.`, + ) + } + } + for (const installed of mount.manifest.modules) { + const own = mountPaths.get( + installed.id === mount.moduleId ? mount.key : installed.key, + )! + for (const used of installed.uses) { + if ( + context.mounts.some( + (candidate) => + candidate.moduleId === used && candidate.as !== undefined, + ) + ) { + // Links into one of several installations: see + // `getRouteModuleUses`. + if (installed.id !== mount.moduleId) { + throw new Error( + `[route modules] ${context.declaration.packageName}: "${installed.id}" links into "${used}", which this application installs several times, but "${installed.id}" is installed by "${mount.moduleId}", which cannot choose an installation. Install "${installed.id}" in this application.`, + ) + } + continue + } + const target = mountPaths.get(used) + if (target === undefined) { + continue + } + const host = getHostPath(target) + if (host === undefined) { + continue + } + if (own !== host && !own.startsWith(`${host}/`)) { + throw new Error( + `[route modules] ${context.declaration.packageName}: "${installed.id}" links into "${used}", which is mounted below "${host}", but "${installed.id}" is mounted at "${own}" and cannot fill those path params. Mount "${installed.id}" below "${host}", or link into "${used}" from the package that mounts it.`, + ) + } + } + } + } + } + + /** + * Full paths of every installed module root in this route tree, by module + * id, and by `#` for the installations of a module installed + * several times. + */ + private getRouteModuleMountPaths(acc: HandleNodeAccumulator) { + const mountPaths = new Map() + for (const mount of this.routeModuleContext?.mounts ?? []) { + const mountNode = this.findMountNode(acc, mount.key) + const parentPath = mountNode.parent + ? inferFullPath(mountNode.parent).replace(/\/$/, '') + : '' + const prefix = `${parentPath}${mount.at ?? ''}` + for (const installed of mount.manifest.modules) { + const local = installed.mountPath.replace(/\/$/, '') + mountPaths.set( + installed.id === mount.moduleId ? mount.key : installed.key, + `${prefix}${local}` || '/', + ) + } + } + return mountPaths + } + + /** + * The installation a mounted module links into for every module it uses + * that this application installs several times: the one whose host routes + * are above the module, so that links fill their path params from the + * current location. None or several such installations are errors. + */ + private getRouteModuleUses(acc: HandleNodeAccumulator) { + const context = this.routeModuleContext + const uses = new Map>() + if (!context || !context.mounts.some((mount) => mount.as !== undefined)) { + return uses + } + const mountPaths = this.getRouteModuleMountPaths(acc) + for (const mount of context.mounts) { + const own = mountPaths.get(mount.key)! + const root = mount.manifest.modules.find( + (installed) => installed.id === mount.moduleId, + ) + for (const used of root?.uses ?? []) { + if ( + !context.mounts.some( + (candidate) => + candidate.moduleId === used && candidate.as !== undefined, + ) + ) { + continue + } + const installations = context.mounts.filter((candidate) => { + if (candidate.moduleId !== used) { + return false + } + const host = getHostPath(mountPaths.get(candidate.key)!) + return ( + host === undefined || own === host || own.startsWith(`${host}/`) + ) + }) + if (installations.length !== 1) { + throw new Error( + `[route modules] ${context.declaration.packageName}: "${mount.key}" links into "${used}", which is installed several times, but ${ + installations.length === 0 + ? 'no installation' + : `the installations ${installations.map((installation) => `"${installation.as}"`).join(' and ')}` + } can take path params from "${own}". Mount "${mount.key}" below the routes with the path params of exactly one installation.`, + ) + } + uses.set(mount.key, { + ...uses.get(mount.key), + [used]: installations[0]!.key, + }) + } + } + return uses + } + + private findMountNode(acc: HandleNodeAccumulator, installation: string) { + const find = (nodes: Array): RouteNode | undefined => { + for (const node of nodes) { + if (node._routeModuleMount?.installation === installation) { + return node + } + const found = node.children && find(node.children) + if (found) { + return found + } + } + return undefined + } + return find(acc.routeTree)! + } + + /** + * Generated files of route modules and of applications that mount them are + * type-checked (mount assertions, declaration emit), so the default header + * leaves out `@ts-nocheck`. A custom header is used as is. + */ + private getGeneratedFileHeader(config: Config): Array { + const header = config.routeTreeFileHeader + if ( + !this.routeModuleContext || + config.disableTypes || + header.length !== DEFAULT_ROUTE_TREE_FILE_HEADER.length || + header.some((line, i) => line !== DEFAULT_ROUTE_TREE_FILE_HEADER[i]) + ) { + return header + } + return header.filter((line) => line !== '// @ts-nocheck') + } + + /** Path of a generated route-module file next to the route tree. */ + private getRouteModuleFilePath(baseName: string) { + return path.join( + path.dirname(this.generatedRouteTreePath), + `${baseName}.ts`, + ) + } + + /** Import specifier of a generated route-module file from `fromFile`. */ + private getRouteModuleImport(fromFile: string, baseName: string) { + const relative = replaceBackslash( + removeExt( + path.relative( + path.dirname(fromFile), + this.getRouteModuleFilePath(baseName), + ), + this.config.addExtensions, + ), + ) + return relative.startsWith('.') ? relative : `./${relative}` + } + + /** + * In a route module, route files get qualified ids and import their route + * factories from the module's scope. + */ + private getRouteFileModuleScope( + node: RouteNode, + ): { routeId: string; importSource: string } | undefined { + const context = this.routeModuleContext + if (context?.declaration.mode !== 'module') { + return undefined + } + const moduleId = context.declaration.moduleId! + return { + routeId: + node._fsRouteType === '__root' + ? `${moduleId}:` + : `${moduleId}:${node.routePath ?? ''}`, + importSource: this.getRouteModuleImport(node.fullPath, ROUTE_SCOPE_FILE), + } + } + public async getCrawlingResult(): Promise { await this.runPromise return this.crawlingResult @@ -1635,6 +2715,12 @@ ${acc.routeTree.map((child) => `${child.variableName}Route: typeof ${getResolved return true } + // package.json and the manifests of route modules this package mounts or + // uses: they change the generated route-module files + if (this.routeModuleFiles.includes(filePath)) { + return true + } + // the virtual route config file passed into `virtualRouteConfig` if ( typeof this.config.virtualRouteConfig === 'string' && diff --git a/packages/router-generator/src/index.ts b/packages/router-generator/src/index.ts index 9a4f8a17ff..c06b06c3be 100644 --- a/packages/router-generator/src/index.ts +++ b/packages/router-generator/src/index.ts @@ -46,3 +46,29 @@ export { getRouteNodes as virtualGetRouteNodes } from './filesystem/virtual/getR export { rootPathId } from './filesystem/physical/rootPathId' export type { TransformContext, TransformOptions } from './transform/types' + +export { + getManifestPath as getRouteModuleManifestPath, + readManifest as readRouteModuleManifest, +} from './route-module/manifest' +export type { + ManifestInstalledModule, + ManifestRoute, + RouteModuleManifest, +} from './route-module/manifest' +export { + getInstalledRouteModuleDirectories, + resolveRouteModuleContext, +} from './route-module/context' +export type { + ResolvedMount, + RouteModuleContext, + ScopeModule, +} from './route-module/context' +export type { + ModuleDeclaration, + RouteModuleDeclaration, + RouteModulesOption, +} from './route-module/declaration' + +export { pruneServerOnlySubtrees } from './pruneServerOnlySubtrees' diff --git a/packages/start-plugin-core/src/start-router-plugin/pruneServerOnlySubtrees.ts b/packages/router-generator/src/pruneServerOnlySubtrees.ts similarity index 85% rename from packages/start-plugin-core/src/start-router-plugin/pruneServerOnlySubtrees.ts rename to packages/router-generator/src/pruneServerOnlySubtrees.ts index e5b995ede5..2e42ea9d5b 100644 --- a/packages/start-plugin-core/src/start-router-plugin/pruneServerOnlySubtrees.ts +++ b/packages/router-generator/src/pruneServerOnlySubtrees.ts @@ -1,8 +1,4 @@ -import { SERVER_PROP } from './constants' -import type { - HandleNodeAccumulator, - RouteNode, -} from '@tanstack/router-generator' +import type { HandleNodeAccumulator, RouteNode } from './types' export function pruneServerOnlySubtrees({ rootRouteNode, @@ -39,7 +35,7 @@ function prune( } const allServerOnly = - node.createFileRouteProps?.has(SERVER_PROP) && + node.createFileRouteProps?.has('server') && node.createFileRouteProps.size === 1 && allChildrenServerOnly // prune this subtree diff --git a/packages/router-generator/src/route-module/context.ts b/packages/router-generator/src/route-module/context.ts new file mode 100644 index 0000000000..55252bfe7e --- /dev/null +++ b/packages/router-generator/src/route-module/context.ts @@ -0,0 +1,629 @@ +import crypto from 'node:crypto' +import { existsSync, realpathSync } from 'node:fs' +import path from 'node:path' +import { cleanPath } from '@tanstack/router-core' +import { generatedPublicNames } from '../generated-names' +import { getManifestPath, readManifest } from './manifest' +import { + findPackageRoot, + getDefaultNamespace, + isRouteModulePackage, + readRouteModuleDeclaration, + resolveModulePackageRoot, +} from './declaration' +import type { RouteModuleManifest } from './manifest' +import type { + ModuleInclude, + RouteModuleDeclaration, + RouteModulesOption, +} from './declaration' + +/** Where the types of a module in scope come from. */ +export interface ModuleTypeSource { + /** Package whose contract (`/route-types`) provides the types. */ + contractPackage: string + /** + * `null`: the module is that package itself (`Router`, + * `InstalledRoutesById`). Otherwise the module is installed by that package + * and is read from its `InstalledRouters`. + */ + installedBy: string | null + /** Key of an installed router in the provider contract. */ + installedKey?: string +} + +export interface ScopeModule { + moduleId: string + /** + * What the namespace addresses: the module id, or `#` for one + * installation of a module installed several times. + */ + key: string + namespace: string + source: ModuleTypeSource + /** + * Set when path params lie above the module in this package's route tree: + * the module this package mounts on the way to it (itself when mounted + * directly). Links through its namespace then pass those params. + */ + hostedThrough?: string +} + +export interface ResolvedMount { + include: ModuleInclude + moduleId: string + /** The module id, or `#` when it is installed several times. */ + key: string + /** The installation name of a module installed several times. */ + as: string | undefined + packageRoot: string + manifest: RouteModuleManifest + /** Current real paths resolved through the provider dependency graph. */ + routeFiles: Array<{ file: string; routeId: string }> + clientTrees: Array<{ filePath: string; clientFilePath: string }> + /** Static mount path relative to the parent (`undefined`: pathless). */ + at: string | undefined +} + +/** TanStack Start usage of a package. */ +export interface RouteModuleStart { + /** The framework's Start package (`@tanstack/react-start`). */ + package: string + /** + * The Start file next to the route tree, if any: a module's fragment + * (`export const start`) or an application's `startInstance`. + */ + file: string | undefined +} + +export interface RouteModuleContext { + declaration: RouteModuleDeclaration + /** Allocated private binding families shared by this generation. */ + identifiers: Map + manifests: Map + mounts: Array + /** Set when the package depends on the framework's Start package. */ + start: RouteModuleStart | undefined + /** Mounted modules whose runtime entry exports Start fragments. */ + startMounts: Array + /** + * Whether this module's runtime entry exports `startModules`: it has a + * fragment or mounts modules that export fragments. + */ + exportsStartModules: boolean + /** Files whose creation or removal changes the context. */ + watchFiles: Array + /** Direct dependencies whose installed routes are visible by id. */ + visibleContracts: Array + /** Modules with a generated namespace. */ + scope: Array + /** Modules this package installs more than once. */ + installedSeveralTimes: Set + /** Manifest files the context was built from (watch relevance). */ + dependencyFiles: Array + /** Changes whenever the generated output may change. */ + hash: string +} + +function fail(declaration: RouteModuleDeclaration, message: string): never { + throw new Error(`[route modules] ${declaration.packageName}: ${message}`) +} + +function loadDependency( + declaration: RouteModuleDeclaration, + moduleId: string, + relation: 'includes' | 'uses', + onWatchFile?: (file: string) => void, +) { + if (moduleId === declaration.moduleId) { + fail( + declaration, + `a module cannot ${relation === 'includes' ? 'include' : 'use'} itself.`, + ) + } + if (!declaration.dependencies.includes(moduleId)) { + fail( + declaration, + `"${moduleId}" is listed in "${relation}" but is not a dependency. Add it to "dependencies" (or "peerDependencies") in package.json.`, + ) + } + const packageRoot = resolveModulePackageRoot( + moduleId, + declaration.packageRoot, + ) + if (!packageRoot) { + fail( + declaration, + `cannot resolve "${moduleId}" from "${declaration.packageRoot}". Install the workspace dependencies.`, + ) + } + onWatchFile?.(path.join(packageRoot, 'package.json')) + onWatchFile?.(getManifestPath(packageRoot)) + if (!isRouteModulePackage(packageRoot)) { + fail( + declaration, + `"${moduleId}" is not a route module: its package.json has no "tanstack.router.module".`, + ) + } + const manifest = readManifest(packageRoot) + if (!manifest) { + fail( + declaration, + `"${moduleId}" has no route module manifest at "${getManifestPath(packageRoot)}". Run "tsr generate" in "${packageRoot}" first (for example with a "dependsOn": ["^generate"] task dependency).`, + ) + } + return { packageRoot, manifest } +} + +function hasPathParams(path: string) { + return /\$/.test(path) +} + +/** The part of a full path up to its last segment with path params. */ +export function getHostPath(fullPath: string): string | undefined { + return /^.*\$[^/]*/.exec(fullPath)?.[0] +} + +/** + * The id of a module route in the installation of `mount`: + * `#:/…` for `:/…` when the module is installed + * several times. + */ +export function getInstallationRouteId( + mount: ResolvedMount, + routeId: string, +): string { + return mount.as !== undefined && routeId.startsWith(`${mount.moduleId}:`) + ? mount.key + routeId.slice(mount.moduleId.length) + : routeId +} + +/** + * Resolves everything a generator run needs about route modules: the package's + * own declaration, the modules it mounts and the modules visible in its scope. + */ +export function resolveRouteModuleContext(opts: { + root: string + routeModules: RouteModulesOption | undefined + /** Publish candidate watch paths even when a provider is not generated yet. */ + onWatchFile?: (file: string) => void + /** + * The framework's Start package (`@tanstack/react-start`) and the directory + * of the generated route tree, where a Start file lives. Callers that only + * need the mounted modules omit them. + */ + start?: { package: string; generatedDirectory: string } +}): RouteModuleContext | undefined { + const declaration = readRouteModuleDeclaration(opts.root, opts.routeModules) + if (!declaration) { + return undefined + } + + const manifests = new Map() + const dependencyFiles: Array = [] + const scope = new Map() + const namespaceOwners = new Map() + const visibleContracts = new Set() + + const addToScope = ( + moduleId: string, + namespace: string, + source: ModuleTypeSource, + hostedThrough?: string, + key = moduleId, + ) => { + if (scope.has(key)) { + return + } + if ( + !/^[A-Za-z_$][\w$]*$/.test(namespace) || + generatedPublicNames.includes(namespace as any) || + [ + 'default', + 'import', + 'export', + 'class', + 'function', + 'const', + 'let', + 'var', + 'new', + 'return', + 'delete', + 'void', + 'typeof', + 'instanceof', + 'in', + 'yield', + 'await', + 'enum', + 'implements', + 'interface', + 'package', + 'private', + 'protected', + 'public', + 'static', + 'null', + 'true', + 'false', + 'this', + 'super', + 'extends', + 'try', + 'catch', + 'finally', + 'throw', + 'if', + 'else', + 'for', + 'while', + 'switch', + 'case', + 'break', + 'continue', + 'do', + 'with', + 'debugger', + ].includes(namespace) + ) { + fail( + declaration, + `the namespace "${namespace}" is not an available JavaScript identifier. Choose a different "as" that does not conflict with generated routing exports.`, + ) + } + const owner = namespaceOwners.get(namespace) + if (owner !== undefined) { + fail( + declaration, + `the modules "${owner}" and "${moduleId}" both get the namespace "${namespace}". Choose another one with "as".`, + ) + } + namespaceOwners.set(namespace, moduleId) + scope.set(key, { moduleId, key, namespace, source, hostedThrough }) + } + + /** + * Adds the modules installed by a dependency. `hostParams`: whether this + * package mounts the dependency under path params. + */ + const addInstalledSubtree = ( + contractPackage: string, + manifest: RouteModuleManifest, + mounted?: { hostParams: boolean; key: string }, + ) => { + for (const installed of manifest.modules) { + if (installed.id === manifest.id) { + continue + } + addToScope( + installed.id, + getDefaultNamespace(installed.id), + { + contractPackage, + installedBy: contractPackage, + installedKey: installed.key, + }, + mounted && (mounted.hostParams || hasPathParams(installed.mountPath)) + ? mounted.key + : undefined, + installed.key, + ) + } + } + + // Modules this package mounts. A module included several times is + // installed once per include, each named with `as`. + const mounts: Array = [] + const seenIncludes = new Set() + const installedSeveralTimes = new Set( + declaration.includes + .map((include) => include.moduleId) + .filter((moduleId, index, all) => all.indexOf(moduleId) !== index), + ) + for (const moduleId of installedSeveralTimes) { + if (declaration.mode === 'module') { + fail( + declaration, + `"${moduleId}" is included more than once. Only an application can install a route module several times.`, + ) + } + const names = new Set() + for (const include of declaration.includes) { + if (include.moduleId !== moduleId) { + continue + } + if (include.as !== undefined && names.has(include.as)) { + fail( + declaration, + `two installations of "${moduleId}" are named "${include.as}". Name each installation with its own "as".`, + ) + } + names.add(include.as!) + if (include.as === undefined) { + fail( + declaration, + `"${moduleId}" is included more than once. Name every installation with "as".`, + ) + } + // `as` names the installation's namespace. + if (!/^[A-Za-z_$][\w$]*$/.test(include.as)) { + fail( + declaration, + `the installation "${include.as}" of "${moduleId}" must be named with a JavaScript identifier.`, + ) + } + } + } + for (const include of declaration.includes) { + const { packageRoot, manifest } = loadDependency( + declaration, + include.moduleId, + 'includes', + opts.onWatchFile, + ) + manifests.set(include.moduleId, manifest) + if (!seenIncludes.has(include.moduleId)) { + seenIncludes.add(include.moduleId) + dependencyFiles.push(getManifestPath(packageRoot)) + } + const at = + include.at === undefined + ? undefined + : cleanPath(`/${include.at}`).replace(/\/$/, '') || undefined + if (at !== undefined && hasPathParams(at)) { + fail( + declaration, + `"${include.moduleId}" must be mounted at a static path, but "${at}" has path params.`, + ) + } + const as = include.as + if ( + installedSeveralTimes.has(include.moduleId) && + manifest.modules.length > 1 + ) { + fail( + declaration, + `"${include.moduleId}" installs other route modules, so it can be installed only once.`, + ) + } + const key = + as === undefined ? include.moduleId : `${include.moduleId}#${as}` + mounts.push({ + include, + moduleId: include.moduleId, + key, + as, + packageRoot, + manifest, + routeFiles: resolveManifestRouteFiles(packageRoot, manifest), + clientTrees: manifest.clientTrees.map(({ owner, file, clientFile }) => ({ + filePath: resolveManifestFile(packageRoot, owner, file), + clientFilePath: resolveManifestFile(packageRoot, owner, clientFile), + })), + at: + at === undefined || at === '/' || at === '' + ? undefined + : `/${at.replace(/^\/+|\/+$/g, '')}`, + }) + visibleContracts.add(include.moduleId) + // Route ids contain the path params of their own and their parents' paths. + const hostParams = hasPathParams(include.parent ?? '') + addToScope( + include.moduleId, + include.namespace, + { contractPackage: include.moduleId, installedBy: null }, + hostParams ? key : undefined, + key, + ) + addInstalledSubtree(include.moduleId, manifest, { hostParams, key }) + } + + // A module installed twice in the tree is ambiguous, unless every + // installation is named. + const installedBy = new Map() + for (const mount of mounts) { + for (const installed of mount.manifest.modules) { + if (installed.id === mount.moduleId && mount.as !== undefined) { + installedBy.set(mount.key, declaration.packageName) + continue + } + const includer = installed.includedBy ?? declaration.packageName + const previous = installedBy.get(installed.id) + if (previous !== undefined) { + fail( + declaration, + `"${installed.id}" is installed twice: by "${previous}" and by "${includer}". A route module can be mounted once per route tree.`, + ) + } + installedBy.set(installed.id, includer) + } + } + + // Modules this package references without mounting them. + const uses = declaration.uses + for (const use of uses) { + if (seenIncludes.has(use.moduleId)) { + continue + } + const { packageRoot, manifest } = loadDependency( + declaration, + use.moduleId, + 'uses', + opts.onWatchFile, + ) + manifests.set(use.moduleId, manifest) + dependencyFiles.push(getManifestPath(packageRoot)) + if ( + installedBy.has(use.moduleId) || + installedSeveralTimes.has(use.moduleId) + ) { + // Already visible through the module that installs it. + continue + } + visibleContracts.add(use.moduleId) + addToScope(use.moduleId, use.namespace, { + contractPackage: use.moduleId, + installedBy: null, + }) + addInstalledSubtree(use.moduleId, manifest) + } + + // The final application must install every module that is used. + if (declaration.mode === 'host') { + for (const mount of mounts) { + for (const installed of mount.manifest.modules) { + for (const used of installed.uses) { + if ( + !installedBy.has(used) && + !mounts.some((mount) => mount.moduleId === used) + ) { + fail( + declaration, + `"${installed.id}" uses routes of "${used}", which is not installed. Add "${used}" to the "includes" of this application or of one of its modules.`, + ) + } + } + } + } + for (const use of uses) { + if ( + !installedBy.has(use.moduleId) && + !mounts.some((mount) => mount.moduleId === use.moduleId) + ) { + fail( + declaration, + `this application uses routes of "${use.moduleId}", which is not installed. Add it to "includes".`, + ) + } + } + } + + // TanStack Start: fragments are composed upward to the application. + const startOptions = opts.start + const startFileCandidates = startOptions + ? ['start.ts', 'start.tsx'].map((file) => + path.join(startOptions.generatedDirectory, file), + ) + : [] + for (const file of startFileCandidates) { + opts.onWatchFile?.(file) + } + const start: RouteModuleStart | undefined = + startOptions && declaration.dependencies.includes(startOptions.package) + ? { + package: startOptions.package, + file: startFileCandidates.find((file) => existsSync(file)), + } + : undefined + const startMounts = [ + ...new Set( + mounts + .filter((mount) => mount.manifest.startModules) + .map((mount) => mount.moduleId), + ), + ] + if (startOptions && declaration.mode === 'host' && startMounts.length > 0) { + if (!start) { + fail( + declaration, + `"${startMounts[0]}" has a TanStack Start fragment. Install it in a TanStack Start application, which depends on "${startOptions.package}".`, + ) + } + if (!start.file) { + fail( + declaration, + `"${startMounts[0]}" has a TanStack Start fragment. Install it in "${startFileCandidates[0]}": export const startInstance = createStart(() => ({ extends: startModules })), with startModules from "./startModules.gen".`, + ) + } + } + const exportsStartModules = + declaration.mode === 'module' && (!!start?.file || startMounts.length > 0) + + const hash = crypto + .createHash('sha256') + .update( + JSON.stringify({ + declaration, + manifests: [...manifests].map(([id, manifest]) => [ + id, + manifest.topologyToken, + ]), + mounts: mounts.map((mount) => [ + mount.key, + mount.include.parent, + mount.at, + mount.manifest.topologyToken, + ]), + scope: [...scope.values()], + start, + }), + ) + .digest('hex') + .slice(0, 16) + + return { + declaration, + identifiers: new Map(), + manifests, + mounts, + start, + startMounts, + exportsStartModules, + watchFiles: start ? startFileCandidates : [], + visibleContracts: [...visibleContracts], + scope: [...scope.values()], + installedSeveralTimes, + dependencyFiles, + hash, + } +} + +/** + * The package roots of every route module installed by a package (directly or + * through other modules): their files are compiled as part of the application. + */ +export function getInstalledRouteModuleDirectories( + context: RouteModuleContext | undefined, +): Array { + const directories = new Set() + for (const mount of context?.mounts ?? []) { + directories.add(mount.packageRoot) + for (const { file } of mount.routeFiles) { + const packageRoot = findPackageRoot(path.dirname(file)) + if (packageRoot) { + directories.add(packageRoot) + } + } + } + return [...directories] +} + +/** Resolve portable paths from each provider's own dependency context. */ +function resolveManifestFile( + packageRoot: string, + owner: Array, + file: string, +) { + let root = packageRoot + for (const packageName of owner) { + const next = resolveModulePackageRoot(packageName, root) + if (!next) { + throw new Error( + `[route modules] Cannot resolve route source owner "${packageName}" from "${root}". Install the provider dependencies and regenerate its manifest.`, + ) + } + root = next + } + return realpathSync(path.resolve(root, file)) +} + +export function resolveManifestRouteFiles( + packageRoot: string, + manifest: RouteModuleManifest, +) { + return manifest.routeFiles.map(({ owner, file, routeId }) => ({ + file: resolveManifestFile(packageRoot, owner, file), + routeId, + })) +} diff --git a/packages/router-generator/src/route-module/declaration.ts b/packages/router-generator/src/route-module/declaration.ts new file mode 100644 index 0000000000..6afac58ff1 --- /dev/null +++ b/packages/router-generator/src/route-module/declaration.ts @@ -0,0 +1,252 @@ +import path from 'node:path' +import { existsSync, readFileSync, realpathSync } from 'node:fs' +import { createRequire } from 'node:module' +import { z } from 'zod' + +const moduleReferenceSchema = z.union([ + z.string(), + z.object({ + module: z.string(), + /** Name of the generated namespace for this module. */ + as: z.string().optional(), + }), +]) + +const includeSchema = z.union([ + z.string(), + z.object({ + module: z.string(), + /** Id of the host route the module is mounted under (default: the root). */ + parent: z.string().optional(), + /** Static path of the module root relative to `parent`. */ + at: z.string().optional(), + /** + * Name of the generated namespace, and of the installation when the + * module is included more than once. + */ + as: z.string().optional(), + }), +]) + +/** `routeModules` generator option: the modules an application installs. */ +export const routeModulesOptionSchema = z.object({ + includes: z.array(includeSchema).optional(), + uses: z.array(moduleReferenceSchema).optional(), +}) + +/** `tanstack.router.module` in a package's `package.json`. */ +export const moduleDeclarationSchema = z.union([ + z.literal(true), + routeModulesOptionSchema, +]) + +export type RouteModulesOption = z.infer +export type ModuleDeclaration = z.infer + +export interface ModuleReference { + moduleId: string + namespace: string +} + +export interface ModuleInclude extends ModuleReference { + parent?: string + at?: string + /** The `as` of the include, if given. */ + as?: string +} + +/** + * The route-module role of the package a generator runs for: + * - `module`: the package is a route module (`tanstack.router.module`); its + * routes have qualified ids and it publishes a contract. + * - `host`: an application that installs route modules (`routeModules` + * option); its own routes are unchanged. + */ +export interface RouteModuleDeclaration { + mode: 'module' | 'host' + packageRoot: string + packageName: string + /** Module id (module mode). */ + moduleId?: string + includes: Array + /** Modules whose routing APIs this package explicitly consumes. */ + uses: Array + dependencies: Array +} + +interface PackageJson { + name?: string + dependencies?: Record + peerDependencies?: Record + tanstack?: { router?: { module?: unknown } } +} + +export function findPackageRoot(start: string): string | undefined { + let dir = path.resolve(start) + for (;;) { + if (existsSync(path.join(dir, 'package.json'))) { + return dir + } + const parent = path.dirname(dir) + if (parent === dir) { + return undefined + } + dir = parent + } +} + +export function readPackageJson(packageRoot: string): PackageJson { + return JSON.parse( + readFileSync(path.join(packageRoot, 'package.json'), 'utf8'), + ) +} + +/** + * The default namespace of a module: the last segment of its package name, + * camel-cased (`@acme/user-account` -> `userAccount`). + */ +export function getDefaultNamespace(moduleId: string): string { + const lastSegment = moduleId.split('/').pop()! + const camel = lastSegment.replace(/[-_.]+([a-zA-Z0-9])/g, (_, c: string) => + c.toUpperCase(), + ) + const identifier = camel.replace(/[^a-zA-Z0-9_$]/g, '') + return /^[0-9]/.test(identifier) ? `_${identifier}` : identifier +} + +function toReference(reference: z.infer) { + const moduleId = typeof reference === 'string' ? reference : reference.module + return { + moduleId, + namespace: + (typeof reference === 'string' ? undefined : reference.as) ?? + getDefaultNamespace(moduleId), + } +} + +function toInclude(include: z.infer): ModuleInclude { + if (typeof include === 'string') { + return toReference(include) + } + return { + ...toReference({ module: include.module, as: include.as }), + parent: include.parent, + at: include.at, + as: include.as, + } +} + +function formatZodError(error: z.ZodError) { + return error.issues + .map((issue) => `${issue.path.join('.') || ''}: ${issue.message}`) + .join('; ') +} + +/** + * Reads the route-module declaration of the package that contains `root`, or + * returns `undefined` for an ordinary application. + */ +export function readRouteModuleDeclaration( + root: string, + inlineOption: RouteModulesOption | undefined, +): RouteModuleDeclaration | undefined { + const packageRoot = findPackageRoot(root) + const packageJson = packageRoot ? readPackageJson(packageRoot) : undefined + const rawDeclaration = packageJson?.tanstack?.router?.module + + if (rawDeclaration === undefined && inlineOption === undefined) { + return undefined + } + + if (!packageRoot || !packageJson) { + throw new Error( + `Route modules require a package.json, but none was found above "${root}".`, + ) + } + const packageName = packageJson.name + if (!packageName) { + throw new Error( + `Route modules require a package name in "${path.join(packageRoot, 'package.json')}".`, + ) + } + + const dependencies = [ + ...Object.keys(packageJson.dependencies ?? {}), + ...Object.keys(packageJson.peerDependencies ?? {}), + ] + + if (rawDeclaration !== undefined) { + if (inlineOption !== undefined) { + throw new Error( + `"${packageName}" declares "tanstack.router.module" in its package.json and also passes "routeModules" to the router generator. Declare its modules in one place: package.json for route modules, the "routeModules" option only for applications.`, + ) + } + const parsed = moduleDeclarationSchema.safeParse(rawDeclaration) + if (!parsed.success) { + throw new Error( + `Invalid "tanstack.router.module" in "${path.join(packageRoot, 'package.json')}": ${formatZodError(parsed.error)}`, + ) + } + const declaration = parsed.data === true ? {} : parsed.data + return { + mode: 'module', + packageRoot, + packageName, + moduleId: packageName, + includes: (declaration.includes ?? []).map(toInclude), + uses: (declaration.uses ?? []).map(toReference), + dependencies, + } + } + + const parsed = routeModulesOptionSchema.safeParse(inlineOption) + if (!parsed.success) { + throw new Error( + `Invalid "routeModules" option: ${formatZodError(parsed.error)}`, + ) + } + return { + mode: 'host', + packageRoot, + packageName, + includes: (parsed.data.includes ?? []).map(toInclude), + uses: (parsed.data.uses ?? []).map(toReference), + dependencies, + } +} + +/** + * Resolves the package root of `moduleId` as seen from `fromPackageRoot`, + * following symlinks (pnpm workspace links) to the real directory. + */ +export function resolveModulePackageRoot( + moduleId: string, + fromPackageRoot: string, +): string | undefined { + const require = createRequire(path.join(fromPackageRoot, 'package.json')) + try { + return path.dirname( + realpathSync(require.resolve(`${moduleId}/package.json`)), + ) + } catch { + // Packages without `"./package.json"` in their exports cannot be read + // through the resolver; fall back to the node_modules link. + let dir = fromPackageRoot + for (;;) { + const candidate = path.join(dir, 'node_modules', moduleId, 'package.json') + if (existsSync(candidate)) { + return path.dirname(realpathSync(candidate)) + } + const parent = path.dirname(dir) + if (parent === dir) { + return undefined + } + dir = parent + } + } +} + +/** Whether a package declares itself a route module. */ +export function isRouteModulePackage(packageRoot: string): boolean { + return readPackageJson(packageRoot).tanstack?.router?.module !== undefined +} diff --git a/packages/router-generator/src/route-module/emit.ts b/packages/router-generator/src/route-module/emit.ts new file mode 100644 index 0000000000..149a5cb90e --- /dev/null +++ b/packages/router-generator/src/route-module/emit.ts @@ -0,0 +1,493 @@ +import type { RouteModuleContext, ScopeModule } from './context' + +export const ROUTE_SCOPE_FILE = 'routeScope.gen' +export const ROUTE_CONTRACT_FILE = 'routeContract.gen' +export const ROUTE_MODULE_FILE = 'routeModule.gen' +export const START_MODULES_FILE = 'startModules.gen' + +/** `@acme/user-account` -> `AcmeUserAccount` */ +export function getModuleIdentifier( + moduleId: string, + identifiers?: Map, +): string { + const allocated = identifiers?.get(moduleId) + if (allocated) { + return allocated + } + const identifier = moduleId + .split(/[^a-zA-Z0-9]+/) + .filter(Boolean) + .map((part) => part[0]!.toUpperCase() + part.slice(1)) + .join('') + return /^[0-9]/.test(identifier) ? `_${identifier}` : identifier || 'Module' +} + +/** Variable of a mounted module root in a generated route tree. */ +export function getMountVariableName( + moduleId: string, + identifiers?: Map, +) { + return `${getModuleIdentifier(moduleId, identifiers)}Module` +} + +const GENERATED_NOTICE = `// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.` + +function routerTypeOf(module: ScopeModule, identifiers: Map) { + const identifier = getModuleIdentifier( + module.source.contractPackage, + identifiers, + ) + return module.source.installedBy === null + ? `${identifier}Router` + : `${identifier}InstalledRouters['${module.source.installedKey ?? module.key}']` +} + +/** + * The path params above a hosted module (`ScopeModule.hostedThrough`): those + * of this package's routes above the module it mounts, and the ones inside + * that module's tree for a module it installs. + */ +function hostParamsOf( + module: ScopeModule & { hostedThrough: string }, + identifiers: Map, +) { + const mounted = `MountedModuleHostParams['${module.hostedThrough}']` + return module.hostedThrough === module.key + ? mounted + : `${mounted} & ${getModuleIdentifier(module.source.contractPackage, identifiers)}InstalledHostParams['${module.source.installedKey ?? module.key}']` +} + +function contractTypeImports( + scope: Array, + identifiers: Map, +) { + const byPackage = new Map>() + const add = (pkg: string, name: string) => { + const names = byPackage.get(pkg) ?? new Set() + names.add(name) + byPackage.set(pkg, names) + } + for (const module of scope) { + const identifier = getModuleIdentifier( + module.source.contractPackage, + identifiers, + ) + add( + module.source.contractPackage, + module.source.installedBy === null + ? `Router as ${identifier}Router` + : `InstalledRouters as ${identifier}InstalledRouters`, + ) + if ( + module.hostedThrough !== undefined && + module.hostedThrough !== module.key + ) { + add( + module.source.contractPackage, + `InstalledHostParams as ${identifier}InstalledHostParams`, + ) + } + } + return [...byPackage.entries()].map( + ([pkg, names]) => + `import type { ${[...names].join(', ')} } from '${pkg}/route-types'`, + ) +} + +const scopeApis = [ + 'Link', + 'createLink', + 'linkOptions', + 'Navigate', + 'useNavigate', + 'redirect', + 'MatchRoute', + 'useMatchRoute', + 'useRouter', + 'getRouteApi', + 'useMatch', + 'useMatches', + 'useParentMatches', + 'useChildMatches', + 'useLoaderData', + 'useLoaderDeps', + 'useSearch', + 'useParams', + 'useRouteContext', + 'useLocation', + 'useRouterState', + 'useLinkProps', + 'useBlocker', + 'notFound', +] as const + +function scopeBindings( + frameworkPackage: string, + routerType: string, + key: string, +) { + const binder = (api: string) => + `bindRouteScope${api[0]!.toUpperCase()}${api.slice(1)}` + return [ + `import { ${scopeApis.map(binder).join(', ')} } from '${frameworkPackage}/_internal/route-module'`, + `import type { RouteScope } from '${frameworkPackage}'`, + ...scopeApis.map( + (api) => + `export const ${api}: RouteScope<${routerType}>['${api}'] = /* @__PURE__ */ ${binder(api)}<${routerType}>('${key}')`, + ), + `import type { ValidateLinkOptions as RouterValidateLinkOptions, ValidateLinkOptionsArray as RouterValidateLinkOptionsArray, ValidateNavigateOptions as RouterValidateNavigateOptions, ValidateNavigateOptionsArray as RouterValidateNavigateOptionsArray, ValidateRedirectOptions as RouterValidateRedirectOptions, ValidateRedirectOptionsArray as RouterValidateRedirectOptionsArray, ValidateFromPath as RouterValidateFromPath, ValidateToPath as RouterValidateToPath, ValidateSearch as RouterValidateSearch, ValidateParams as RouterValidateParams, ValidateId as RouterValidateId, ValidateUseSearchOptions as RouterValidateUseSearchOptions, ValidateUseParamsOptions as RouterValidateUseParamsOptions } from '${frameworkPackage}'`, + `export type ValidateLinkOptions = RouterValidateLinkOptions<${routerType}, TOptions, TDefaultFrom, TComp>`, + `export type ValidateLinkOptionsArray = ReadonlyArray, TDefaultFrom extends string = string, TComp = 'a'> = RouterValidateLinkOptionsArray<${routerType}, TOptions, TDefaultFrom, TComp>`, + `export type ValidateNavigateOptions = RouterValidateNavigateOptions<${routerType}, TOptions, TDefaultFrom>`, + `export type ValidateNavigateOptionsArray = ReadonlyArray, TDefaultFrom extends string = string> = RouterValidateNavigateOptionsArray<${routerType}, TOptions, TDefaultFrom>`, + `export type ValidateRedirectOptions = RouterValidateRedirectOptions<${routerType}, TOptions, TDefaultFrom>`, + `export type ValidateRedirectOptionsArray = ReadonlyArray, TDefaultFrom extends string = string> = RouterValidateRedirectOptionsArray<${routerType}, TOptions, TDefaultFrom>`, + `export type ValidateFromPath = RouterValidateFromPath<${routerType}, TFrom>`, + `export type ValidateToPath = RouterValidateToPath<${routerType}, TTo, TFrom>`, + `export type ValidateSearch = RouterValidateSearch<${routerType}, TTo, TFrom>`, + `export type ValidateParams = RouterValidateParams<${routerType}, TTo, TFrom>`, + `export type ValidateId = RouterValidateId<${routerType}, TId>`, + `export type ValidateUseSearchOptions = RouterValidateUseSearchOptions`, + `export type ValidateUseParamsOptions = RouterValidateUseParamsOptions`, + ] +} + +function scopeMatchGuard( + frameworkPackage: string, + routerType: string, + routeIds: Array, +) { + // Every route id of a module starts with its root id, `:` or + // `#:`, and package names contain no colon. Checking + // these prefixes instead of listing every route keeps the guard small and + // accepts routes a module adds after this scope was generated. Explicitly + // named installations check their final identity. Local provider routes + // accept any installation of that provider, using the stable local id. + const local = new Set() + const installed = new Set() + for (const id of routeIds) { + const root = id.slice(0, id.indexOf(':') + 1) + ;(root.includes('#') ? installed : local).add(root) + } + const checks = [ + ...[...local].map( + (root) => `localRouteId.startsWith(${JSON.stringify(root)})`, + ), + ...[...installed].map( + (root) => `match.routeId.startsWith(${JSON.stringify(root)})`, + ), + ] + return [ + `import type { AnyRouteMatch, KnownRouteMatchUnion } from '${frameworkPackage}'`, + `/** Narrows a full router match to the routes installed in this scope. */ +export function isScopedMatch(match: AnyRouteMatch): match is KnownRouteMatchUnion<${routerType}> { + ${local.size ? "const localRouteId = match.localRouteId ?? ''\n " : ''}return ${checks.length ? checks.join(' || ') : 'false'} +}`, + ] +} + +export function getRouteNamespaceFile( + module: ScopeModule, + context: RouteModuleContext, +) { + // Ordinal names are portable on case-insensitive filesystems and do not + // impose filesystem length limits on otherwise valid public JS aliases. + return `${ROUTE_SCOPE_FILE}.namespace${context.scope + .map((entry) => entry.key) + .sort() + .indexOf(module.key)}` +} + +function namespaceRouteIds(context: RouteModuleContext, module: ScopeModule) { + const manifest = context.manifests.get(module.source.contractPackage)! + const rootId = `${module.source.installedKey ?? module.moduleId}:` + const included = new Set([rootId]) + // A manifest is not required to list parents before children. + for (let size = -1; size !== included.size; ) { + size = included.size + for (const route of manifest.routes) { + if (route.parent && included.has(route.parent)) { + included.add(route.id) + } + } + } + return [...included].map((id) => + module.key === module.moduleId || !id.startsWith(`${module.moduleId}:`) + ? id + : module.key + id.slice(module.moduleId.length), + ) +} + +/** An ESM namespace preserves products.Link without retaining unused APIs. */ +export function buildRouteNamespaceSource(opts: { + context: RouteModuleContext + module: ScopeModule + frameworkPackage: string + routeTreeImport: string + header: Array +}) { + const { context, module, frameworkPackage } = opts + let router = routerTypeOf(module, context.identifiers) + const lines = [ + ...opts.header, + GENERATED_NOTICE, + `import type { ScopedRouter, HostedRouter } from '${frameworkPackage}'`, + ...contractTypeImports([module], context.identifiers), + ] + if (module.hostedThrough !== undefined) { + lines.push( + `import type { MountedModuleHostParams } from '${opts.routeTreeImport}'`, + ) + router = `HostedRouter<${router}, ${hostParamsOf(module as ScopeModule & { hostedThrough: string }, context.identifiers)}>` + } + lines.push( + `type Router = ScopedRouter<${router}, '${module.key}'>`, + ...scopeBindings(frameworkPackage, 'Router', module.key), + ...scopeMatchGuard( + frameworkPackage, + 'Router', + namespaceRouteIds(context, module), + ), + ) + return lines.join('\n\n') + '\n' +} + +/** Source of routeScope.gen.ts; each runtime API is an independent ESM export. */ +export function buildRouteScopeSource(opts: { + context: RouteModuleContext + frameworkPackage: string + routeTreeImport: string + startImport: string + ownRouteIds: Array + namespaceImport: (module: ScopeModule) => string + header: Array +}): string { + const { context, frameworkPackage } = opts + const { declaration } = context + const lines: Array = [...opts.header, GENERATED_NOTICE] + if (declaration.mode === 'module') { + const moduleId = declaration.moduleId! + const start = context.start + lines.push( + `import { bindCreateModuleRoot } from '${frameworkPackage}/_internal/route-module'`, + `import { createFileRoute as createFrameworkFileRoute } from '${frameworkPackage}'`, + `import type { ScopeRouter, FileRouteScope } from '${frameworkPackage}'`, + `import type { FileRoutesByPath, routeTree } from '${opts.routeTreeImport}'`, + `export type RouteModuleRouter = ScopeRouter`, + ) + if (start) { + lines.push( + `import { createServerFn as createStartServerFn, createMiddleware as createStartMiddleware } from '${start.package}'`, + `import { createStartModule as createStartModuleFor } from '${start.package}/_internal/route-module'`, + `import type { CreateServerFn, CreateMiddlewareFn, StartModuleRegister${start.file ? ', StartModuleConfig' : ''} } from '${start.package}'`, + ...(start.file + ? [`import type { start } from '${opts.startImport}'`] + : []), + ) + } + lines.push( + `export interface RouteModuleRegister${start ? ` extends StartModuleRegister<'${moduleId}'>` : ''} { + router: RouteModuleRouter${start ? `\n ssr: true${start.file ? '\n config: StartModuleConfig' : ''}` : ''} +}`, + `export const createFileRoute = createFrameworkFileRoute as FileRouteScope['createFileRoute']`, + `export const createModuleRoot = /* @__PURE__ */ bindCreateModuleRoot('${moduleId}')`, + ...scopeBindings(frameworkPackage, 'RouteModuleRouter', moduleId), + ...scopeMatchGuard( + frameworkPackage, + 'RouteModuleRouter', + opts.ownRouteIds, + ), + ) + if (start) { + lines.push( + `export const createServerFn = createStartServerFn as unknown as CreateServerFn`, + `export const createMiddleware = createStartMiddleware as unknown as CreateMiddlewareFn>`, + `export const createStartModule = /* @__PURE__ */ createStartModuleFor('${moduleId}')`, + ) + } + } + for (const module of context.scope) { + lines.push( + `export * as ${module.namespace} from '${opts.namespaceImport(module)}'`, + ) + } + if (declaration.mode === 'host' && context.scope.length === 0) { + lines.push('export {}') + } + return lines.join('\n\n') + '\n' +} + +/** Source of `routeContract.gen.ts`: the public type entry of a module. */ +export function buildRouteContractSource(opts: { + context: RouteModuleContext + frameworkPackage: string + routeTreeImport: string + routeScopeImport: string + header: Array +}): string { + const { context } = opts + const moduleId = context.declaration.moduleId! + const mounted = context.mounts.map((mount) => ({ + moduleId: mount.moduleId, + identifier: getModuleIdentifier(mount.moduleId, context.identifiers), + })) + const lines: Array = [...opts.header, GENERATED_NOTICE] + lines.push( + [ + `import type { RouteModuleRouter } from '${opts.routeScopeImport}'`, + ...(context.mounts.some((mount) => mount.as !== undefined) + ? [ + `import type { InstallationRoutesById } from '${opts.frameworkPackage}'`, + ] + : []), + `import type { FileRoutesById, ${mounted.length ? 'MountedModuleHostParams, ' : ''}routeTree } from '${opts.routeTreeImport}'`, + ...mounted.map( + ({ moduleId: id, identifier }) => + `import type { InstalledHostParams as ${identifier}InstalledHostParams, InstalledRoutesById as ${identifier}InstalledRoutesById, InstalledRouters as ${identifier}InstalledRouters } from '${id}/route-types'`, + ), + ].join('\n'), + ) + const hostParams = context.mounts.flatMap((mount) => { + const identifier = getModuleIdentifier(mount.moduleId, context.identifiers) + const above = `MountedModuleHostParams['${mount.key}']` + return mount.manifest.modules.map((installed) => + installed.id === mount.moduleId + ? ` '${mount.key}': ${above}` + : ` '${installed.key}': ${above} & ${identifier}InstalledHostParams['${installed.key}']`, + ) + }) + lines.push( + `/** The route tree of "${moduleId}": its module root with all its routes. */ +export type RouteModuleTree = typeof routeTree`, + `/** The router type of "${moduleId}" (module-local paths, qualified ids). */ +export type Router = RouteModuleRouter`, + `/** The routes of "${moduleId}" by qualified id, without other modules. */ +export type OwnRoutesById = FileRoutesById`, + `/** All routes installed with "${moduleId}", including the modules it mounts. */ +export interface InstalledRoutesById extends FileRoutesById${mounted + .map(({ moduleId, identifier }) => { + const mount = context.mounts.find( + (entry) => entry.moduleId === moduleId, + )! + return mount.as === undefined + ? `, ${identifier}InstalledRoutesById` + : `, InstallationRoutesById<${identifier}InstalledRoutesById, '${moduleId}', '${mount.as}'>` + }) + .join('')} {}`, + `/** The routers of "${moduleId}" and of every module it mounts, by module id. */ +export interface InstalledRouters${ + mounted.length + ? ` extends ${mounted.map(({ identifier }) => `Omit<${identifier}InstalledRouters, '${context.mounts.find((mount) => getModuleIdentifier(mount.moduleId, context.identifiers) === identifier)!.moduleId}'>`).join(', ')}` + : '' + } { + '${moduleId}': Router +${context.mounts.map((mount) => ` '${mount.key}': ${getModuleIdentifier(mount.moduleId, context.identifiers)}InstalledRouters['${mount.moduleId}']`).join('\n')} +}`, + `/** + * The path params above every module "${moduleId}" installs, relative to its + * root. Packages that mount "${moduleId}" under path params add their own. + */ +export interface InstalledHostParams {${hostParams.length ? `\n${hostParams.join('\n')}\n` : ''}}`, + ) + return lines.join('\n\n') + '\n' +} + +function startModulesImports(context: RouteModuleContext) { + return context.startMounts.map((moduleId) => ({ + identifier: `${getModuleIdentifier(moduleId, context.identifiers)}StartModules`, + statement: `import { startModules as ${getModuleIdentifier(moduleId, context.identifiers)}StartModules } from '${moduleId}/route-module'`, + })) +} + +/** Source of `routeModule.gen.ts`: the runtime entry includers import. */ +export function buildRouteModuleSource(opts: { + context: RouteModuleContext + routeTreeImport: string + /** Import specifier of the module's Start file. */ + startImport: string + header: Array +}): string { + const { context } = opts + const lines: Array = [...opts.header, GENERATED_NOTICE] + const mounted = startModulesImports(context) + const ownFragment = context.exportsStartModules && !!context.start?.file + if (context.exportsStartModules) { + lines.push( + [ + ...(ownFragment ? [`import { start } from '${opts.startImport}'`] : []), + ...mounted.map((entry) => entry.statement), + ].join('\n'), + ) + } + lines.push( + `/** The root route of this module with all its routes. Mount it with \`mountRouteModule\`. */ +export { routeTree as routeModule } from '${opts.routeTreeImport}'`, + ) + if (context.exportsStartModules) { + const entries = [ + ...mounted.map((entry) => `...${entry.identifier}`), + ...(ownFragment ? ['start'] : []), + ] + const types = [ + ...mounted.map((entry) => `...typeof ${entry.identifier}`), + ...(ownFragment ? ['typeof start'] : []), + ] + lines.push( + `/** + * The TanStack Start fragments of this module and of the modules it mounts. + * Applications install them with \`createStart(() => ({ extends: startModules }))\`. + */ +export const startModules: readonly [${types.join(', ')}] = [${entries.join(', ')}]`, + ) + } + return lines.join('\n\n') + '\n' +} + +/** + * Source of an application's `startModules.gen.ts`: the Start fragments of + * every installed route module, and a type check of the application's + * Start instance against them. + */ +export function buildStartModulesSource(opts: { + context: RouteModuleContext + /** Import specifier of the application's Start file. */ + startImport: string + header: Array +}): string { + const { context } = opts + const mounted = startModulesImports(context) + return ( + [ + ...opts.header, + GENERATED_NOTICE, + [ + `import type { AssertStartModules, ValidateStartModules } from '${context.start!.package}'`, + ...(context.start!.file + ? [`import type { startInstance } from '${opts.startImport}'`] + : [`import type { StartInstance } from '${context.start!.package}'`]), + ...mounted.map((entry) => entry.statement), + ].join('\n'), + `/** + * The TanStack Start fragments of every installed route module. Install them + * with \`createStart(() => ({ extends: startModules }))\`. + */ +export const startModules: readonly [${mounted + .map((entry) => `...typeof ${entry.identifier}`) + .join(', ')}] = [${mounted + .map((entry) => `...${entry.identifier}`) + .join(', ')}]`, + ...(!context.start!.file + ? [`type DefaultStartInstance = StartInstance<[], true, [], []>`] + : []), + `/** + * Fails to type-check when \`startInstance\` does not install the fragments or + * does not provide the context they require. + */ +export type StartModulesCheck = AssertStartModules< + ValidateStartModules<${context.start!.file ? 'typeof startInstance' : 'DefaultStartInstance'}, typeof startModules, readonly [${[...new Set(context.mounts.flatMap((mount) => mount.manifest.modules.map((module) => module.id.split('#')[0]!)))].map((id) => `'${id}'`).join(', ')}]> +>`, + ].join('\n\n') + '\n' + ) +} diff --git a/packages/router-generator/src/route-module/manifest.ts b/packages/router-generator/src/route-module/manifest.ts new file mode 100644 index 0000000000..06ae18931a --- /dev/null +++ b/packages/router-generator/src/route-module/manifest.ts @@ -0,0 +1,126 @@ +import path from 'node:path' +import { existsSync, mkdirSync, readFileSync } from 'node:fs' +import * as fsp from 'node:fs/promises' +import crypto from 'node:crypto' + +export const ROUTE_MODULE_MANIFEST_VERSION = 2 + +/** A route of a module subtree, with its path relative to the module root. */ +export interface ManifestRoute { + id: string + /** + * Id of the parent route; `null` for the module root, whose parent is the + * route the module is mounted under. + */ + parent: string | null + /** Full path relative to the module root (module-local for own routes). */ + fullPath: string + /** Whether the route has no children (used for path conflict checks). */ + leaf: boolean + /** Provider-side page eligibility; consumers resolve the final URL. */ + prerender?: boolean +} + +/** A module installed in the subtree of a manifest's module. */ +export interface ManifestInstalledModule { + id: string + /** Runtime installation identity; differs from id for an explicit name. */ + key: string + /** Modules whose routes this module references. */ + uses: Array + /** Full path of the module root relative to the manifest's module root. */ + mountPath: string + /** Package that installs the module (`null` for the manifest's module). */ + includedBy: string | null +} + +/** + * `.tanstack/route-module.json`: the topology of a route module, written by its + * own route generation and read by the packages that install or use it. + */ +export interface RouteModuleManifest { + version: typeof ROUTE_MODULE_MANIFEST_VERSION + id: string + packageName: string + /** All routes of the module's subtree, including installed modules. */ + routes: Array + /** + * Route source paths relative to their provider. `owner` is the dependency + * chain from this package to that provider, resolved in order by consumers. + * Relative physical() paths outside a provider retain their source layout. + */ + routeFiles: Array<{ owner: Array; file: string; routeId: string }> + /** Portable client-only views of provider route trees. */ + clientTrees: Array<{ owner: Array; file: string; clientFile: string }> + /** The module itself and every module installed in its subtree. */ + modules: Array + /** + * Whether the module's runtime entry exports `startModules`: the TanStack + * Start fragments of the module and of the modules it installs. + */ + startModules: boolean + /** Hash of the topology above; changes whenever includers must regenerate. */ + topologyToken: string +} + +export function getManifestPath(packageRoot: string) { + return path.join(packageRoot, '.tanstack', 'route-module.json') +} + +function readVersioned(file: string, what: string): T | undefined { + if (!existsSync(file)) { + return undefined + } + const value = JSON.parse(readFileSync(file, 'utf8')) as { version: number } + if (value.version !== ROUTE_MODULE_MANIFEST_VERSION) { + throw new Error( + `The ${what} "${file}" has version ${value.version}; this generator reads version ${ROUTE_MODULE_MANIFEST_VERSION}. Regenerate it with the same version of @tanstack/router-generator.`, + ) + } + return value as T +} + +/** Writes `value` as JSON if the content changed. Returns whether it wrote. */ +async function writeJson(file: string, value: unknown): Promise { + const content = `${JSON.stringify(value, null, 2)}\n` + if (existsSync(file) && readFileSync(file, 'utf8') === content) { + return false + } + mkdirSync(path.dirname(file), { recursive: true }) + const tmp = `${file}.${process.pid}.tmp` + await fsp.writeFile(tmp, content) + await fsp.rename(tmp, file) + return true +} + +export function readManifest( + packageRoot: string, +): RouteModuleManifest | undefined { + return readVersioned(getManifestPath(packageRoot), 'route module manifest') +} + +export function writeManifest( + packageRoot: string, + manifest: RouteModuleManifest, +): Promise { + return writeJson(getManifestPath(packageRoot), manifest) +} + +export function computeTopologyToken( + manifest: Omit, +): string { + return crypto + .createHash('sha256') + .update( + JSON.stringify({ + id: manifest.id, + routes: manifest.routes, + routeFiles: manifest.routeFiles, + clientTrees: manifest.clientTrees, + modules: manifest.modules, + startModules: manifest.startModules, + }), + ) + .digest('hex') + .slice(0, 16) +} diff --git a/packages/router-generator/src/routeClassification.ts b/packages/router-generator/src/routeClassification.ts new file mode 100644 index 0000000000..e662595b5e --- /dev/null +++ b/packages/router-generator/src/routeClassification.ts @@ -0,0 +1,11 @@ +import type { RouteNode } from './types' + +/** Page eligibility before resolving its installation's full URL. */ +export function isPrerenderableRoute(node: RouteNode): boolean { + return Boolean( + node.routePath && + !node.routePath.includes('$') && + !node.isNonPath && + node.createFileRouteProps?.has('component'), + ) +} diff --git a/packages/router-generator/src/transform/transform.ts b/packages/router-generator/src/transform/transform.ts index 9fcad87948..8a0f31bcdc 100644 --- a/packages/router-generator/src/transform/transform.ts +++ b/packages/router-generator/src/transform/transform.ts @@ -119,12 +119,44 @@ export function transform({ routeCall.routeIdArg.start!, routeCall.routeIdArg.end!, ) - const targetModule = `@tanstack/${ctx.target}-router` + const frameworkModule = `@tanstack/${ctx.target}-router` + const targetModule = ctx.routeImportSource ?? frameworkModule const imports = parseTargetImports(ast.program.body, source, targetModule) const s = new MagicString(source) let modified = false + // Route-module files take route constructors from their scope module only: + // the framework package or a stale scope path (a moved file) lose them. + if (targetModule !== frameworkModule) { + for (const declaration of parseTargetImports( + ast.program.body, + source, + (moduleName) => moduleName !== targetModule, + )) { + const named = declaration.named.filter( + (specifier) => !isRouteConstructorName(specifier.imported), + ) + if (named.length === declaration.named.length) { + continue + } + const replacement = renderImportDeclaration({ ...declaration, named }) + if (replacement === null) { + s.remove( + declaration.declaration.start!, + getRemovalEnd(source, declaration.declaration.end!), + ) + } else { + s.update( + declaration.declaration.start!, + declaration.declaration.end!, + replacement, + ) + } + modified = true + } + } + if (routeCall.callee.name !== expectedCallee) { s.update(routeCall.callee.start!, routeCall.callee.end!, expectedCallee) modified = true @@ -351,15 +383,19 @@ function getCreateFileRouteProps( function parseTargetImports( body: Array, source: string, - targetModule: string, + targetModule: string | ((moduleName: string) => boolean), ) { const imports: Array = [] + const isTarget = + typeof targetModule === 'string' + ? (moduleName: string) => moduleName === targetModule + : targetModule for (const statement of body) { if ( !t.isImportDeclaration(statement) || statement.importKind === 'type' || - statement.source.value !== targetModule + !isTarget(statement.source.value) ) { continue } diff --git a/packages/router-generator/src/transform/types.ts b/packages/router-generator/src/transform/types.ts index 4a8fecaada..a9c869d781 100644 --- a/packages/router-generator/src/transform/types.ts +++ b/packages/router-generator/src/transform/types.ts @@ -28,4 +28,9 @@ export interface TransformContext { target: Config['target'] routeId: string lazy: boolean + /** + * Module that route constructors are imported from. Defaults to the + * framework package; route modules import them from their scope module. + */ + routeImportSource?: string } diff --git a/packages/router-generator/src/types.ts b/packages/router-generator/src/types.ts index ec0aa226ce..2ee83bdd3e 100644 --- a/packages/router-generator/src/types.ts +++ b/packages/router-generator/src/types.ts @@ -27,6 +27,16 @@ export type RouteNode = { _virtualParentRoutePath?: string /** Internal routePath segment metadata for escaped or explicit literal syntax. */ _routePathSegmentMetadata?: Array + /** + * Internal: this node is the root of a mounted route module. It has no file + * and only appears in the children of its host route. + */ + _routeModuleMount?: { + moduleId: string + /** The module id, or `#` for one of several installations. */ + installation: string + at: string | undefined + } } export interface GetRouteNodesResult { diff --git a/packages/router-generator/src/utils.ts b/packages/router-generator/src/utils.ts index 747980aa7b..7d933f9d47 100644 --- a/packages/router-generator/src/utils.ts +++ b/packages/router-generator/src/utils.ts @@ -1241,28 +1241,44 @@ export const findParent = (node: RouteNode | undefined): string => { export function buildFileRoutesByPathInterface(opts: { routeNodes: Array - module: string + /** + * Module to augment. Without it the interface is exported locally (route + * modules), and entries omit `preLoaderRoute`, which only the deprecated + * lazy and loader route APIs read. + */ + module: string | undefined interfaceName: string config?: Pick + /** Maps a route path to the route id (route modules qualify ids). */ + qualifyId?: (id: string) => string }): string { - return `declare module '${opts.module}' { - interface ${opts.interfaceName} { - ${opts.routeNodes - .map((routeNode) => { - const filePathId = routeNode.routePath - const preloaderRoute = `typeof ${routeNode.variableName}RouteImport` + const qualifyId = opts.qualifyId ?? ((id: string) => id) + const entries = opts.routeNodes + .map((routeNode) => { + const filePathId = qualifyId(routeNode.routePath ?? '') + const parent = findParent(routeNode) - const parent = findParent(routeNode) - - return `'${filePathId}': { + return `'${filePathId}': { id: '${filePathId}' path: '${inferPath(routeNode)}' - fullPath: '${inferFullPath(routeNode)}' - preLoaderRoute: ${preloaderRoute} + fullPath: '${inferFullPath(routeNode)}'${ + opts.module === undefined + ? '' + : `\n preLoaderRoute: typeof ${routeNode.variableName}RouteImport` + } parentRoute: typeof ${parent} }` - }) - .join('\n')} + }) + .join('\n') + + if (opts.module === undefined) { + return `export interface ${opts.interfaceName} { + ${entries} +}` + } + return `declare module '${opts.module}' { + interface ${opts.interfaceName} { + ${entries} } }` } diff --git a/packages/router-generator/tests/route-modules.test.ts b/packages/router-generator/tests/route-modules.test.ts new file mode 100644 index 0000000000..8204c082c5 --- /dev/null +++ b/packages/router-generator/tests/route-modules.test.ts @@ -0,0 +1,1859 @@ +import fs from 'node:fs/promises' +import { spawnSync } from 'node:child_process' +import { existsSync, readFileSync, realpathSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { createJiti } from 'jiti' +import { fileURLToPath } from 'node:url' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' + +import { Generator, getConfig, readRouteModuleManifest } from '../src' + +let workspace: string + +beforeEach(async () => { + workspace = realpathSync( + await fs.mkdtemp(path.join(os.tmpdir(), 'tsr-generator-modules-')), + ) +}) + +afterEach(async () => { + await fs.rm(workspace, { recursive: true, force: true }) +}) + +interface PackageSpec { + name: string + packageJson?: Record + files: Record + dependencies?: Array +} + +/** Writes a package into the workspace; dependencies are linked siblings. */ +async function writePackage(spec: PackageSpec) { + const root = path.join(workspace, spec.name.replace('@fixture/', '')) + await fs.mkdir(root, { recursive: true }) + await fs.writeFile( + path.join(root, 'package.json'), + JSON.stringify( + { + name: spec.name, + dependencies: Object.fromEntries( + (spec.dependencies ?? []).map((dependency) => [dependency, '*']), + ), + ...spec.packageJson, + }, + null, + 2, + ), + ) + for (const [file, content] of Object.entries(spec.files)) { + await fs.mkdir(path.dirname(path.join(root, file)), { recursive: true }) + await fs.writeFile(path.join(root, file), content) + } + for (const dependency of spec.dependencies ?? []) { + const link = path.join(root, 'node_modules', dependency) + await fs.mkdir(path.dirname(link), { recursive: true }) + await fs.symlink( + path.join(workspace, dependency.replace('@fixture/', '')), + link, + 'dir', + ) + } + return root +} + +async function generate(root: string, inline: Record = {}) { + const config = getConfig( + { + disableLogging: true, + tmpDir: path.join(workspace, '.tmp'), + routesDirectory: './src/routes', + generatedRouteTree: './src/routeTree.gen.ts', + ...inline, + }, + root, + ) + await new Generator({ config, root }).run() +} + +const read = (root: string, file: string) => + readFileSync(path.join(root, file), 'utf8') + +/** Generated files are formatted: compare their content on one line. */ +const compact = (source: string) => source.replace(/\s+/g, ' ') + +function readNamespace(root: string, namespace: string) { + const entry = [ + ...read(root, 'src/routeScope.gen.ts').matchAll( + /export \* as (\w+) from '([^']+)'/g, + ), + ].find((match) => match[1] === namespace) + if (!entry) { + throw new Error(`Generated namespace ${namespace} was not exported`) + } + return read(root, path.join('src', `${entry[2]}.ts`)) +} + +async function linkRouter(root: string) { + const target = fileURLToPath(new URL('../../react-router', import.meta.url)) + const link = path.join(root, 'node_modules/@tanstack/react-router') + await fs.mkdir(path.dirname(link), { recursive: true }) + await fs.symlink(target, link, 'dir') +} + +async function checkConsumerTypes( + root: string, + files: Array, + compilerOptions: Record = {}, +) { + await fs.writeFile( + path.join(root, 'tsconfig.json'), + JSON.stringify({ + compilerOptions: { + target: 'ES2022', + module: 'ESNext', + moduleResolution: 'Bundler', + jsx: 'react-jsx', + strict: true, + skipLibCheck: false, + noEmit: true, + types: [], + ...compilerOptions, + }, + files, + }), + ) + const compiler = fileURLToPath( + new URL('../../../node_modules/typescript59/lib/tsc.js', import.meta.url), + ) + const result = spawnSync( + process.execPath, + [compiler, '--pretty', 'false', '-p', root], + { + encoding: 'utf8', + stdio: 'pipe', + }, + ) + if (result.error) { + throw result.error + } + const diagnostics = `${result.stdout ?? ''}${result.stderr ?? ''}` + return result.status === 0 + ? diagnostics + : diagnostics || `TypeScript exited with status ${result.status}` +} + +const moduleRoot = `import { Outlet } from '@tanstack/react-router' +import { createModuleRoot } from '../routeScope.gen' + +export const Route = createModuleRoot()({ component: () => }) +` + +const route = ( + id: string, +) => `import { createFileRoute } from '../routeScope.gen' + +export const Route = createFileRoute('${id}')({}) +` + +describe('installed route-module composition contracts', () => { + const appRoot = `import { createRootRoute } from '@tanstack/react-router' +export const Route = createRootRoute() +` + + it('preserves adjacent TypeScript declaration outputs when regenerating namespaces', async () => { + const catalog = await writePackage( + catalogPackage({ + packageJson: { + tanstack: { router: { module: true } }, + exports: { + './route-module': './src/routeModule.gen.ts', + './route-types': './src/routeContract.gen.ts', + }, + }, + files: { + 'src/routes/__root.tsx': `import { createModuleRoot } from '../routeScope.gen' +export const Route = createModuleRoot()({})`, + 'src/routes/profile.tsx': route('@fixture/catalog:/profile'), + }, + }), + ) + await linkRouter(catalog) + await generate(catalog) + const shop = await writePackage({ + name: '@fixture/shop', + dependencies: ['@fixture/catalog'], + packageJson: { + tanstack: { router: { module: { uses: ['@fixture/catalog'] } } }, + }, + files: { + 'src/routes/__root.tsx': `import { createModuleRoot } from '../routeScope.gen' +export const Route = createModuleRoot()({})`, + }, + }) + await linkRouter(shop) + const config = { routeFileIgnorePattern: '\\.d\\.ts$' } + await generate(shop, config) + expect( + await checkConsumerTypes(shop, ['src/routeScope.gen.ts'], { + noEmit: false, + declaration: true, + emitDeclarationOnly: true, + }), + ).toBe('') + const namespaceFiles = [ + ...read(shop, 'src/routeScope.gen.ts').matchAll( + /export \* as \w+ from '([^']+)'/g, + ), + ].map((match) => path.join('src', `${match[1]}.d.ts`)) + expect(namespaceFiles).toHaveLength(1) + const declarations = ['src/routeScope.gen.d.ts', ...namespaceFiles].map( + (file) => ({ file, content: read(shop, file) }), + ) + await generate(shop, config) + for (const declaration of declarations) { + expect(read(shop, declaration.file)).toBe(declaration.content) + } + }, 30_000) + + it('uses an explicit installation name for the first installation', async () => { + const catalog = await writePackage(catalogPackage()) + await generate(catalog) + const app = await writePackage({ + name: '@fixture/app', + dependencies: ['@fixture/catalog'], + files: { 'src/routes/__root.tsx': appRoot }, + }) + const generator = new Generator({ + root: app, + config: getConfig( + { + disableLogging: true, + tmpDir: path.join(workspace, '.tmp'), + routeModules: { + includes: [ + { + module: '@fixture/catalog', + as: 'catalogFeature', + at: '/catalog', + }, + ], + }, + }, + app, + ), + }) + await generator.run() + expect( + generator.getMountedRouteModuleRoutes().map((node) => node.id), + ).toContain('@fixture/catalog#catalogFeature:/$itemId') + }) + + it.each(['catalog', '/catalog'])( + 'checks collisions for the mount spelling %s', + async (at) => { + const catalog = await writePackage(catalogPackage()) + await generate(catalog) + const app = await writePackage({ + name: '@fixture/app', + dependencies: ['@fixture/catalog'], + files: { + 'src/routes/__root.tsx': appRoot, + 'src/routes/catalog.tsx': `import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/catalog')({}) +`, + }, + }) + await expect( + generate(app, { + routeModules: { includes: [{ module: '@fixture/catalog', at }] }, + }), + ).rejects.toThrow(/full path.*used by both/i) + }, + ) + + it.each(['catalog//sale', '/catalog//sale/'])( + 'checks collisions after normalizing interior slashes in %s', + async (at) => { + const catalog = await writePackage(catalogPackage()) + await generate(catalog) + const app = await writePackage({ + name: '@fixture/app', + dependencies: ['@fixture/catalog'], + files: { + 'src/routes/__root.tsx': appRoot, + 'src/routes/catalog.sale.tsx': `import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/catalog/sale')({})`, + }, + }) + await expect( + generate(app, { + routeModules: { includes: [{ module: '@fixture/catalog', at }] }, + }), + ).rejects.toThrow(/full path.*used by both/i) + }, + ) + + it('rejects host and module path parameter overlap', async () => { + const catalog = await writePackage(catalogPackage()) + await generate(catalog) + const app = await writePackage({ + name: '@fixture/app', + dependencies: ['@fixture/catalog'], + files: { + 'src/routes/__root.tsx': appRoot, + 'src/routes/orgs.$itemId.tsx': `import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/orgs/$itemId')({})`, + }, + }) + await expect( + generate(app, { + routeModules: { + includes: [ + { + module: '@fixture/catalog', + parent: '/orgs/$itemId', + at: '/catalog', + }, + ], + }, + }), + ).rejects.toThrow(/parameter.*itemId|itemId.*parameter/i) + }) + + it.each(['$', '{$}[.]txt'])( + 'rejects a module wildcard %s that overwrites a host _splat parameter', + async (file) => { + const catalog = await writePackage( + catalogPackage({ + files: { + 'src/routes/__root.tsx': moduleRoot, + [`src/routes/${file}.tsx`]: '', + }, + }), + ) + await generate(catalog) + const app = await writePackage({ + name: '@fixture/app', + dependencies: ['@fixture/catalog'], + files: { + 'src/routes/__root.tsx': appRoot, + 'src/routes/orgs.$_splat.tsx': `import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/orgs/$_splat')({})`, + }, + }) + await expect( + generate(app, { + routeModules: { + includes: [ + { + module: '@fixture/catalog', + parent: '/orgs/$_splat', + at: '/catalog', + }, + ], + }, + }), + ).rejects.toThrow(/parameter.*_splat|_splat.*parameter/i) + }, + ) + + it('preserves named nested installation contracts and hosted namespace guards', async () => { + const exports = { + './route-module': './src/routeModule.gen.ts', + './route-types': './src/routeContract.gen.ts', + } + const catalog = await writePackage( + catalogPackage({ + packageJson: { tanstack: { router: { module: true } }, exports }, + files: { + 'src/routes/__root.tsx': `import { createModuleRoot } from '../routeScope.gen' +export const Route = createModuleRoot()({})`, + 'src/routes/profile.tsx': route('@fixture/catalog:/profile'), + }, + }), + ) + await linkRouter(catalog) + await generate(catalog) + const shop = await writePackage({ + name: '@fixture/shop', + dependencies: ['@fixture/catalog'], + packageJson: { + exports, + tanstack: { + router: { + module: { + includes: [ + { + module: '@fixture/catalog', + as: 'ownedCatalog', + parent: '/teams/$teamId', + at: '/catalog', + }, + ], + }, + }, + }, + }, + files: { + 'src/routes/__root.tsx': `import { createModuleRoot } from '../routeScope.gen' +export const Route = createModuleRoot()({})`, + 'src/routes/teams.$teamId.tsx': route('@fixture/shop:/teams/$teamId'), + }, + }) + await linkRouter(shop) + await generate(shop) + const manifest = readRouteModuleManifest(shop)! + expect(manifest.modules).toContainEqual( + expect.objectContaining({ + id: '@fixture/catalog', + key: '@fixture/catalog#ownedCatalog', + }), + ) + expect(manifest.routes).toContainEqual( + expect.objectContaining({ + id: '@fixture/catalog#ownedCatalog:/profile', + parent: '@fixture/catalog#ownedCatalog:', + fullPath: '/teams/$teamId/catalog/profile', + }), + ) + const app = await writePackage({ + name: '@fixture/app', + dependencies: ['@fixture/shop'], + files: { + 'src/routes/__root.tsx': appRoot, + 'src/routes/orgs.$orgId.tsx': `import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/orgs/$orgId')({})`, + 'src/consumer.ts': `import type { InstalledRoutesById, InstalledHostParams } from '@fixture/shop/route-types' +import { catalog } from './routeScope.gen' +const id: InstalledRoutesById['@fixture/catalog#ownedCatalog:/profile']['id'] = '@fixture/catalog#ownedCatalog:/profile' +const host: InstalledHostParams['@fixture/catalog#ownedCatalog'] = { teamId: 'team' } +catalog.linkOptions({ to: '/profile', params: { orgId: 'org', teamId: host.teamId } }) +export { id } +`, + }, + }) + await linkRouter(app) + await generate(app, { + routeModules: { + includes: [ + { + module: '@fixture/shop', + as: 'namedShop', + parent: '/orgs/$orgId', + at: '/shop', + }, + ], + }, + }) + expect(await checkConsumerTypes(app, ['src/consumer.ts'])).toBe('') + const jiti = createJiti(import.meta.url, { + moduleCache: false, + fsCache: false, + }) + const scope = await jiti.import<{ + catalog: { + isScopedMatch: (match: { + routeId: string + localRouteId?: string + }) => boolean + } + namedShop: { + isScopedMatch: (match: { + routeId: string + localRouteId?: string + }) => boolean + } + }>(path.join(app, 'src/routeScope.gen.ts')) + const match = { + routeId: '@fixture/catalog#ownedCatalog:/profile', + localRouteId: '@fixture/catalog:/profile', + } + expect(scope.catalog.isScopedMatch(match)).toBe(true) + expect(scope.namedShop.isScopedMatch(match)).toBe(true) + expect( + scope.catalog.isScopedMatch({ + ...match, + routeId: '@fixture/catalog#other:/profile', + }), + ).toBe(false) + // Membership follows module root ids, not the routes known at generation: + // a route the module adds later passes, an installation whose name merely + // starts with the same characters does not, and neither does an + // application route. + expect( + scope.namedShop.isScopedMatch({ + routeId: '@fixture/catalog#ownedCatalog:/added', + localRouteId: '@fixture/catalog:/added', + }), + ).toBe(true) + expect( + scope.catalog.isScopedMatch({ + ...match, + routeId: '@fixture/catalog#ownedCatalogs:/profile', + }), + ).toBe(false) + expect(scope.namedShop.isScopedMatch({ routeId: '/orgs/$orgId' })).toBe( + false, + ) + // The provider's own scope combines both checks: its routes pass in any + // installation through `localRouteId`, the installation it names passes + // through `routeId`. + const shopScope = await jiti.import<{ + isScopedMatch: (match: { + routeId: string + localRouteId?: string + }) => boolean + }>(path.join(shop, 'src/routeScope.gen.ts')) + expect( + shopScope.isScopedMatch({ + routeId: '@fixture/shop#namedShop:/teams/$teamId', + localRouteId: '@fixture/shop:/teams/$teamId', + }), + ).toBe(true) + expect(shopScope.isScopedMatch(match)).toBe(true) + expect( + shopScope.isScopedMatch({ + ...match, + routeId: '@fixture/catalog#ownedCatalogs:/profile', + }), + ).toBe(false) + }, 30_000) + + it('keeps case-only namespace aliases independently addressable on portable filenames', async () => { + const catalog = await writePackage(catalogPackage()) + await generate(catalog) + const app = await writePackage({ + name: '@fixture/app', + dependencies: ['@fixture/catalog'], + files: { 'src/routes/__root.tsx': appRoot }, + }) + await linkRouter(app) + await generate(app, { + routeModules: { + includes: [ + { module: '@fixture/catalog', as: 'catalog', at: '/first' }, + { module: '@fixture/catalog', as: 'Catalog', at: '/second' }, + ], + }, + }) + const namespaceFiles = [ + ...read(app, 'src/routeScope.gen.ts').matchAll( + /export \* as \w+ from '([^']+)'/g, + ), + ].map((match) => match[1]!) + expect(namespaceFiles).toHaveLength(2) + expect(new Set(namespaceFiles.map((file) => file.toLowerCase())).size).toBe( + 2, + ) + const jiti = createJiti(import.meta.url, { + moduleCache: false, + fsCache: false, + }) + const scope = await jiti.import<{ + catalog: { linkOptions: (options: { to: string }) => { _module: string } } + Catalog: { linkOptions: (options: { to: string }) => { _module: string } } + }>(path.join(app, 'src/routeScope.gen.ts')) + expect(scope.catalog.linkOptions({ to: '/' })._module).toBe( + '@fixture/catalog#catalog', + ) + expect(scope.Catalog.linkOptions({ to: '/' })._module).toBe( + '@fixture/catalog#Catalog', + ) + }) + + it.each(['bindRouteScopeLink', 'createStartServerFn'])( + 'allows the namespace export %s beside a private imported binding', + async (alias) => { + const catalog = await writePackage( + catalogPackage({ + packageJson: { + tanstack: { router: { module: true } }, + exports: { + './route-module': './src/routeModule.gen.ts', + './route-types': './src/routeContract.gen.ts', + }, + }, + files: { + 'src/routes/__root.tsx': `import { createModuleRoot } from '../routeScope.gen' +export const Route = createModuleRoot()({})`, + 'src/routes/profile.tsx': route('@fixture/catalog:/profile'), + }, + }), + ) + await linkRouter(catalog) + await generate(catalog) + const shop = await writePackage({ + name: '@fixture/shop', + dependencies: ['@fixture/catalog'], + packageJson: { + dependencies: { + '@fixture/catalog': '*', + '@tanstack/react-start': '*', + }, + tanstack: { + router: { + module: { uses: [{ module: '@fixture/catalog', as: alias }] }, + }, + }, + }, + files: { + 'src/routes/__root.tsx': `import { createModuleRoot } from '../routeScope.gen' +export const Route = createModuleRoot()({})`, + 'src/routes/index.tsx': route('@fixture/shop:/'), + 'src/consumer.ts': `import { ${alias}, linkOptions, createServerFn } from './routeScope.gen' +export const ownLink = linkOptions({ to: '/' }) +export const dependencyLink = ${alias}.linkOptions({ to: '/profile' }) +export const serverFn = createServerFn().handler(() => 'ok') +// @ts-expect-error The dependency namespace retains its provider's local paths. +${alias}.linkOptions({ to: '/outside' }) +`, + }, + }) + await linkRouter(shop) + await fs.symlink( + fileURLToPath(new URL('../../react-start', import.meta.url)), + path.join(shop, 'node_modules/@tanstack/react-start'), + 'dir', + ) + await fs.mkdir(path.join(shop, 'node_modules/@types'), { + recursive: true, + }) + await fs.symlink( + fileURLToPath( + new URL('../../../node_modules/@types/node', import.meta.url), + ), + path.join(shop, 'node_modules/@types/node'), + 'dir', + ) + await generate(shop) + expect( + await checkConsumerTypes(shop, ['src/consumer.ts'], { + types: ['node'], + }), + ).toBe('') + }, + 30_000, + ) + + it('loads ordinary routes whose derived private names collide', async () => { + const app = await writePackage({ + name: '@fixture/app', + files: { + 'src/routes/__root.tsx': appRoot, + 'src/routes/foo-bar.tsx': `import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/foo-bar')({})`, + 'src/routes/fooBar.tsx': `import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/fooBar')({})`, + }, + }) + await linkRouter(app) + await generate(app) + const jiti = createJiti(import.meta.url, { + moduleCache: false, + fsCache: false, + }) + await expect( + jiti.import(path.join(app, 'src/routeTree.gen.ts')), + ).resolves.toHaveProperty('routeTree') + const source = read(app, 'src/routeTree.gen.ts') + await generate(app) + expect(read(app, 'src/routeTree.gen.ts')).toBe(source) + }) + + it('loads packages whose private identifiers normalize to the same name', async () => { + for (const name of ['foo-bar', 'foo_bar']) { + const root = await writePackage({ + name: `@fixture/${name}`, + packageJson: { + tanstack: { router: { module: true } }, + exports: { './route-module': './src/routeModule.gen.ts' }, + }, + files: { + 'src/routes/__root.tsx': `import { createModuleRoot } from '../routeScope.gen' +export const Route = createModuleRoot()({})`, + 'src/routes/index.tsx': route(`@fixture/${name}:/`), + }, + }) + await linkRouter(root) + await generate(root) + } + const app = await writePackage({ + name: '@fixture/app', + dependencies: ['@fixture/foo-bar', '@fixture/foo_bar'], + files: { 'src/routes/__root.tsx': appRoot }, + }) + await linkRouter(app) + await generate(app, { + routeModules: { + includes: [ + { module: '@fixture/foo-bar', as: 'first', at: '/first' }, + { module: '@fixture/foo_bar', as: 'second', at: '/second' }, + ], + }, + }) + const jiti = createJiti(import.meta.url, { + moduleCache: false, + fsCache: false, + }) + await expect( + jiti.import(path.join(app, 'src/routeTree.gen.ts')), + ).resolves.toHaveProperty('routeTree') + }) + + it('resolves cached provider route files after moving the workspace', async () => { + const catalog = await writePackage(catalogPackage()) + await generate(catalog) + await writePackage({ + name: '@fixture/app', + dependencies: ['@fixture/catalog'], + files: { 'src/routes/__root.tsx': appRoot }, + }) + const moved = `${workspace}-relocated` + await fs.rename(workspace, moved) + workspace = moved + const app = path.join(workspace, 'app') + const movedCatalog = path.join(workspace, 'catalog') + const dependency = path.join(app, 'node_modules/@fixture/catalog') + await fs.unlink(dependency) + await fs.symlink(movedCatalog, dependency, 'dir') + const generator = new Generator({ + root: app, + config: getConfig( + { + disableLogging: true, + tmpDir: path.join(workspace, '.tmp'), + routeModules: { + includes: [{ module: '@fixture/catalog', at: '/catalog' }], + }, + }, + app, + ), + }) + await generator.run() + expect( + generator + .getRoutesByFileMap() + .get(path.join(movedCatalog, 'src/routes/$itemId.tsx')), + ).toEqual({ routeId: '@fixture/catalog:/$itemId' }) + }) + + it('refreshes consumer topology when provider source and generated tree paths change', async () => { + const catalog = await writePackage( + catalogPackage({ + files: { + 'src/routes/__root.tsx': moduleRoot, + 'src/routes/profile.tsx': route('@fixture/catalog:/profile'), + }, + }), + ) + await generate(catalog) + const app = await writePackage({ + name: '@fixture/app', + dependencies: ['@fixture/catalog'], + files: { 'src/routes/__root.tsx': appRoot }, + }) + const changes: Array> = + [] + const generator = new Generator({ + root: app, + config: getConfig( + { + disableLogging: true, + tmpDir: path.join(workspace, '.tmp'), + routeModules: { + includes: [{ module: '@fixture/catalog', at: '/catalog' }], + }, + plugins: [ + { + name: 'observe-provider-paths', + onRouteTreeChanged() { + changes.push(generator.getRouteModuleClientTrees()) + }, + }, + ], + }, + app, + ), + }) + await generator.run() + const originalRoutes = readRouteModuleManifest(catalog)!.routes + await fs.mkdir(path.join(catalog, 'src/routes/profile')) + await fs.rename( + path.join(catalog, 'src/routes/profile.tsx'), + path.join(catalog, 'src/routes/profile/route.tsx'), + ) + await generate(catalog) + expect(readRouteModuleManifest(catalog)!.routes).toEqual(originalRoutes) + await generator.run({ + type: 'update', + path: path.join(catalog, '.tanstack/route-module.json'), + }) + expect(changes).toHaveLength(2) + expect(generator.getMountedRouteModuleRoutes()).toContainEqual( + expect.objectContaining({ + id: '@fixture/catalog:/profile', + filePath: path.join(catalog, 'src/routes/profile/route.tsx'), + }), + ) + expect( + generator + .getRoutesByFileMap() + .get(path.join(catalog, 'src/routes/profile/route.tsx')), + ).toEqual({ + routeId: '@fixture/catalog:/profile', + }) + await generate(catalog, { generatedRouteTree: './src/movedTree.gen.ts' }) + expect(readRouteModuleManifest(catalog)!.routes).toEqual(originalRoutes) + await generator.run({ + type: 'update', + path: path.join(catalog, '.tanstack/route-module.json'), + }) + expect(changes).toHaveLength(3) + expect(changes[2]).toContainEqual({ + filePath: path.join(catalog, 'src/movedTree.gen.ts'), + clientFilePath: path.join(catalog, 'src/movedTree.gen.client.ts'), + }) + }) + + it('accepts routes a used provider gains before and after its namespace is regenerated', async () => { + const runtimeModuleRoot = `import { createModuleRoot } from '../routeScope.gen' +export const Route = createModuleRoot()({}) +` + const exports = { + './route-module': './src/routeModule.gen.ts', + './route-types': './src/routeContract.gen.ts', + './scope': './src/routeScope.gen.ts', + } + const catalog = await writePackage( + catalogPackage({ + packageJson: { tanstack: { router: { module: true } }, exports }, + files: { + 'src/routes/__root.tsx': runtimeModuleRoot, + 'src/routes/profile.tsx': route('@fixture/catalog:/profile'), + }, + }), + ) + await linkRouter(catalog) + await generate(catalog) + const shop = await writePackage({ + name: '@fixture/shop', + dependencies: ['@fixture/catalog'], + packageJson: { + exports, + tanstack: { router: { module: { uses: ['@fixture/catalog'] } } }, + }, + files: { 'src/routes/__root.tsx': runtimeModuleRoot }, + }) + await linkRouter(shop) + const consumerGenerator = new Generator({ + root: shop, + config: getConfig( + { disableLogging: true, tmpDir: path.join(workspace, '.tmp') }, + shop, + ), + }) + await consumerGenerator.run() + const app = await writePackage({ + name: '@fixture/app', + dependencies: ['@fixture/catalog', '@fixture/shop'], + files: { + 'src/routes/__root.tsx': appRoot, + 'src/consumer.ts': `import { createMemoryHistory, createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' +import { catalog } from '@fixture/shop/scope' +export function matchCatalog(pathname: string) { + const history = createMemoryHistory({ initialEntries: [pathname] }) + const router = createRouter({ routeTree, history, isServer: true }) + try { + const match = router.matchRoutes(pathname).at(-1)! + return { routeId: match.routeId, accepted: catalog.isScopedMatch(match) } + } finally { + history.destroy() + } +} +`, + }, + }) + await linkRouter(app) + const appOptions = { + routeModules: { + includes: [ + { module: '@fixture/catalog', at: '/catalog' }, + { module: '@fixture/shop', at: '/shop' }, + ], + }, + } + const loadConsumer = () => + createJiti(import.meta.url, { + moduleCache: false, + fsCache: false, + }).import<{ + matchCatalog: (pathname: string) => { + routeId: string + accepted: boolean + } + }>(path.join(app, 'src/consumer.ts')) + await generate(app, appOptions) + expect((await loadConsumer()).matchCatalog('/catalog/profile')).toEqual({ + routeId: '@fixture/catalog:/profile', + accepted: true, + }) + + await fs.writeFile( + path.join(catalog, 'src/routes/settings.tsx'), + route('@fixture/catalog:/settings'), + ) + await generate(catalog) + // The guard tests module ids, so the shop scope generated before the route + // existed accepts it as soon as the application tree contains it. + await generate(app, appOptions) + expect((await loadConsumer()).matchCatalog('/catalog/settings')).toEqual({ + routeId: '@fixture/catalog:/settings', + accepted: true, + }) + await consumerGenerator.run({ + type: 'update', + path: path.join(catalog, '.tanstack/route-module.json'), + }) + await generate(app, appOptions) + expect((await loadConsumer()).matchCatalog('/catalog/settings')).toEqual({ + routeId: '@fixture/catalog:/settings', + accepted: true, + }) + }) +}) + +function catalogPackage(extra: Partial = {}): PackageSpec { + return { + name: '@fixture/catalog', + packageJson: { + tanstack: { router: { module: true } }, + }, + files: { + 'src/routes/__root.tsx': moduleRoot, + 'src/routes/index.tsx': route('@fixture/catalog:/'), + 'src/routes/$itemId.tsx': route('@fixture/catalog:/$itemId'), + 'src/routes/_layout.tsx': route('@fixture/catalog:/_layout'), + 'src/routes/_layout/sale.tsx': route( + '@fixture/catalog:/_layout/sale', + ).replace('../routeScope.gen', '../../routeScope.gen'), + }, + ...extra, + } +} + +describe('route module generation', () => { + it('generates qualified ids, a local FileRoutesByPath and the module files', async () => { + const pkg = await writePackage(catalogPackage()) + await generate(pkg) + + const routeTree = read(pkg, 'src/routeTree.gen.ts') + expect(routeTree).not.toContain('@ts-nocheck') + expect(routeTree).not.toContain('declare module') + expect(routeTree).not.toContain('preLoaderRoute') + await expect(routeTree).toMatchFileSnapshot( + 'route-modules/module/routeTree.snapshot.ts', + ) + await expect(read(pkg, 'src/routeScope.gen.ts')).toMatchFileSnapshot( + 'route-modules/module/routeScope.snapshot.ts', + ) + await expect(read(pkg, 'src/routeContract.gen.ts')).toMatchFileSnapshot( + 'route-modules/module/routeContract.snapshot.ts', + ) + await expect(read(pkg, 'src/routeModule.gen.ts')).toMatchFileSnapshot( + 'route-modules/module/routeModule.snapshot.ts', + ) + + // The module's own guard accepts its routes in any installation, including + // routes added after generation, and rejects other modules' routes and + // application routes. + await linkRouter(pkg) + const jiti = createJiti(import.meta.url, { + moduleCache: false, + fsCache: false, + }) + const scope = await jiti.import<{ + isScopedMatch: (match: { + routeId: string + localRouteId?: string + }) => boolean + }>(path.join(pkg, 'src/routeScope.gen.ts')) + expect( + scope.isScopedMatch({ + routeId: '@fixture/catalog#eu:/added', + localRouteId: '@fixture/catalog:/added', + }), + ).toBe(true) + expect( + scope.isScopedMatch({ + routeId: '@fixture/catalog-extra:/', + localRouteId: '@fixture/catalog-extra:/', + }), + ).toBe(false) + expect(scope.isScopedMatch({ routeId: '/about' })).toBe(false) + expect(scope.isScopedMatch({ routeId: '__root__' })).toBe(false) + + const manifest = readRouteModuleManifest(pkg)! + expect(manifest.id).toBe('@fixture/catalog') + const root = '@fixture/catalog:' + expect(manifest.routes).toEqual([ + { id: root, parent: null, fullPath: '/', leaf: false }, + { id: `${root}/`, parent: root, fullPath: '/', leaf: true }, + { id: `${root}/$itemId`, parent: root, fullPath: '/$itemId', leaf: true }, + { id: `${root}/_layout`, parent: root, fullPath: '/', leaf: false }, + { + id: `${root}/_layout/sale`, + parent: `${root}/_layout`, + fullPath: '/sale', + leaf: true, + }, + ]) + expect(manifest.routeFiles).toContainEqual({ + owner: [], + file: 'src/routes/$itemId.tsx', + routeId: '@fixture/catalog:/$itemId', + }) + expect(manifest.routeFiles).toContainEqual({ + owner: [], + file: 'src/routes/__root.tsx', + routeId: '@fixture/catalog:', + }) + }) + + it('rewrites route ids and route factory imports to the module scope', async () => { + const root = await writePackage( + catalogPackage({ + files: { + 'src/routes/__root.tsx': moduleRoot, + 'src/routes/index.tsx': `import { Link, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({}) +export const A = Link +`, + 'src/routes/empty.tsx': '', + }, + }), + ) + await generate(root) + + expect(read(root, 'src/routes/index.tsx')) + .toBe(`import { createFileRoute } from '../routeScope.gen' +import { Link } from '@tanstack/react-router' + +export const Route = createFileRoute('@fixture/catalog:/')({}) +export const A = Link +`) + const scaffolded = read(root, 'src/routes/empty.tsx') + expect(scaffolded).toContain( + "import { createFileRoute } from '../routeScope.gen'", + ) + expect(scaffolded).toContain("createFileRoute('@fixture/catalog:/empty')") + }) + + it('repairs a route factory import from a stale scope path', async () => { + const root = await writePackage( + catalogPackage({ + files: { + 'src/routes/__root.tsx': moduleRoot, + // moved one directory down without updating the import + 'src/routes/nested/moved.tsx': route( + '@fixture/catalog:/nested/moved', + ), + }, + }), + ) + await generate(root) + await generate(root) + expect(read(root, 'src/routes/nested/moved.tsx')).toBe( + `import { createFileRoute } from '../../routeScope.gen' + +export const Route = createFileRoute('@fixture/catalog:/nested/moved')({}) +`, + ) + }) + + it('scaffolds a module root', async () => { + const root = await writePackage( + catalogPackage({ files: { 'src/routes/__root.tsx': '' } }), + ) + await generate(root) + const scaffolded = read(root, 'src/routes/__root.tsx') + expect(scaffolded).toContain( + "import { createModuleRoot } from '../routeScope.gen'", + ) + expect(scaffolded).toContain('export const Route = createModuleRoot()(') + }) + + it('rejects lazy route files', async () => { + const root = await writePackage( + catalogPackage({ + files: { + 'src/routes/__root.tsx': moduleRoot, + 'src/routes/about.lazy.tsx': '', + }, + }), + ) + await expect(generate(root)).rejects.toThrow(/lazy route files/) + }) + + it('rejects disableTypes', async () => { + const root = await writePackage(catalogPackage()) + await expect(generate(root, { disableTypes: true })).rejects.toThrow( + /require TypeScript/, + ) + }) + + it('rejects an invalid declaration', async () => { + const root = await writePackage( + catalogPackage({ + packageJson: { + tanstack: { router: { module: { includes: [{ at: '/x' }] } } }, + }, + }), + ) + await expect(generate(root)).rejects.toThrow( + /Invalid "tanstack.router.module"/, + ) + }) +}) + +describe('mounting route modules', () => { + async function writeCatalog() { + const catalog = await writePackage(catalogPackage()) + await generate(catalog) + return catalog + } + + it('mounts included modules and composes their routes by id', async () => { + await writeCatalog() + const shop = await writePackage({ + name: '@fixture/shop', + packageJson: { + tanstack: { + router: { + module: { + includes: [ + { module: '@fixture/catalog', parent: '/_layout', at: '/c' }, + ], + }, + }, + }, + }, + dependencies: ['@fixture/catalog'], + files: { + 'src/routes/__root.tsx': moduleRoot, + 'src/routes/index.tsx': route('@fixture/shop:/'), + 'src/routes/_layout.tsx': route('@fixture/shop:/_layout'), + }, + }) + await generate(shop) + + await expect(read(shop, 'src/routeTree.gen.ts')).toMatchFileSnapshot( + 'route-modules/includer/routeTree.snapshot.ts', + ) + await expect(read(shop, 'src/routeScope.gen.ts')).toMatchFileSnapshot( + 'route-modules/includer/routeScope.snapshot.ts', + ) + await expect(readNamespace(shop, 'catalog')).toMatchFileSnapshot( + 'route-modules/includer/routeScope.catalog.snapshot.ts', + ) + await expect(read(shop, 'src/routeContract.gen.ts')).toMatchFileSnapshot( + 'route-modules/includer/routeContract.snapshot.ts', + ) + + const manifest = readRouteModuleManifest(shop)! + const catalogRoot = '@fixture/catalog:' + expect( + manifest.routes.filter((r) => r.id.startsWith('@fixture/catalog')), + ).toEqual([ + { + id: catalogRoot, + parent: '@fixture/shop:/_layout', + fullPath: '/c/', + leaf: false, + }, + { + id: `${catalogRoot}/`, + parent: catalogRoot, + fullPath: '/c/', + leaf: true, + }, + { + id: `${catalogRoot}/$itemId`, + parent: catalogRoot, + fullPath: '/c/$itemId', + leaf: true, + }, + { + id: `${catalogRoot}/_layout`, + parent: catalogRoot, + fullPath: '/c/', + leaf: false, + }, + { + id: `${catalogRoot}/_layout/sale`, + parent: `${catalogRoot}/_layout`, + fullPath: '/c/sale', + leaf: true, + }, + ]) + expect(manifest.modules).toEqual([ + { + id: '@fixture/shop', + key: '@fixture/shop', + uses: [], + mountPath: '/', + includedBy: null, + }, + { + id: '@fixture/catalog', + key: '@fixture/catalog', + uses: [], + mountPath: '/c/', + includedBy: '@fixture/shop', + }, + ]) + }) + + it('mounts modules into an application and keeps its own routes plain', async () => { + await writeCatalog() + const app = await writePackage({ + name: '@fixture/app', + dependencies: ['@fixture/catalog'], + files: { + 'src/routes/__root.tsx': `import { createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute() +`, + 'src/routes/index.tsx': `import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({}) +`, + }, + }) + await generate(app, { + routeModules: { + includes: [{ module: '@fixture/catalog', at: '/catalog' }], + }, + }) + + const routeTree = read(app, 'src/routeTree.gen.ts') + expect(routeTree).toContain("declare module '@tanstack/react-router'") + await expect(routeTree).toMatchFileSnapshot( + 'route-modules/application/routeTree.snapshot.ts', + ) + await expect(read(app, 'src/routeScope.gen.ts')).toMatchFileSnapshot( + 'route-modules/application/routeScope.snapshot.ts', + ) + await expect(readNamespace(app, 'catalog')).toMatchFileSnapshot( + 'route-modules/application/routeScope.catalog.snapshot.ts', + ) + expect(existsSync(path.join(app, 'src/routeContract.gen.ts'))).toBe(false) + expect(existsSync(path.join(app, '.tanstack/route-module.json'))).toBe( + false, + ) + }) + + it('lists the route files of mounted modules for bundlers', async () => { + const catalog = await writeCatalog() + const app = await writePackage({ + name: '@fixture/app', + dependencies: ['@fixture/catalog'], + files: { + 'src/routes/__root.tsx': `import { createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute() +`, + }, + }) + const config = getConfig( + { + disableLogging: true, + tmpDir: path.join(workspace, '.tmp'), + routesDirectory: './src/routes', + generatedRouteTree: './src/routeTree.gen.ts', + routeModules: { + includes: [{ module: '@fixture/catalog', at: '/catalog' }], + }, + }, + app, + ) + const generator = new Generator({ config, root: app }) + await generator.run() + + const routesByFile = generator.getRoutesByFileMap() + expect(routesByFile.get(path.join(app, 'src/routes/__root.tsx'))).toEqual({ + routeId: '/__root', + }) + expect( + routesByFile.get(path.join(catalog, 'src/routes/$itemId.tsx')), + ).toEqual({ routeId: '@fixture/catalog:/$itemId' }) + expect( + generator + .getMountedRouteModuleRoutes() + .filter((r) => r.id.includes('$itemId') || r.id.endsWith(':')), + ).toEqual([ + { + id: '@fixture/catalog:', + parent: '__root__', + filePath: path.join(catalog, 'src/routes/__root.tsx'), + fullPath: '/catalog/', + }, + { + id: '@fixture/catalog:/$itemId', + parent: '@fixture/catalog:', + filePath: path.join(catalog, 'src/routes/$itemId.tsx'), + fullPath: '/catalog/$itemId', + }, + ]) + expect(generator.getRouteModuleWatchFiles()).toEqual([ + path.join(app, 'package.json'), + path.join(catalog, 'package.json'), + path.join(catalog, '.tanstack/route-module.json'), + path.join(app, 'src/start.ts'), + path.join(app, 'src/start.tsx'), + ]) + }) + + it('rejects a module that is not a dependency', async () => { + await writeCatalog() + const app = await writePackage({ + name: '@fixture/app', + files: { + 'src/routes/__root.tsx': '', + }, + }) + await expect( + generate(app, { + routeModules: { + includes: [{ module: '@fixture/catalog', at: '/catalog' }], + }, + }), + ).rejects.toThrow(/is not a dependency/) + }) + + it('rejects a module without a manifest', async () => { + await writePackage(catalogPackage()) + const app = await writePackage({ + name: '@fixture/app', + dependencies: ['@fixture/catalog'], + files: { 'src/routes/__root.tsx': '' }, + }) + await expect( + generate(app, { + routeModules: { + includes: [{ module: '@fixture/catalog', at: '/catalog' }], + }, + }), + ).rejects.toThrow(/has no route module manifest/) + }) + + it('rejects an unknown parent route', async () => { + await writeCatalog() + const app = await writePackage({ + name: '@fixture/app', + dependencies: ['@fixture/catalog'], + files: { 'src/routes/__root.tsx': '' }, + }) + await expect( + generate(app, { + routeModules: { + includes: [{ module: '@fixture/catalog', parent: '/_missing' }], + }, + }), + ).rejects.toThrow(/parent route "\/_missing"/) + }) + + it('rejects full paths that collide with mounted module routes', async () => { + await writeCatalog() + const app = await writePackage({ + name: '@fixture/app', + dependencies: ['@fixture/catalog'], + files: { + 'src/routes/__root.tsx': '', + 'src/routes/catalog.sale.tsx': '', + }, + }) + await expect( + generate(app, { + routeModules: { + includes: [{ module: '@fixture/catalog', at: '/catalog' }], + }, + }), + ).rejects.toThrow(/full path "\/catalog\/sale"/) + }) + + it('rejects declaring modules in package.json and in the options', async () => { + const root = await writePackage(catalogPackage()) + await expect( + generate(root, { routeModules: { includes: [] } }), + ).rejects.toThrow(/in one place/) + }) +}) + +describe('mounting under path params', () => { + /** `@fixture/shop` mounts the catalog below its `/orgs/$orgId` route. */ + async function writeShop(includes: Array> = []) { + const catalog = await writePackage(catalogPackage()) + await generate(catalog) + const shop = await writePackage({ + name: '@fixture/shop', + packageJson: { + tanstack: { + router: { + module: { + includes: [ + { + module: '@fixture/catalog', + parent: '/orgs/$orgId', + at: '/catalog', + }, + ...includes, + ], + }, + }, + }, + }, + dependencies: [ + '@fixture/catalog', + ...includes.map((include) => include.module!), + ], + files: { + 'src/routes/__root.tsx': moduleRoot, + 'src/routes/index.tsx': route('@fixture/shop:/'), + 'src/routes/orgs.$orgId.tsx': route('@fixture/shop:/orgs/$orgId'), + }, + }) + return shop + } + + it('types the namespace of the mounted module with the path params above it', async () => { + const shop = await writeShop() + await generate(shop) + + await expect(read(shop, 'src/routeTree.gen.ts')).toMatchFileSnapshot( + 'route-modules/host-params/routeTree.snapshot.ts', + ) + await expect(read(shop, 'src/routeScope.gen.ts')).toMatchFileSnapshot( + 'route-modules/host-params/routeScope.snapshot.ts', + ) + await expect(readNamespace(shop, 'catalog')).toMatchFileSnapshot( + 'route-modules/host-params/routeScope.catalog.snapshot.ts', + ) + await expect(read(shop, 'src/routeContract.gen.ts')).toMatchFileSnapshot( + 'route-modules/host-params/routeContract.snapshot.ts', + ) + }) + + it('adds the path params inside a module for the modules it installs', async () => { + const shop = await writeShop() + await generate(shop) + const app = await writePackage({ + name: '@fixture/app', + dependencies: ['@fixture/shop'], + files: { + 'src/routes/__root.tsx': `import { createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute() +`, + }, + }) + await generate(app, { routeModules: { includes: ['@fixture/shop'] } }) + + const scope = compact(readNamespace(app, 'catalog')) + expect(scope).toContain( + "HostedRouter< FixtureShopInstalledRouters['@fixture/catalog'], MountedModuleHostParams['@fixture/shop'] & FixtureShopInstalledHostParams['@fixture/catalog']", + ) + expect(scope).toContain("bindRouteScopeLink('@fixture/catalog')") + // The shop itself is mounted at the root: its namespace takes no params. + expect(compact(readNamespace(app, 'shop'))).toContain( + "type Router = ScopedRouter", + ) + }) + + async function writeAccount() { + const account = await writePackage({ + name: '@fixture/account', + packageJson: { + tanstack: { router: { module: { uses: ['@fixture/catalog'] } } }, + }, + dependencies: ['@fixture/catalog'], + files: { + 'src/routes/__root.tsx': moduleRoot, + 'src/routes/index.tsx': route('@fixture/account:/'), + }, + }) + await generate(account) + } + + it('rejects a module that uses it from outside the routes with the params', async () => { + const shop = await writeShop([ + { module: '@fixture/account', at: '/account' }, + ]) + await writeAccount() + + await expect(generate(shop)).rejects.toThrow( + '"@fixture/account" links into "@fixture/catalog", which is mounted below "/orgs/$orgId", but "@fixture/account" is mounted at "/account"', + ) + }) + + it('accepts a module that uses it from below the routes with the params', async () => { + const shop = await writeShop([ + { module: '@fixture/account', parent: '/orgs/$orgId', at: '/account' }, + ]) + await writeAccount() + + await generate(shop) + expect(compact(readNamespace(shop, 'account'))).toContain( + "HostedRouter< FixtureAccountRouter, MountedModuleHostParams['@fixture/account']", + ) + }) +}) + +describe('installing a module several times', () => { + const appRoute = ( + path: string, + ) => `import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('${path}')({}) +` + + /** + * `@fixture/app` installs the catalog under `/orgs/$orgId` (`orgCatalog`) + * and `/users/$userId` (`userCatalog`); `@fixture/account`, which uses the + * catalog, is mounted at `account`. + */ + async function writeApp() { + const catalog = await writePackage(catalogPackage()) + await generate(catalog) + const account = await writePackage({ + name: '@fixture/account', + packageJson: { + tanstack: { router: { module: { uses: ['@fixture/catalog'] } } }, + }, + dependencies: ['@fixture/catalog'], + files: { + 'src/routes/__root.tsx': moduleRoot, + 'src/routes/index.tsx': route('@fixture/account:/'), + }, + }) + await generate(account) + return writePackage({ + name: '@fixture/app', + dependencies: ['@fixture/catalog', '@fixture/account'], + files: { + 'src/routes/__root.tsx': `import { createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute() +`, + 'src/routes/orgs.$orgId.tsx': appRoute('/orgs/$orgId'), + 'src/routes/users.$userId.tsx': appRoute('/users/$userId'), + }, + }) + } + + const installations = [ + { + module: '@fixture/catalog', + parent: '/orgs/$orgId', + at: '/catalog', + as: 'orgCatalog', + }, + { + module: '@fixture/catalog', + parent: '/users/$userId', + at: '/catalog', + as: 'userCatalog', + }, + ] + + it('mounts every installation and gives it a namespace', async () => { + const app = await writeApp() + await generate(app, { + routeModules: { + includes: [ + ...installations, + { + module: '@fixture/account', + parent: '/orgs/$orgId', + at: '/account', + }, + ], + }, + }) + + await expect(read(app, 'src/routeTree.gen.ts')).toMatchFileSnapshot( + 'route-modules/installations/routeTree.snapshot.ts', + ) + await expect(read(app, 'src/routeScope.gen.ts')).toMatchFileSnapshot( + 'route-modules/installations/routeScope.snapshot.ts', + ) + for (const namespace of ['orgCatalog', 'userCatalog', 'account']) { + await expect(readNamespace(app, namespace)).toMatchFileSnapshot( + `route-modules/installations/routeScope.${namespace}.snapshot.ts`, + ) + } + }) + + it('requires a name for every installation', async () => { + const app = await writeApp() + + await expect( + generate(app, { + routeModules: { + includes: [installations[0], { ...installations[1], as: undefined }], + }, + }), + ).rejects.toThrow( + '"@fixture/catalog" is included more than once. Name every installation with "as".', + ) + await expect( + generate(app, { + routeModules: { + includes: [ + installations[0], + { ...installations[1], as: 'orgCatalog' }, + ], + }, + }), + ).rejects.toThrow( + 'two installations of "@fixture/catalog" are named "orgCatalog"', + ) + }) + + it('rejects a module that uses it from below no installation', async () => { + const app = await writeApp() + + await expect( + generate(app, { + routeModules: { + includes: [ + ...installations, + { module: '@fixture/account', at: '/account' }, + ], + }, + }), + ).rejects.toThrow( + '"@fixture/account" links into "@fixture/catalog", which is installed several times, but no installation can take path params from "/account"', + ) + }) + + it('lets only applications install a module several times', async () => { + const catalog = await writePackage(catalogPackage()) + await generate(catalog) + const shop = await writePackage({ + name: '@fixture/shop', + packageJson: { + tanstack: { router: { module: { includes: installations } } }, + }, + dependencies: ['@fixture/catalog'], + files: { + 'src/routes/__root.tsx': moduleRoot, + 'src/routes/orgs.$orgId.tsx': route('@fixture/shop:/orgs/$orgId'), + 'src/routes/users.$userId.tsx': route('@fixture/shop:/users/$userId'), + }, + }) + + await expect(generate(shop)).rejects.toThrow( + 'Only an application can install a route module several times.', + ) + }) +}) + +describe('TanStack Start fragments', () => { + const startDependency = { '@tanstack/react-start': '*' } + const startFile = `import { createStartModule } from './routeScope.gen' + +export const start = createStartModule(() => ({})) +` + const appRoot = `import { createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute() +` + + async function writeStartCatalog(withFragment = true) { + const base = catalogPackage() + const catalog = await writePackage({ + ...base, + packageJson: { ...base.packageJson, dependencies: startDependency }, + files: { + ...base.files, + ...(withFragment ? { 'src/start.ts': startFile } : {}), + }, + }) + await generate(catalog) + return catalog + } + + async function writeStartApp(opts: { + startApp: boolean + startFile: boolean + }) { + return writePackage({ + name: '@fixture/app', + dependencies: ['@fixture/catalog'], + packageJson: { + dependencies: { + '@fixture/catalog': '*', + ...(opts.startApp ? startDependency : {}), + }, + }, + files: { + 'src/routes/__root.tsx': appRoot, + ...(opts.startFile + ? { + 'src/start.ts': `import { createStart } from '@tanstack/react-start' +import { startModules } from './startModules.gen' + +export const startInstance = createStart(() => ({ extends: startModules })) +`, + } + : {}), + }, + }) + } + + it('gives a Start module typed server functions and exports its fragment', async () => { + const catalog = await writeStartCatalog() + + await expect(read(catalog, 'src/routeScope.gen.ts')).toMatchFileSnapshot( + 'route-modules/start-module/routeScope.snapshot.ts', + ) + await expect(read(catalog, 'src/routeModule.gen.ts')).toMatchFileSnapshot( + 'route-modules/start-module/routeModule.snapshot.ts', + ) + expect(readRouteModuleManifest(catalog)!.startModules).toBe(true) + }) + + it('registers a Start module without a fragment for server rendering only', async () => { + const catalog = await writeStartCatalog(false) + + const scope = read(catalog, 'src/routeScope.gen.ts') + expect(scope).toContain(' ssr: true\n}') + expect(scope).toContain('export const createServerFn') + expect(scope).not.toContain('StartModuleConfig') + expect(read(catalog, 'src/routeModule.gen.ts')).not.toContain( + 'startModules', + ) + expect(readRouteModuleManifest(catalog)!.startModules).toBe(false) + }) + + it('generates installed requirement validation for the default Start instance', async () => { + await writeStartCatalog(false) + const app = await writeStartApp({ startApp: true, startFile: false }) + await generate(app, { + routeModules: { + includes: [{ module: '@fixture/catalog', at: '/catalog' }], + }, + }) + const validation = compact(read(app, 'src/startModules.gen.ts')) + expect(validation).toContain( + 'export type StartModulesCheck = AssertStartModules<', + ) + expect(validation).toMatch( + /ValidateStartModules<[^,]+, typeof startModules, readonly \['@fixture\/catalog'\]/, + ) + expect(validation).toContain("from '@tanstack/react-start'") + }) + + it('passes the fragments of mounted modules on to the application', async () => { + await writeStartCatalog() + const shop = await writePackage({ + name: '@fixture/shop', + packageJson: { + tanstack: { + router: { + module: { + includes: [{ module: '@fixture/catalog', at: '/catalog' }], + }, + }, + }, + }, + dependencies: ['@fixture/catalog'], + files: { 'src/routes/__root.tsx': moduleRoot }, + }) + await generate(shop) + + const routeModule = read(shop, 'src/routeModule.gen.ts') + expect(routeModule).toContain( + "import { startModules as FixtureCatalogStartModules } from '@fixture/catalog/route-module'", + ) + expect(routeModule).toMatch( + /export const startModules: readonly \[\.\.\.typeof FixtureCatalogStartModules\] = \[\s*\.\.\.FixtureCatalogStartModules,?\s*\]/, + ) + // The includer itself does not use Start. + expect(read(shop, 'src/routeScope.gen.ts')).not.toContain('createServerFn') + expect(readRouteModuleManifest(shop)!.startModules).toBe(true) + }) + + it('lists the fragments for the Start instance of an application', async () => { + await writeStartCatalog() + const app = await writeStartApp({ startApp: true, startFile: true }) + await generate(app, { + routeModules: { + includes: [{ module: '@fixture/catalog', at: '/catalog' }], + }, + }) + + await expect(read(app, 'src/startModules.gen.ts')).toMatchFileSnapshot( + 'route-modules/start-application/startModules.snapshot.ts', + ) + }) + + it('retains installed requirement validation when the final fragment is removed', async () => { + await writeStartCatalog() + const app = await writeStartApp({ startApp: true, startFile: true }) + await generate(app, { + routeModules: { + includes: [{ module: '@fixture/catalog', at: '/catalog' }], + }, + }) + expect(existsSync(path.join(app, 'src/startModules.gen.ts'))).toBe(true) + + await writeStartCatalog(false) + await fs.rm(path.join(workspace, 'catalog/src/start.ts')) + await generate(path.join(workspace, 'catalog')) + await generate(app, { + routeModules: { + includes: [{ module: '@fixture/catalog', at: '/catalog' }], + }, + }) + const validation = compact(read(app, 'src/startModules.gen.ts')) + expect(validation).toContain('export const startModules: readonly [] = []') + expect(validation).toContain( + 'export type StartModulesCheck = AssertStartModules<', + ) + expect(validation).toContain("readonly ['@fixture/catalog']") + }) + + it('requires a Start file in an application that installs a fragment', async () => { + await writeStartCatalog() + const app = await writeStartApp({ startApp: true, startFile: false }) + + await expect( + generate(app, { + routeModules: { + includes: [{ module: '@fixture/catalog', at: '/catalog' }], + }, + }), + ).rejects.toThrow( + /"@fixture\/catalog" has a TanStack Start fragment\. Install it in ".*src\/start\.ts": export const startInstance = createStart/, + ) + }) + + it('rejects a fragment in an application without TanStack Start', async () => { + await writeStartCatalog() + const app = await writeStartApp({ startApp: false, startFile: false }) + + await expect( + generate(app, { + routeModules: { + includes: [{ module: '@fixture/catalog', at: '/catalog' }], + }, + }), + ).rejects.toThrow( + /Install it in a TanStack Start application, which depends on "@tanstack\/react-start"/, + ) + }) +}) diff --git a/packages/router-generator/tests/route-modules/application/routeScope.catalog.snapshot.ts b/packages/router-generator/tests/route-modules/application/routeScope.catalog.snapshot.ts new file mode 100644 index 0000000000..086f9f431b --- /dev/null +++ b/packages/router-generator/tests/route-modules/application/routeScope.catalog.snapshot.ts @@ -0,0 +1,210 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import type { ScopedRouter, HostedRouter } from '@tanstack/react-router' + +import type { Router as FixtureCatalogRouter } from '@fixture/catalog/route-types' + +type Router = ScopedRouter + +import { + bindRouteScopeLink, + bindRouteScopeCreateLink, + bindRouteScopeLinkOptions, + bindRouteScopeNavigate, + bindRouteScopeUseNavigate, + bindRouteScopeRedirect, + bindRouteScopeMatchRoute, + bindRouteScopeUseMatchRoute, + bindRouteScopeUseRouter, + bindRouteScopeGetRouteApi, + bindRouteScopeUseMatch, + bindRouteScopeUseMatches, + bindRouteScopeUseParentMatches, + bindRouteScopeUseChildMatches, + bindRouteScopeUseLoaderData, + bindRouteScopeUseLoaderDeps, + bindRouteScopeUseSearch, + bindRouteScopeUseParams, + bindRouteScopeUseRouteContext, + bindRouteScopeUseLocation, + bindRouteScopeUseRouterState, + bindRouteScopeUseLinkProps, + bindRouteScopeUseBlocker, + bindRouteScopeNotFound, +} from '@tanstack/react-router/_internal/route-module' + +import type { RouteScope } from '@tanstack/react-router' + +export const Link: RouteScope['Link'] = + /* @__PURE__ */ bindRouteScopeLink('@fixture/catalog') + +export const createLink: RouteScope['createLink'] = + /* @__PURE__ */ bindRouteScopeCreateLink('@fixture/catalog') + +export const linkOptions: RouteScope['linkOptions'] = + /* @__PURE__ */ bindRouteScopeLinkOptions('@fixture/catalog') + +export const Navigate: RouteScope['Navigate'] = + /* @__PURE__ */ bindRouteScopeNavigate('@fixture/catalog') + +export const useNavigate: RouteScope['useNavigate'] = + /* @__PURE__ */ bindRouteScopeUseNavigate('@fixture/catalog') + +export const redirect: RouteScope['redirect'] = + /* @__PURE__ */ bindRouteScopeRedirect('@fixture/catalog') + +export const MatchRoute: RouteScope['MatchRoute'] = + /* @__PURE__ */ bindRouteScopeMatchRoute('@fixture/catalog') + +export const useMatchRoute: RouteScope['useMatchRoute'] = + /* @__PURE__ */ bindRouteScopeUseMatchRoute('@fixture/catalog') + +export const useRouter: RouteScope['useRouter'] = + /* @__PURE__ */ bindRouteScopeUseRouter('@fixture/catalog') + +export const getRouteApi: RouteScope['getRouteApi'] = + /* @__PURE__ */ bindRouteScopeGetRouteApi('@fixture/catalog') + +export const useMatch: RouteScope['useMatch'] = + /* @__PURE__ */ bindRouteScopeUseMatch('@fixture/catalog') + +export const useMatches: RouteScope['useMatches'] = + /* @__PURE__ */ bindRouteScopeUseMatches('@fixture/catalog') + +export const useParentMatches: RouteScope['useParentMatches'] = + /* @__PURE__ */ bindRouteScopeUseParentMatches('@fixture/catalog') + +export const useChildMatches: RouteScope['useChildMatches'] = + /* @__PURE__ */ bindRouteScopeUseChildMatches('@fixture/catalog') + +export const useLoaderData: RouteScope['useLoaderData'] = + /* @__PURE__ */ bindRouteScopeUseLoaderData('@fixture/catalog') + +export const useLoaderDeps: RouteScope['useLoaderDeps'] = + /* @__PURE__ */ bindRouteScopeUseLoaderDeps('@fixture/catalog') + +export const useSearch: RouteScope['useSearch'] = + /* @__PURE__ */ bindRouteScopeUseSearch('@fixture/catalog') + +export const useParams: RouteScope['useParams'] = + /* @__PURE__ */ bindRouteScopeUseParams('@fixture/catalog') + +export const useRouteContext: RouteScope['useRouteContext'] = + /* @__PURE__ */ bindRouteScopeUseRouteContext('@fixture/catalog') + +export const useLocation: RouteScope['useLocation'] = + /* @__PURE__ */ bindRouteScopeUseLocation('@fixture/catalog') + +export const useRouterState: RouteScope['useRouterState'] = + /* @__PURE__ */ bindRouteScopeUseRouterState('@fixture/catalog') + +export const useLinkProps: RouteScope['useLinkProps'] = + /* @__PURE__ */ bindRouteScopeUseLinkProps('@fixture/catalog') + +export const useBlocker: RouteScope['useBlocker'] = + /* @__PURE__ */ bindRouteScopeUseBlocker('@fixture/catalog') + +export const notFound: RouteScope['notFound'] = + /* @__PURE__ */ bindRouteScopeNotFound('@fixture/catalog') + +import type { + ValidateLinkOptions as RouterValidateLinkOptions, + ValidateLinkOptionsArray as RouterValidateLinkOptionsArray, + ValidateNavigateOptions as RouterValidateNavigateOptions, + ValidateNavigateOptionsArray as RouterValidateNavigateOptionsArray, + ValidateRedirectOptions as RouterValidateRedirectOptions, + ValidateRedirectOptionsArray as RouterValidateRedirectOptionsArray, + ValidateFromPath as RouterValidateFromPath, + ValidateToPath as RouterValidateToPath, + ValidateSearch as RouterValidateSearch, + ValidateParams as RouterValidateParams, + ValidateId as RouterValidateId, + ValidateUseSearchOptions as RouterValidateUseSearchOptions, + ValidateUseParamsOptions as RouterValidateUseParamsOptions, +} from '@tanstack/react-router' + +export type ValidateLinkOptions< + TOptions = unknown, + TDefaultFrom extends string = string, + TComp = 'a', +> = RouterValidateLinkOptions + +export type ValidateLinkOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, + TComp = 'a', +> = RouterValidateLinkOptionsArray + +export type ValidateNavigateOptions< + TOptions = unknown, + TDefaultFrom extends string = string, +> = RouterValidateNavigateOptions + +export type ValidateNavigateOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, +> = RouterValidateNavigateOptionsArray + +export type ValidateRedirectOptions< + TOptions = unknown, + TDefaultFrom extends string = string, +> = RouterValidateRedirectOptions + +export type ValidateRedirectOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, +> = RouterValidateRedirectOptionsArray + +export type ValidateFromPath = RouterValidateFromPath< + Router, + TFrom +> + +export type ValidateToPath< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateToPath + +export type ValidateSearch< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateSearch + +export type ValidateParams< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateParams + +export type ValidateId = RouterValidateId< + Router, + TId +> + +export type ValidateUseSearchOptions = RouterValidateUseSearchOptions< + TOptions, + Router +> + +export type ValidateUseParamsOptions = RouterValidateUseParamsOptions< + TOptions, + Router +> + +import type { + AnyRouteMatch, + KnownRouteMatchUnion, +} from '@tanstack/react-router' + +/** Narrows a full router match to the routes installed in this scope. */ +export function isScopedMatch( + match: AnyRouteMatch, +): match is KnownRouteMatchUnion { + const localRouteId = match.localRouteId ?? '' + return localRouteId.startsWith('@fixture/catalog:') +} diff --git a/packages/router-generator/tests/route-modules/application/routeScope.snapshot.ts b/packages/router-generator/tests/route-modules/application/routeScope.snapshot.ts new file mode 100644 index 0000000000..631ae0fb37 --- /dev/null +++ b/packages/router-generator/tests/route-modules/application/routeScope.snapshot.ts @@ -0,0 +1,9 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +export * as catalog from './routeScope.gen.namespace0' diff --git a/packages/router-generator/tests/route-modules/application/routeTree.snapshot.ts b/packages/router-generator/tests/route-modules/application/routeTree.snapshot.ts new file mode 100644 index 0000000000..7dca3bfddd --- /dev/null +++ b/packages/router-generator/tests/route-modules/application/routeTree.snapshot.ts @@ -0,0 +1,79 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { mountRouteModule } from '@tanstack/react-router/_internal/route-module' +import { routeModule as FixtureCatalogRouteModule } from '@fixture/catalog/route-module' +import type { MountedRoutesById } from '@tanstack/react-router' +import type { InstalledRoutesById as FixtureCatalogInstalledRoutesById } from '@fixture/catalog/route-types' + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) + +const FixtureCatalogModuleRoute: typeof FixtureCatalogRouteModule = + mountRouteModule(FixtureCatalogRouteModule, { + parent: () => rootRouteImport, + at: '/catalog', + }) + +/** The path params of the routes above each mounted route module. */ +export interface MountedModuleHostParams { + '@fixture/catalog': (typeof rootRouteImport)['types']['allParams'] +} + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute +} +interface RouteModuleRoutesById + extends + FileRoutesById, + MountedRoutesById {} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' + fileRoutesByTo: FileRoutesByTo + to: '/' + id: keyof RouteModuleRoutesById + fileRoutesById: RouteModuleRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + FixtureCatalogModuleRoute: typeof FixtureCatalogModuleRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + FixtureCatalogModuleRoute: FixtureCatalogModuleRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/packages/router-generator/tests/route-modules/host-params/routeContract.snapshot.ts b/packages/router-generator/tests/route-modules/host-params/routeContract.snapshot.ts new file mode 100644 index 0000000000..76c34bba48 --- /dev/null +++ b/packages/router-generator/tests/route-modules/host-params/routeContract.snapshot.ts @@ -0,0 +1,49 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import type { RouteModuleRouter } from './routeScope.gen' +import type { + FileRoutesById, + MountedModuleHostParams, + routeTree, +} from './routeTree.gen' +import type { + InstalledHostParams as FixtureCatalogInstalledHostParams, + InstalledRoutesById as FixtureCatalogInstalledRoutesById, + InstalledRouters as FixtureCatalogInstalledRouters, +} from '@fixture/catalog/route-types' + +/** The route tree of "@fixture/shop": its module root with all its routes. */ +export type RouteModuleTree = typeof routeTree + +/** The router type of "@fixture/shop" (module-local paths, qualified ids). */ +export type Router = RouteModuleRouter + +/** The routes of "@fixture/shop" by qualified id, without other modules. */ +export type OwnRoutesById = FileRoutesById + +/** All routes installed with "@fixture/shop", including the modules it mounts. */ +export interface InstalledRoutesById + extends FileRoutesById, FixtureCatalogInstalledRoutesById {} + +/** The routers of "@fixture/shop" and of every module it mounts, by module id. */ +export interface InstalledRouters extends Omit< + FixtureCatalogInstalledRouters, + '@fixture/catalog' +> { + '@fixture/shop': Router + '@fixture/catalog': FixtureCatalogInstalledRouters['@fixture/catalog'] +} + +/** + * The path params above every module "@fixture/shop" installs, relative to its + * root. Packages that mount "@fixture/shop" under path params add their own. + */ +export interface InstalledHostParams { + '@fixture/catalog': MountedModuleHostParams['@fixture/catalog'] +} diff --git a/packages/router-generator/tests/route-modules/host-params/routeScope.catalog.snapshot.ts b/packages/router-generator/tests/route-modules/host-params/routeScope.catalog.snapshot.ts new file mode 100644 index 0000000000..643d0d3271 --- /dev/null +++ b/packages/router-generator/tests/route-modules/host-params/routeScope.catalog.snapshot.ts @@ -0,0 +1,218 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import type { ScopedRouter, HostedRouter } from '@tanstack/react-router' + +import type { Router as FixtureCatalogRouter } from '@fixture/catalog/route-types' + +import type { MountedModuleHostParams } from './routeTree.gen' + +type Router = ScopedRouter< + HostedRouter< + FixtureCatalogRouter, + MountedModuleHostParams['@fixture/catalog'] + >, + '@fixture/catalog' +> + +import { + bindRouteScopeLink, + bindRouteScopeCreateLink, + bindRouteScopeLinkOptions, + bindRouteScopeNavigate, + bindRouteScopeUseNavigate, + bindRouteScopeRedirect, + bindRouteScopeMatchRoute, + bindRouteScopeUseMatchRoute, + bindRouteScopeUseRouter, + bindRouteScopeGetRouteApi, + bindRouteScopeUseMatch, + bindRouteScopeUseMatches, + bindRouteScopeUseParentMatches, + bindRouteScopeUseChildMatches, + bindRouteScopeUseLoaderData, + bindRouteScopeUseLoaderDeps, + bindRouteScopeUseSearch, + bindRouteScopeUseParams, + bindRouteScopeUseRouteContext, + bindRouteScopeUseLocation, + bindRouteScopeUseRouterState, + bindRouteScopeUseLinkProps, + bindRouteScopeUseBlocker, + bindRouteScopeNotFound, +} from '@tanstack/react-router/_internal/route-module' + +import type { RouteScope } from '@tanstack/react-router' + +export const Link: RouteScope['Link'] = + /* @__PURE__ */ bindRouteScopeLink('@fixture/catalog') + +export const createLink: RouteScope['createLink'] = + /* @__PURE__ */ bindRouteScopeCreateLink('@fixture/catalog') + +export const linkOptions: RouteScope['linkOptions'] = + /* @__PURE__ */ bindRouteScopeLinkOptions('@fixture/catalog') + +export const Navigate: RouteScope['Navigate'] = + /* @__PURE__ */ bindRouteScopeNavigate('@fixture/catalog') + +export const useNavigate: RouteScope['useNavigate'] = + /* @__PURE__ */ bindRouteScopeUseNavigate('@fixture/catalog') + +export const redirect: RouteScope['redirect'] = + /* @__PURE__ */ bindRouteScopeRedirect('@fixture/catalog') + +export const MatchRoute: RouteScope['MatchRoute'] = + /* @__PURE__ */ bindRouteScopeMatchRoute('@fixture/catalog') + +export const useMatchRoute: RouteScope['useMatchRoute'] = + /* @__PURE__ */ bindRouteScopeUseMatchRoute('@fixture/catalog') + +export const useRouter: RouteScope['useRouter'] = + /* @__PURE__ */ bindRouteScopeUseRouter('@fixture/catalog') + +export const getRouteApi: RouteScope['getRouteApi'] = + /* @__PURE__ */ bindRouteScopeGetRouteApi('@fixture/catalog') + +export const useMatch: RouteScope['useMatch'] = + /* @__PURE__ */ bindRouteScopeUseMatch('@fixture/catalog') + +export const useMatches: RouteScope['useMatches'] = + /* @__PURE__ */ bindRouteScopeUseMatches('@fixture/catalog') + +export const useParentMatches: RouteScope['useParentMatches'] = + /* @__PURE__ */ bindRouteScopeUseParentMatches('@fixture/catalog') + +export const useChildMatches: RouteScope['useChildMatches'] = + /* @__PURE__ */ bindRouteScopeUseChildMatches('@fixture/catalog') + +export const useLoaderData: RouteScope['useLoaderData'] = + /* @__PURE__ */ bindRouteScopeUseLoaderData('@fixture/catalog') + +export const useLoaderDeps: RouteScope['useLoaderDeps'] = + /* @__PURE__ */ bindRouteScopeUseLoaderDeps('@fixture/catalog') + +export const useSearch: RouteScope['useSearch'] = + /* @__PURE__ */ bindRouteScopeUseSearch('@fixture/catalog') + +export const useParams: RouteScope['useParams'] = + /* @__PURE__ */ bindRouteScopeUseParams('@fixture/catalog') + +export const useRouteContext: RouteScope['useRouteContext'] = + /* @__PURE__ */ bindRouteScopeUseRouteContext('@fixture/catalog') + +export const useLocation: RouteScope['useLocation'] = + /* @__PURE__ */ bindRouteScopeUseLocation('@fixture/catalog') + +export const useRouterState: RouteScope['useRouterState'] = + /* @__PURE__ */ bindRouteScopeUseRouterState('@fixture/catalog') + +export const useLinkProps: RouteScope['useLinkProps'] = + /* @__PURE__ */ bindRouteScopeUseLinkProps('@fixture/catalog') + +export const useBlocker: RouteScope['useBlocker'] = + /* @__PURE__ */ bindRouteScopeUseBlocker('@fixture/catalog') + +export const notFound: RouteScope['notFound'] = + /* @__PURE__ */ bindRouteScopeNotFound('@fixture/catalog') + +import type { + ValidateLinkOptions as RouterValidateLinkOptions, + ValidateLinkOptionsArray as RouterValidateLinkOptionsArray, + ValidateNavigateOptions as RouterValidateNavigateOptions, + ValidateNavigateOptionsArray as RouterValidateNavigateOptionsArray, + ValidateRedirectOptions as RouterValidateRedirectOptions, + ValidateRedirectOptionsArray as RouterValidateRedirectOptionsArray, + ValidateFromPath as RouterValidateFromPath, + ValidateToPath as RouterValidateToPath, + ValidateSearch as RouterValidateSearch, + ValidateParams as RouterValidateParams, + ValidateId as RouterValidateId, + ValidateUseSearchOptions as RouterValidateUseSearchOptions, + ValidateUseParamsOptions as RouterValidateUseParamsOptions, +} from '@tanstack/react-router' + +export type ValidateLinkOptions< + TOptions = unknown, + TDefaultFrom extends string = string, + TComp = 'a', +> = RouterValidateLinkOptions + +export type ValidateLinkOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, + TComp = 'a', +> = RouterValidateLinkOptionsArray + +export type ValidateNavigateOptions< + TOptions = unknown, + TDefaultFrom extends string = string, +> = RouterValidateNavigateOptions + +export type ValidateNavigateOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, +> = RouterValidateNavigateOptionsArray + +export type ValidateRedirectOptions< + TOptions = unknown, + TDefaultFrom extends string = string, +> = RouterValidateRedirectOptions + +export type ValidateRedirectOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, +> = RouterValidateRedirectOptionsArray + +export type ValidateFromPath = RouterValidateFromPath< + Router, + TFrom +> + +export type ValidateToPath< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateToPath + +export type ValidateSearch< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateSearch + +export type ValidateParams< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateParams + +export type ValidateId = RouterValidateId< + Router, + TId +> + +export type ValidateUseSearchOptions = RouterValidateUseSearchOptions< + TOptions, + Router +> + +export type ValidateUseParamsOptions = RouterValidateUseParamsOptions< + TOptions, + Router +> + +import type { + AnyRouteMatch, + KnownRouteMatchUnion, +} from '@tanstack/react-router' + +/** Narrows a full router match to the routes installed in this scope. */ +export function isScopedMatch( + match: AnyRouteMatch, +): match is KnownRouteMatchUnion { + const localRouteId = match.localRouteId ?? '' + return localRouteId.startsWith('@fixture/catalog:') +} diff --git a/packages/router-generator/tests/route-modules/host-params/routeScope.snapshot.ts b/packages/router-generator/tests/route-modules/host-params/routeScope.snapshot.ts new file mode 100644 index 0000000000..aeff85d0a5 --- /dev/null +++ b/packages/router-generator/tests/route-modules/host-params/routeScope.snapshot.ts @@ -0,0 +1,261 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { bindCreateModuleRoot } from '@tanstack/react-router/_internal/route-module' + +import { createFileRoute as createFrameworkFileRoute } from '@tanstack/react-router' + +import type { ScopeRouter, FileRouteScope } from '@tanstack/react-router' + +import type { FileRoutesByPath, routeTree } from './routeTree.gen' + +export type RouteModuleRouter = ScopeRouter + +export interface RouteModuleRegister { + router: RouteModuleRouter +} + +export const createFileRoute = createFrameworkFileRoute as FileRouteScope< + FileRoutesByPath, + RouteModuleRegister, + '@fixture/shop' +>['createFileRoute'] + +export const createModuleRoot = /* @__PURE__ */ bindCreateModuleRoot< + RouteModuleRegister, + '@fixture/shop' +>('@fixture/shop') + +import { + bindRouteScopeLink, + bindRouteScopeCreateLink, + bindRouteScopeLinkOptions, + bindRouteScopeNavigate, + bindRouteScopeUseNavigate, + bindRouteScopeRedirect, + bindRouteScopeMatchRoute, + bindRouteScopeUseMatchRoute, + bindRouteScopeUseRouter, + bindRouteScopeGetRouteApi, + bindRouteScopeUseMatch, + bindRouteScopeUseMatches, + bindRouteScopeUseParentMatches, + bindRouteScopeUseChildMatches, + bindRouteScopeUseLoaderData, + bindRouteScopeUseLoaderDeps, + bindRouteScopeUseSearch, + bindRouteScopeUseParams, + bindRouteScopeUseRouteContext, + bindRouteScopeUseLocation, + bindRouteScopeUseRouterState, + bindRouteScopeUseLinkProps, + bindRouteScopeUseBlocker, + bindRouteScopeNotFound, +} from '@tanstack/react-router/_internal/route-module' + +import type { RouteScope } from '@tanstack/react-router' + +export const Link: RouteScope['Link'] = + /* @__PURE__ */ bindRouteScopeLink('@fixture/shop') + +export const createLink: RouteScope['createLink'] = + /* @__PURE__ */ bindRouteScopeCreateLink('@fixture/shop') + +export const linkOptions: RouteScope['linkOptions'] = + /* @__PURE__ */ bindRouteScopeLinkOptions('@fixture/shop') + +export const Navigate: RouteScope['Navigate'] = + /* @__PURE__ */ bindRouteScopeNavigate('@fixture/shop') + +export const useNavigate: RouteScope['useNavigate'] = + /* @__PURE__ */ bindRouteScopeUseNavigate('@fixture/shop') + +export const redirect: RouteScope['redirect'] = + /* @__PURE__ */ bindRouteScopeRedirect('@fixture/shop') + +export const MatchRoute: RouteScope['MatchRoute'] = + /* @__PURE__ */ bindRouteScopeMatchRoute('@fixture/shop') + +export const useMatchRoute: RouteScope['useMatchRoute'] = + /* @__PURE__ */ bindRouteScopeUseMatchRoute( + '@fixture/shop', + ) + +export const useRouter: RouteScope['useRouter'] = + /* @__PURE__ */ bindRouteScopeUseRouter('@fixture/shop') + +export const getRouteApi: RouteScope['getRouteApi'] = + /* @__PURE__ */ bindRouteScopeGetRouteApi('@fixture/shop') + +export const useMatch: RouteScope['useMatch'] = + /* @__PURE__ */ bindRouteScopeUseMatch('@fixture/shop') + +export const useMatches: RouteScope['useMatches'] = + /* @__PURE__ */ bindRouteScopeUseMatches('@fixture/shop') + +export const useParentMatches: RouteScope['useParentMatches'] = + /* @__PURE__ */ bindRouteScopeUseParentMatches( + '@fixture/shop', + ) + +export const useChildMatches: RouteScope['useChildMatches'] = + /* @__PURE__ */ bindRouteScopeUseChildMatches( + '@fixture/shop', + ) + +export const useLoaderData: RouteScope['useLoaderData'] = + /* @__PURE__ */ bindRouteScopeUseLoaderData( + '@fixture/shop', + ) + +export const useLoaderDeps: RouteScope['useLoaderDeps'] = + /* @__PURE__ */ bindRouteScopeUseLoaderDeps( + '@fixture/shop', + ) + +export const useSearch: RouteScope['useSearch'] = + /* @__PURE__ */ bindRouteScopeUseSearch('@fixture/shop') + +export const useParams: RouteScope['useParams'] = + /* @__PURE__ */ bindRouteScopeUseParams('@fixture/shop') + +export const useRouteContext: RouteScope['useRouteContext'] = + /* @__PURE__ */ bindRouteScopeUseRouteContext( + '@fixture/shop', + ) + +export const useLocation: RouteScope['useLocation'] = + /* @__PURE__ */ bindRouteScopeUseLocation('@fixture/shop') + +export const useRouterState: RouteScope['useRouterState'] = + /* @__PURE__ */ bindRouteScopeUseRouterState( + '@fixture/shop', + ) + +export const useLinkProps: RouteScope['useLinkProps'] = + /* @__PURE__ */ bindRouteScopeUseLinkProps('@fixture/shop') + +export const useBlocker: RouteScope['useBlocker'] = + /* @__PURE__ */ bindRouteScopeUseBlocker('@fixture/shop') + +export const notFound: RouteScope['notFound'] = + /* @__PURE__ */ bindRouteScopeNotFound('@fixture/shop') + +import type { + ValidateLinkOptions as RouterValidateLinkOptions, + ValidateLinkOptionsArray as RouterValidateLinkOptionsArray, + ValidateNavigateOptions as RouterValidateNavigateOptions, + ValidateNavigateOptionsArray as RouterValidateNavigateOptionsArray, + ValidateRedirectOptions as RouterValidateRedirectOptions, + ValidateRedirectOptionsArray as RouterValidateRedirectOptionsArray, + ValidateFromPath as RouterValidateFromPath, + ValidateToPath as RouterValidateToPath, + ValidateSearch as RouterValidateSearch, + ValidateParams as RouterValidateParams, + ValidateId as RouterValidateId, + ValidateUseSearchOptions as RouterValidateUseSearchOptions, + ValidateUseParamsOptions as RouterValidateUseParamsOptions, +} from '@tanstack/react-router' + +export type ValidateLinkOptions< + TOptions = unknown, + TDefaultFrom extends string = string, + TComp = 'a', +> = RouterValidateLinkOptions + +export type ValidateLinkOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, + TComp = 'a', +> = RouterValidateLinkOptionsArray< + RouteModuleRouter, + TOptions, + TDefaultFrom, + TComp +> + +export type ValidateNavigateOptions< + TOptions = unknown, + TDefaultFrom extends string = string, +> = RouterValidateNavigateOptions + +export type ValidateNavigateOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, +> = RouterValidateNavigateOptionsArray< + RouteModuleRouter, + TOptions, + TDefaultFrom +> + +export type ValidateRedirectOptions< + TOptions = unknown, + TDefaultFrom extends string = string, +> = RouterValidateRedirectOptions + +export type ValidateRedirectOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, +> = RouterValidateRedirectOptionsArray< + RouteModuleRouter, + TOptions, + TDefaultFrom +> + +export type ValidateFromPath = RouterValidateFromPath< + RouteModuleRouter, + TFrom +> + +export type ValidateToPath< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateToPath + +export type ValidateSearch< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateSearch + +export type ValidateParams< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateParams + +export type ValidateId = RouterValidateId< + RouteModuleRouter, + TId +> + +export type ValidateUseSearchOptions = RouterValidateUseSearchOptions< + TOptions, + RouteModuleRouter +> + +export type ValidateUseParamsOptions = RouterValidateUseParamsOptions< + TOptions, + RouteModuleRouter +> + +import type { + AnyRouteMatch, + KnownRouteMatchUnion, +} from '@tanstack/react-router' + +/** Narrows a full router match to the routes installed in this scope. */ +export function isScopedMatch( + match: AnyRouteMatch, +): match is KnownRouteMatchUnion { + const localRouteId = match.localRouteId ?? '' + return ( + localRouteId.startsWith('@fixture/shop:') || + localRouteId.startsWith('@fixture/catalog:') + ) +} + +export * as catalog from './routeScope.gen.namespace0' diff --git a/packages/router-generator/tests/route-modules/host-params/routeTree.snapshot.ts b/packages/router-generator/tests/route-modules/host-params/routeTree.snapshot.ts new file mode 100644 index 0000000000..f1f5e14918 --- /dev/null +++ b/packages/router-generator/tests/route-modules/host-params/routeTree.snapshot.ts @@ -0,0 +1,103 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { mountRouteModule } from '@tanstack/react-router/_internal/route-module' +import { routeModule as FixtureCatalogRouteModule } from '@fixture/catalog/route-module' +import type { MountedRoutesById } from '@tanstack/react-router' +import type { InstalledRoutesById as FixtureCatalogInstalledRoutesById } from '@fixture/catalog/route-types' + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as OrgsOrgIdRouteImport } from './routes/orgs.$orgId' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const OrgsOrgIdRoute = OrgsOrgIdRouteImport.update({ + id: '/orgs/$orgId', + path: '/orgs/$orgId', + getParentRoute: () => rootRouteImport, +} as any) + +const FixtureCatalogModuleRoute: typeof FixtureCatalogRouteModule = + mountRouteModule(FixtureCatalogRouteModule, { + parent: () => OrgsOrgIdRoute, + at: '/catalog', + }) + +/** The path params of the routes above each mounted route module. */ +export interface MountedModuleHostParams { + '@fixture/catalog': (typeof OrgsOrgIdRoute)['types']['allParams'] +} + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/orgs/$orgId': typeof OrgsOrgIdRouteWithChildren +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/orgs/$orgId': typeof OrgsOrgIdRouteWithChildren +} +export interface FileRoutesById { + '@fixture/shop:': typeof rootRouteImport + '@fixture/shop:/': typeof IndexRoute + '@fixture/shop:/orgs/$orgId': typeof OrgsOrgIdRouteWithChildren +} +interface RouteModuleRoutesById + extends + FileRoutesById, + MountedRoutesById {} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/orgs/$orgId' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/orgs/$orgId' + id: keyof RouteModuleRoutesById + fileRoutesById: RouteModuleRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + OrgsOrgIdRoute: typeof OrgsOrgIdRouteWithChildren +} + +export interface FileRoutesByPath { + '@fixture/shop:/': { + id: '@fixture/shop:/' + path: '/' + fullPath: '/' + parentRoute: typeof rootRouteImport + } + '@fixture/shop:/orgs/$orgId': { + id: '@fixture/shop:/orgs/$orgId' + path: '/orgs/$orgId' + fullPath: '/orgs/$orgId' + parentRoute: typeof rootRouteImport + } +} + +interface OrgsOrgIdRouteChildren { + FixtureCatalogModuleRoute: typeof FixtureCatalogModuleRoute +} + +const OrgsOrgIdRouteChildren: OrgsOrgIdRouteChildren = { + FixtureCatalogModuleRoute: FixtureCatalogModuleRoute, +} + +const OrgsOrgIdRouteWithChildren = OrgsOrgIdRoute._addFileChildren( + OrgsOrgIdRouteChildren, +) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + OrgsOrgIdRoute: OrgsOrgIdRouteWithChildren, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/packages/router-generator/tests/route-modules/includer/routeContract.snapshot.ts b/packages/router-generator/tests/route-modules/includer/routeContract.snapshot.ts new file mode 100644 index 0000000000..76c34bba48 --- /dev/null +++ b/packages/router-generator/tests/route-modules/includer/routeContract.snapshot.ts @@ -0,0 +1,49 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import type { RouteModuleRouter } from './routeScope.gen' +import type { + FileRoutesById, + MountedModuleHostParams, + routeTree, +} from './routeTree.gen' +import type { + InstalledHostParams as FixtureCatalogInstalledHostParams, + InstalledRoutesById as FixtureCatalogInstalledRoutesById, + InstalledRouters as FixtureCatalogInstalledRouters, +} from '@fixture/catalog/route-types' + +/** The route tree of "@fixture/shop": its module root with all its routes. */ +export type RouteModuleTree = typeof routeTree + +/** The router type of "@fixture/shop" (module-local paths, qualified ids). */ +export type Router = RouteModuleRouter + +/** The routes of "@fixture/shop" by qualified id, without other modules. */ +export type OwnRoutesById = FileRoutesById + +/** All routes installed with "@fixture/shop", including the modules it mounts. */ +export interface InstalledRoutesById + extends FileRoutesById, FixtureCatalogInstalledRoutesById {} + +/** The routers of "@fixture/shop" and of every module it mounts, by module id. */ +export interface InstalledRouters extends Omit< + FixtureCatalogInstalledRouters, + '@fixture/catalog' +> { + '@fixture/shop': Router + '@fixture/catalog': FixtureCatalogInstalledRouters['@fixture/catalog'] +} + +/** + * The path params above every module "@fixture/shop" installs, relative to its + * root. Packages that mount "@fixture/shop" under path params add their own. + */ +export interface InstalledHostParams { + '@fixture/catalog': MountedModuleHostParams['@fixture/catalog'] +} diff --git a/packages/router-generator/tests/route-modules/includer/routeScope.catalog.snapshot.ts b/packages/router-generator/tests/route-modules/includer/routeScope.catalog.snapshot.ts new file mode 100644 index 0000000000..086f9f431b --- /dev/null +++ b/packages/router-generator/tests/route-modules/includer/routeScope.catalog.snapshot.ts @@ -0,0 +1,210 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import type { ScopedRouter, HostedRouter } from '@tanstack/react-router' + +import type { Router as FixtureCatalogRouter } from '@fixture/catalog/route-types' + +type Router = ScopedRouter + +import { + bindRouteScopeLink, + bindRouteScopeCreateLink, + bindRouteScopeLinkOptions, + bindRouteScopeNavigate, + bindRouteScopeUseNavigate, + bindRouteScopeRedirect, + bindRouteScopeMatchRoute, + bindRouteScopeUseMatchRoute, + bindRouteScopeUseRouter, + bindRouteScopeGetRouteApi, + bindRouteScopeUseMatch, + bindRouteScopeUseMatches, + bindRouteScopeUseParentMatches, + bindRouteScopeUseChildMatches, + bindRouteScopeUseLoaderData, + bindRouteScopeUseLoaderDeps, + bindRouteScopeUseSearch, + bindRouteScopeUseParams, + bindRouteScopeUseRouteContext, + bindRouteScopeUseLocation, + bindRouteScopeUseRouterState, + bindRouteScopeUseLinkProps, + bindRouteScopeUseBlocker, + bindRouteScopeNotFound, +} from '@tanstack/react-router/_internal/route-module' + +import type { RouteScope } from '@tanstack/react-router' + +export const Link: RouteScope['Link'] = + /* @__PURE__ */ bindRouteScopeLink('@fixture/catalog') + +export const createLink: RouteScope['createLink'] = + /* @__PURE__ */ bindRouteScopeCreateLink('@fixture/catalog') + +export const linkOptions: RouteScope['linkOptions'] = + /* @__PURE__ */ bindRouteScopeLinkOptions('@fixture/catalog') + +export const Navigate: RouteScope['Navigate'] = + /* @__PURE__ */ bindRouteScopeNavigate('@fixture/catalog') + +export const useNavigate: RouteScope['useNavigate'] = + /* @__PURE__ */ bindRouteScopeUseNavigate('@fixture/catalog') + +export const redirect: RouteScope['redirect'] = + /* @__PURE__ */ bindRouteScopeRedirect('@fixture/catalog') + +export const MatchRoute: RouteScope['MatchRoute'] = + /* @__PURE__ */ bindRouteScopeMatchRoute('@fixture/catalog') + +export const useMatchRoute: RouteScope['useMatchRoute'] = + /* @__PURE__ */ bindRouteScopeUseMatchRoute('@fixture/catalog') + +export const useRouter: RouteScope['useRouter'] = + /* @__PURE__ */ bindRouteScopeUseRouter('@fixture/catalog') + +export const getRouteApi: RouteScope['getRouteApi'] = + /* @__PURE__ */ bindRouteScopeGetRouteApi('@fixture/catalog') + +export const useMatch: RouteScope['useMatch'] = + /* @__PURE__ */ bindRouteScopeUseMatch('@fixture/catalog') + +export const useMatches: RouteScope['useMatches'] = + /* @__PURE__ */ bindRouteScopeUseMatches('@fixture/catalog') + +export const useParentMatches: RouteScope['useParentMatches'] = + /* @__PURE__ */ bindRouteScopeUseParentMatches('@fixture/catalog') + +export const useChildMatches: RouteScope['useChildMatches'] = + /* @__PURE__ */ bindRouteScopeUseChildMatches('@fixture/catalog') + +export const useLoaderData: RouteScope['useLoaderData'] = + /* @__PURE__ */ bindRouteScopeUseLoaderData('@fixture/catalog') + +export const useLoaderDeps: RouteScope['useLoaderDeps'] = + /* @__PURE__ */ bindRouteScopeUseLoaderDeps('@fixture/catalog') + +export const useSearch: RouteScope['useSearch'] = + /* @__PURE__ */ bindRouteScopeUseSearch('@fixture/catalog') + +export const useParams: RouteScope['useParams'] = + /* @__PURE__ */ bindRouteScopeUseParams('@fixture/catalog') + +export const useRouteContext: RouteScope['useRouteContext'] = + /* @__PURE__ */ bindRouteScopeUseRouteContext('@fixture/catalog') + +export const useLocation: RouteScope['useLocation'] = + /* @__PURE__ */ bindRouteScopeUseLocation('@fixture/catalog') + +export const useRouterState: RouteScope['useRouterState'] = + /* @__PURE__ */ bindRouteScopeUseRouterState('@fixture/catalog') + +export const useLinkProps: RouteScope['useLinkProps'] = + /* @__PURE__ */ bindRouteScopeUseLinkProps('@fixture/catalog') + +export const useBlocker: RouteScope['useBlocker'] = + /* @__PURE__ */ bindRouteScopeUseBlocker('@fixture/catalog') + +export const notFound: RouteScope['notFound'] = + /* @__PURE__ */ bindRouteScopeNotFound('@fixture/catalog') + +import type { + ValidateLinkOptions as RouterValidateLinkOptions, + ValidateLinkOptionsArray as RouterValidateLinkOptionsArray, + ValidateNavigateOptions as RouterValidateNavigateOptions, + ValidateNavigateOptionsArray as RouterValidateNavigateOptionsArray, + ValidateRedirectOptions as RouterValidateRedirectOptions, + ValidateRedirectOptionsArray as RouterValidateRedirectOptionsArray, + ValidateFromPath as RouterValidateFromPath, + ValidateToPath as RouterValidateToPath, + ValidateSearch as RouterValidateSearch, + ValidateParams as RouterValidateParams, + ValidateId as RouterValidateId, + ValidateUseSearchOptions as RouterValidateUseSearchOptions, + ValidateUseParamsOptions as RouterValidateUseParamsOptions, +} from '@tanstack/react-router' + +export type ValidateLinkOptions< + TOptions = unknown, + TDefaultFrom extends string = string, + TComp = 'a', +> = RouterValidateLinkOptions + +export type ValidateLinkOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, + TComp = 'a', +> = RouterValidateLinkOptionsArray + +export type ValidateNavigateOptions< + TOptions = unknown, + TDefaultFrom extends string = string, +> = RouterValidateNavigateOptions + +export type ValidateNavigateOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, +> = RouterValidateNavigateOptionsArray + +export type ValidateRedirectOptions< + TOptions = unknown, + TDefaultFrom extends string = string, +> = RouterValidateRedirectOptions + +export type ValidateRedirectOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, +> = RouterValidateRedirectOptionsArray + +export type ValidateFromPath = RouterValidateFromPath< + Router, + TFrom +> + +export type ValidateToPath< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateToPath + +export type ValidateSearch< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateSearch + +export type ValidateParams< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateParams + +export type ValidateId = RouterValidateId< + Router, + TId +> + +export type ValidateUseSearchOptions = RouterValidateUseSearchOptions< + TOptions, + Router +> + +export type ValidateUseParamsOptions = RouterValidateUseParamsOptions< + TOptions, + Router +> + +import type { + AnyRouteMatch, + KnownRouteMatchUnion, +} from '@tanstack/react-router' + +/** Narrows a full router match to the routes installed in this scope. */ +export function isScopedMatch( + match: AnyRouteMatch, +): match is KnownRouteMatchUnion { + const localRouteId = match.localRouteId ?? '' + return localRouteId.startsWith('@fixture/catalog:') +} diff --git a/packages/router-generator/tests/route-modules/includer/routeScope.snapshot.ts b/packages/router-generator/tests/route-modules/includer/routeScope.snapshot.ts new file mode 100644 index 0000000000..aeff85d0a5 --- /dev/null +++ b/packages/router-generator/tests/route-modules/includer/routeScope.snapshot.ts @@ -0,0 +1,261 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { bindCreateModuleRoot } from '@tanstack/react-router/_internal/route-module' + +import { createFileRoute as createFrameworkFileRoute } from '@tanstack/react-router' + +import type { ScopeRouter, FileRouteScope } from '@tanstack/react-router' + +import type { FileRoutesByPath, routeTree } from './routeTree.gen' + +export type RouteModuleRouter = ScopeRouter + +export interface RouteModuleRegister { + router: RouteModuleRouter +} + +export const createFileRoute = createFrameworkFileRoute as FileRouteScope< + FileRoutesByPath, + RouteModuleRegister, + '@fixture/shop' +>['createFileRoute'] + +export const createModuleRoot = /* @__PURE__ */ bindCreateModuleRoot< + RouteModuleRegister, + '@fixture/shop' +>('@fixture/shop') + +import { + bindRouteScopeLink, + bindRouteScopeCreateLink, + bindRouteScopeLinkOptions, + bindRouteScopeNavigate, + bindRouteScopeUseNavigate, + bindRouteScopeRedirect, + bindRouteScopeMatchRoute, + bindRouteScopeUseMatchRoute, + bindRouteScopeUseRouter, + bindRouteScopeGetRouteApi, + bindRouteScopeUseMatch, + bindRouteScopeUseMatches, + bindRouteScopeUseParentMatches, + bindRouteScopeUseChildMatches, + bindRouteScopeUseLoaderData, + bindRouteScopeUseLoaderDeps, + bindRouteScopeUseSearch, + bindRouteScopeUseParams, + bindRouteScopeUseRouteContext, + bindRouteScopeUseLocation, + bindRouteScopeUseRouterState, + bindRouteScopeUseLinkProps, + bindRouteScopeUseBlocker, + bindRouteScopeNotFound, +} from '@tanstack/react-router/_internal/route-module' + +import type { RouteScope } from '@tanstack/react-router' + +export const Link: RouteScope['Link'] = + /* @__PURE__ */ bindRouteScopeLink('@fixture/shop') + +export const createLink: RouteScope['createLink'] = + /* @__PURE__ */ bindRouteScopeCreateLink('@fixture/shop') + +export const linkOptions: RouteScope['linkOptions'] = + /* @__PURE__ */ bindRouteScopeLinkOptions('@fixture/shop') + +export const Navigate: RouteScope['Navigate'] = + /* @__PURE__ */ bindRouteScopeNavigate('@fixture/shop') + +export const useNavigate: RouteScope['useNavigate'] = + /* @__PURE__ */ bindRouteScopeUseNavigate('@fixture/shop') + +export const redirect: RouteScope['redirect'] = + /* @__PURE__ */ bindRouteScopeRedirect('@fixture/shop') + +export const MatchRoute: RouteScope['MatchRoute'] = + /* @__PURE__ */ bindRouteScopeMatchRoute('@fixture/shop') + +export const useMatchRoute: RouteScope['useMatchRoute'] = + /* @__PURE__ */ bindRouteScopeUseMatchRoute( + '@fixture/shop', + ) + +export const useRouter: RouteScope['useRouter'] = + /* @__PURE__ */ bindRouteScopeUseRouter('@fixture/shop') + +export const getRouteApi: RouteScope['getRouteApi'] = + /* @__PURE__ */ bindRouteScopeGetRouteApi('@fixture/shop') + +export const useMatch: RouteScope['useMatch'] = + /* @__PURE__ */ bindRouteScopeUseMatch('@fixture/shop') + +export const useMatches: RouteScope['useMatches'] = + /* @__PURE__ */ bindRouteScopeUseMatches('@fixture/shop') + +export const useParentMatches: RouteScope['useParentMatches'] = + /* @__PURE__ */ bindRouteScopeUseParentMatches( + '@fixture/shop', + ) + +export const useChildMatches: RouteScope['useChildMatches'] = + /* @__PURE__ */ bindRouteScopeUseChildMatches( + '@fixture/shop', + ) + +export const useLoaderData: RouteScope['useLoaderData'] = + /* @__PURE__ */ bindRouteScopeUseLoaderData( + '@fixture/shop', + ) + +export const useLoaderDeps: RouteScope['useLoaderDeps'] = + /* @__PURE__ */ bindRouteScopeUseLoaderDeps( + '@fixture/shop', + ) + +export const useSearch: RouteScope['useSearch'] = + /* @__PURE__ */ bindRouteScopeUseSearch('@fixture/shop') + +export const useParams: RouteScope['useParams'] = + /* @__PURE__ */ bindRouteScopeUseParams('@fixture/shop') + +export const useRouteContext: RouteScope['useRouteContext'] = + /* @__PURE__ */ bindRouteScopeUseRouteContext( + '@fixture/shop', + ) + +export const useLocation: RouteScope['useLocation'] = + /* @__PURE__ */ bindRouteScopeUseLocation('@fixture/shop') + +export const useRouterState: RouteScope['useRouterState'] = + /* @__PURE__ */ bindRouteScopeUseRouterState( + '@fixture/shop', + ) + +export const useLinkProps: RouteScope['useLinkProps'] = + /* @__PURE__ */ bindRouteScopeUseLinkProps('@fixture/shop') + +export const useBlocker: RouteScope['useBlocker'] = + /* @__PURE__ */ bindRouteScopeUseBlocker('@fixture/shop') + +export const notFound: RouteScope['notFound'] = + /* @__PURE__ */ bindRouteScopeNotFound('@fixture/shop') + +import type { + ValidateLinkOptions as RouterValidateLinkOptions, + ValidateLinkOptionsArray as RouterValidateLinkOptionsArray, + ValidateNavigateOptions as RouterValidateNavigateOptions, + ValidateNavigateOptionsArray as RouterValidateNavigateOptionsArray, + ValidateRedirectOptions as RouterValidateRedirectOptions, + ValidateRedirectOptionsArray as RouterValidateRedirectOptionsArray, + ValidateFromPath as RouterValidateFromPath, + ValidateToPath as RouterValidateToPath, + ValidateSearch as RouterValidateSearch, + ValidateParams as RouterValidateParams, + ValidateId as RouterValidateId, + ValidateUseSearchOptions as RouterValidateUseSearchOptions, + ValidateUseParamsOptions as RouterValidateUseParamsOptions, +} from '@tanstack/react-router' + +export type ValidateLinkOptions< + TOptions = unknown, + TDefaultFrom extends string = string, + TComp = 'a', +> = RouterValidateLinkOptions + +export type ValidateLinkOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, + TComp = 'a', +> = RouterValidateLinkOptionsArray< + RouteModuleRouter, + TOptions, + TDefaultFrom, + TComp +> + +export type ValidateNavigateOptions< + TOptions = unknown, + TDefaultFrom extends string = string, +> = RouterValidateNavigateOptions + +export type ValidateNavigateOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, +> = RouterValidateNavigateOptionsArray< + RouteModuleRouter, + TOptions, + TDefaultFrom +> + +export type ValidateRedirectOptions< + TOptions = unknown, + TDefaultFrom extends string = string, +> = RouterValidateRedirectOptions + +export type ValidateRedirectOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, +> = RouterValidateRedirectOptionsArray< + RouteModuleRouter, + TOptions, + TDefaultFrom +> + +export type ValidateFromPath = RouterValidateFromPath< + RouteModuleRouter, + TFrom +> + +export type ValidateToPath< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateToPath + +export type ValidateSearch< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateSearch + +export type ValidateParams< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateParams + +export type ValidateId = RouterValidateId< + RouteModuleRouter, + TId +> + +export type ValidateUseSearchOptions = RouterValidateUseSearchOptions< + TOptions, + RouteModuleRouter +> + +export type ValidateUseParamsOptions = RouterValidateUseParamsOptions< + TOptions, + RouteModuleRouter +> + +import type { + AnyRouteMatch, + KnownRouteMatchUnion, +} from '@tanstack/react-router' + +/** Narrows a full router match to the routes installed in this scope. */ +export function isScopedMatch( + match: AnyRouteMatch, +): match is KnownRouteMatchUnion { + const localRouteId = match.localRouteId ?? '' + return ( + localRouteId.startsWith('@fixture/shop:') || + localRouteId.startsWith('@fixture/catalog:') + ) +} + +export * as catalog from './routeScope.gen.namespace0' diff --git a/packages/router-generator/tests/route-modules/includer/routeTree.snapshot.ts b/packages/router-generator/tests/route-modules/includer/routeTree.snapshot.ts new file mode 100644 index 0000000000..d02ea20b3e --- /dev/null +++ b/packages/router-generator/tests/route-modules/includer/routeTree.snapshot.ts @@ -0,0 +1,99 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { mountRouteModule } from '@tanstack/react-router/_internal/route-module' +import { routeModule as FixtureCatalogRouteModule } from '@fixture/catalog/route-module' +import type { MountedRoutesById } from '@tanstack/react-router' +import type { InstalledRoutesById as FixtureCatalogInstalledRoutesById } from '@fixture/catalog/route-types' + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as LayoutRouteImport } from './routes/_layout' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) + +const FixtureCatalogModuleRoute: typeof FixtureCatalogRouteModule = + mountRouteModule(FixtureCatalogRouteModule, { + parent: () => LayoutRoute, + at: '/c', + }) + +/** The path params of the routes above each mounted route module. */ +export interface MountedModuleHostParams { + '@fixture/catalog': (typeof LayoutRoute)['types']['allParams'] +} + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute +} +export interface FileRoutesById { + '@fixture/shop:': typeof rootRouteImport + '@fixture/shop:/': typeof IndexRoute + '@fixture/shop:/_layout': typeof LayoutRouteWithChildren +} +interface RouteModuleRoutesById + extends + FileRoutesById, + MountedRoutesById {} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' + fileRoutesByTo: FileRoutesByTo + to: '/' + id: keyof RouteModuleRoutesById + fileRoutesById: RouteModuleRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + LayoutRoute: typeof LayoutRouteWithChildren +} + +export interface FileRoutesByPath { + '@fixture/shop:/': { + id: '@fixture/shop:/' + path: '/' + fullPath: '/' + parentRoute: typeof rootRouteImport + } + '@fixture/shop:/_layout': { + id: '@fixture/shop:/_layout' + path: '' + fullPath: '/' + parentRoute: typeof rootRouteImport + } +} + +interface LayoutRouteChildren { + FixtureCatalogModuleRoute: typeof FixtureCatalogModuleRoute +} + +const LayoutRouteChildren: LayoutRouteChildren = { + FixtureCatalogModuleRoute: FixtureCatalogModuleRoute, +} + +const LayoutRouteWithChildren = + LayoutRoute._addFileChildren(LayoutRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + LayoutRoute: LayoutRouteWithChildren, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/packages/router-generator/tests/route-modules/installations/routeScope.account.snapshot.ts b/packages/router-generator/tests/route-modules/installations/routeScope.account.snapshot.ts new file mode 100644 index 0000000000..9cd3f2cbf9 --- /dev/null +++ b/packages/router-generator/tests/route-modules/installations/routeScope.account.snapshot.ts @@ -0,0 +1,218 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import type { ScopedRouter, HostedRouter } from '@tanstack/react-router' + +import type { Router as FixtureAccountRouter } from '@fixture/account/route-types' + +import type { MountedModuleHostParams } from './routeTree.gen' + +type Router = ScopedRouter< + HostedRouter< + FixtureAccountRouter, + MountedModuleHostParams['@fixture/account'] + >, + '@fixture/account' +> + +import { + bindRouteScopeLink, + bindRouteScopeCreateLink, + bindRouteScopeLinkOptions, + bindRouteScopeNavigate, + bindRouteScopeUseNavigate, + bindRouteScopeRedirect, + bindRouteScopeMatchRoute, + bindRouteScopeUseMatchRoute, + bindRouteScopeUseRouter, + bindRouteScopeGetRouteApi, + bindRouteScopeUseMatch, + bindRouteScopeUseMatches, + bindRouteScopeUseParentMatches, + bindRouteScopeUseChildMatches, + bindRouteScopeUseLoaderData, + bindRouteScopeUseLoaderDeps, + bindRouteScopeUseSearch, + bindRouteScopeUseParams, + bindRouteScopeUseRouteContext, + bindRouteScopeUseLocation, + bindRouteScopeUseRouterState, + bindRouteScopeUseLinkProps, + bindRouteScopeUseBlocker, + bindRouteScopeNotFound, +} from '@tanstack/react-router/_internal/route-module' + +import type { RouteScope } from '@tanstack/react-router' + +export const Link: RouteScope['Link'] = + /* @__PURE__ */ bindRouteScopeLink('@fixture/account') + +export const createLink: RouteScope['createLink'] = + /* @__PURE__ */ bindRouteScopeCreateLink('@fixture/account') + +export const linkOptions: RouteScope['linkOptions'] = + /* @__PURE__ */ bindRouteScopeLinkOptions('@fixture/account') + +export const Navigate: RouteScope['Navigate'] = + /* @__PURE__ */ bindRouteScopeNavigate('@fixture/account') + +export const useNavigate: RouteScope['useNavigate'] = + /* @__PURE__ */ bindRouteScopeUseNavigate('@fixture/account') + +export const redirect: RouteScope['redirect'] = + /* @__PURE__ */ bindRouteScopeRedirect('@fixture/account') + +export const MatchRoute: RouteScope['MatchRoute'] = + /* @__PURE__ */ bindRouteScopeMatchRoute('@fixture/account') + +export const useMatchRoute: RouteScope['useMatchRoute'] = + /* @__PURE__ */ bindRouteScopeUseMatchRoute('@fixture/account') + +export const useRouter: RouteScope['useRouter'] = + /* @__PURE__ */ bindRouteScopeUseRouter('@fixture/account') + +export const getRouteApi: RouteScope['getRouteApi'] = + /* @__PURE__ */ bindRouteScopeGetRouteApi('@fixture/account') + +export const useMatch: RouteScope['useMatch'] = + /* @__PURE__ */ bindRouteScopeUseMatch('@fixture/account') + +export const useMatches: RouteScope['useMatches'] = + /* @__PURE__ */ bindRouteScopeUseMatches('@fixture/account') + +export const useParentMatches: RouteScope['useParentMatches'] = + /* @__PURE__ */ bindRouteScopeUseParentMatches('@fixture/account') + +export const useChildMatches: RouteScope['useChildMatches'] = + /* @__PURE__ */ bindRouteScopeUseChildMatches('@fixture/account') + +export const useLoaderData: RouteScope['useLoaderData'] = + /* @__PURE__ */ bindRouteScopeUseLoaderData('@fixture/account') + +export const useLoaderDeps: RouteScope['useLoaderDeps'] = + /* @__PURE__ */ bindRouteScopeUseLoaderDeps('@fixture/account') + +export const useSearch: RouteScope['useSearch'] = + /* @__PURE__ */ bindRouteScopeUseSearch('@fixture/account') + +export const useParams: RouteScope['useParams'] = + /* @__PURE__ */ bindRouteScopeUseParams('@fixture/account') + +export const useRouteContext: RouteScope['useRouteContext'] = + /* @__PURE__ */ bindRouteScopeUseRouteContext('@fixture/account') + +export const useLocation: RouteScope['useLocation'] = + /* @__PURE__ */ bindRouteScopeUseLocation('@fixture/account') + +export const useRouterState: RouteScope['useRouterState'] = + /* @__PURE__ */ bindRouteScopeUseRouterState('@fixture/account') + +export const useLinkProps: RouteScope['useLinkProps'] = + /* @__PURE__ */ bindRouteScopeUseLinkProps('@fixture/account') + +export const useBlocker: RouteScope['useBlocker'] = + /* @__PURE__ */ bindRouteScopeUseBlocker('@fixture/account') + +export const notFound: RouteScope['notFound'] = + /* @__PURE__ */ bindRouteScopeNotFound('@fixture/account') + +import type { + ValidateLinkOptions as RouterValidateLinkOptions, + ValidateLinkOptionsArray as RouterValidateLinkOptionsArray, + ValidateNavigateOptions as RouterValidateNavigateOptions, + ValidateNavigateOptionsArray as RouterValidateNavigateOptionsArray, + ValidateRedirectOptions as RouterValidateRedirectOptions, + ValidateRedirectOptionsArray as RouterValidateRedirectOptionsArray, + ValidateFromPath as RouterValidateFromPath, + ValidateToPath as RouterValidateToPath, + ValidateSearch as RouterValidateSearch, + ValidateParams as RouterValidateParams, + ValidateId as RouterValidateId, + ValidateUseSearchOptions as RouterValidateUseSearchOptions, + ValidateUseParamsOptions as RouterValidateUseParamsOptions, +} from '@tanstack/react-router' + +export type ValidateLinkOptions< + TOptions = unknown, + TDefaultFrom extends string = string, + TComp = 'a', +> = RouterValidateLinkOptions + +export type ValidateLinkOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, + TComp = 'a', +> = RouterValidateLinkOptionsArray + +export type ValidateNavigateOptions< + TOptions = unknown, + TDefaultFrom extends string = string, +> = RouterValidateNavigateOptions + +export type ValidateNavigateOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, +> = RouterValidateNavigateOptionsArray + +export type ValidateRedirectOptions< + TOptions = unknown, + TDefaultFrom extends string = string, +> = RouterValidateRedirectOptions + +export type ValidateRedirectOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, +> = RouterValidateRedirectOptionsArray + +export type ValidateFromPath = RouterValidateFromPath< + Router, + TFrom +> + +export type ValidateToPath< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateToPath + +export type ValidateSearch< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateSearch + +export type ValidateParams< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateParams + +export type ValidateId = RouterValidateId< + Router, + TId +> + +export type ValidateUseSearchOptions = RouterValidateUseSearchOptions< + TOptions, + Router +> + +export type ValidateUseParamsOptions = RouterValidateUseParamsOptions< + TOptions, + Router +> + +import type { + AnyRouteMatch, + KnownRouteMatchUnion, +} from '@tanstack/react-router' + +/** Narrows a full router match to the routes installed in this scope. */ +export function isScopedMatch( + match: AnyRouteMatch, +): match is KnownRouteMatchUnion { + const localRouteId = match.localRouteId ?? '' + return localRouteId.startsWith('@fixture/account:') +} diff --git a/packages/router-generator/tests/route-modules/installations/routeScope.orgCatalog.snapshot.ts b/packages/router-generator/tests/route-modules/installations/routeScope.orgCatalog.snapshot.ts new file mode 100644 index 0000000000..ea0b1a8d95 --- /dev/null +++ b/packages/router-generator/tests/route-modules/installations/routeScope.orgCatalog.snapshot.ts @@ -0,0 +1,249 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import type { ScopedRouter, HostedRouter } from '@tanstack/react-router' + +import type { Router as FixtureCatalogRouter } from '@fixture/catalog/route-types' + +import type { MountedModuleHostParams } from './routeTree.gen' + +type Router = ScopedRouter< + HostedRouter< + FixtureCatalogRouter, + MountedModuleHostParams['@fixture/catalog#orgCatalog'] + >, + '@fixture/catalog#orgCatalog' +> + +import { + bindRouteScopeLink, + bindRouteScopeCreateLink, + bindRouteScopeLinkOptions, + bindRouteScopeNavigate, + bindRouteScopeUseNavigate, + bindRouteScopeRedirect, + bindRouteScopeMatchRoute, + bindRouteScopeUseMatchRoute, + bindRouteScopeUseRouter, + bindRouteScopeGetRouteApi, + bindRouteScopeUseMatch, + bindRouteScopeUseMatches, + bindRouteScopeUseParentMatches, + bindRouteScopeUseChildMatches, + bindRouteScopeUseLoaderData, + bindRouteScopeUseLoaderDeps, + bindRouteScopeUseSearch, + bindRouteScopeUseParams, + bindRouteScopeUseRouteContext, + bindRouteScopeUseLocation, + bindRouteScopeUseRouterState, + bindRouteScopeUseLinkProps, + bindRouteScopeUseBlocker, + bindRouteScopeNotFound, +} from '@tanstack/react-router/_internal/route-module' + +import type { RouteScope } from '@tanstack/react-router' + +export const Link: RouteScope['Link'] = + /* @__PURE__ */ bindRouteScopeLink('@fixture/catalog#orgCatalog') + +export const createLink: RouteScope['createLink'] = + /* @__PURE__ */ bindRouteScopeCreateLink( + '@fixture/catalog#orgCatalog', + ) + +export const linkOptions: RouteScope['linkOptions'] = + /* @__PURE__ */ bindRouteScopeLinkOptions( + '@fixture/catalog#orgCatalog', + ) + +export const Navigate: RouteScope['Navigate'] = + /* @__PURE__ */ bindRouteScopeNavigate('@fixture/catalog#orgCatalog') + +export const useNavigate: RouteScope['useNavigate'] = + /* @__PURE__ */ bindRouteScopeUseNavigate( + '@fixture/catalog#orgCatalog', + ) + +export const redirect: RouteScope['redirect'] = + /* @__PURE__ */ bindRouteScopeRedirect('@fixture/catalog#orgCatalog') + +export const MatchRoute: RouteScope['MatchRoute'] = + /* @__PURE__ */ bindRouteScopeMatchRoute( + '@fixture/catalog#orgCatalog', + ) + +export const useMatchRoute: RouteScope['useMatchRoute'] = + /* @__PURE__ */ bindRouteScopeUseMatchRoute( + '@fixture/catalog#orgCatalog', + ) + +export const useRouter: RouteScope['useRouter'] = + /* @__PURE__ */ bindRouteScopeUseRouter('@fixture/catalog#orgCatalog') + +export const getRouteApi: RouteScope['getRouteApi'] = + /* @__PURE__ */ bindRouteScopeGetRouteApi( + '@fixture/catalog#orgCatalog', + ) + +export const useMatch: RouteScope['useMatch'] = + /* @__PURE__ */ bindRouteScopeUseMatch('@fixture/catalog#orgCatalog') + +export const useMatches: RouteScope['useMatches'] = + /* @__PURE__ */ bindRouteScopeUseMatches( + '@fixture/catalog#orgCatalog', + ) + +export const useParentMatches: RouteScope['useParentMatches'] = + /* @__PURE__ */ bindRouteScopeUseParentMatches( + '@fixture/catalog#orgCatalog', + ) + +export const useChildMatches: RouteScope['useChildMatches'] = + /* @__PURE__ */ bindRouteScopeUseChildMatches( + '@fixture/catalog#orgCatalog', + ) + +export const useLoaderData: RouteScope['useLoaderData'] = + /* @__PURE__ */ bindRouteScopeUseLoaderData( + '@fixture/catalog#orgCatalog', + ) + +export const useLoaderDeps: RouteScope['useLoaderDeps'] = + /* @__PURE__ */ bindRouteScopeUseLoaderDeps( + '@fixture/catalog#orgCatalog', + ) + +export const useSearch: RouteScope['useSearch'] = + /* @__PURE__ */ bindRouteScopeUseSearch('@fixture/catalog#orgCatalog') + +export const useParams: RouteScope['useParams'] = + /* @__PURE__ */ bindRouteScopeUseParams('@fixture/catalog#orgCatalog') + +export const useRouteContext: RouteScope['useRouteContext'] = + /* @__PURE__ */ bindRouteScopeUseRouteContext( + '@fixture/catalog#orgCatalog', + ) + +export const useLocation: RouteScope['useLocation'] = + /* @__PURE__ */ bindRouteScopeUseLocation( + '@fixture/catalog#orgCatalog', + ) + +export const useRouterState: RouteScope['useRouterState'] = + /* @__PURE__ */ bindRouteScopeUseRouterState( + '@fixture/catalog#orgCatalog', + ) + +export const useLinkProps: RouteScope['useLinkProps'] = + /* @__PURE__ */ bindRouteScopeUseLinkProps( + '@fixture/catalog#orgCatalog', + ) + +export const useBlocker: RouteScope['useBlocker'] = + /* @__PURE__ */ bindRouteScopeUseBlocker( + '@fixture/catalog#orgCatalog', + ) + +export const notFound: RouteScope['notFound'] = + /* @__PURE__ */ bindRouteScopeNotFound('@fixture/catalog#orgCatalog') + +import type { + ValidateLinkOptions as RouterValidateLinkOptions, + ValidateLinkOptionsArray as RouterValidateLinkOptionsArray, + ValidateNavigateOptions as RouterValidateNavigateOptions, + ValidateNavigateOptionsArray as RouterValidateNavigateOptionsArray, + ValidateRedirectOptions as RouterValidateRedirectOptions, + ValidateRedirectOptionsArray as RouterValidateRedirectOptionsArray, + ValidateFromPath as RouterValidateFromPath, + ValidateToPath as RouterValidateToPath, + ValidateSearch as RouterValidateSearch, + ValidateParams as RouterValidateParams, + ValidateId as RouterValidateId, + ValidateUseSearchOptions as RouterValidateUseSearchOptions, + ValidateUseParamsOptions as RouterValidateUseParamsOptions, +} from '@tanstack/react-router' + +export type ValidateLinkOptions< + TOptions = unknown, + TDefaultFrom extends string = string, + TComp = 'a', +> = RouterValidateLinkOptions + +export type ValidateLinkOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, + TComp = 'a', +> = RouterValidateLinkOptionsArray + +export type ValidateNavigateOptions< + TOptions = unknown, + TDefaultFrom extends string = string, +> = RouterValidateNavigateOptions + +export type ValidateNavigateOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, +> = RouterValidateNavigateOptionsArray + +export type ValidateRedirectOptions< + TOptions = unknown, + TDefaultFrom extends string = string, +> = RouterValidateRedirectOptions + +export type ValidateRedirectOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, +> = RouterValidateRedirectOptionsArray + +export type ValidateFromPath = RouterValidateFromPath< + Router, + TFrom +> + +export type ValidateToPath< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateToPath + +export type ValidateSearch< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateSearch + +export type ValidateParams< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateParams + +export type ValidateId = RouterValidateId< + Router, + TId +> + +export type ValidateUseSearchOptions = RouterValidateUseSearchOptions< + TOptions, + Router +> + +export type ValidateUseParamsOptions = RouterValidateUseParamsOptions< + TOptions, + Router +> + +import type { + AnyRouteMatch, + KnownRouteMatchUnion, +} from '@tanstack/react-router' + +/** Narrows a full router match to the routes installed in this scope. */ +export function isScopedMatch( + match: AnyRouteMatch, +): match is KnownRouteMatchUnion { + return match.routeId.startsWith('@fixture/catalog#orgCatalog:') +} diff --git a/packages/router-generator/tests/route-modules/installations/routeScope.snapshot.ts b/packages/router-generator/tests/route-modules/installations/routeScope.snapshot.ts new file mode 100644 index 0000000000..983731384b --- /dev/null +++ b/packages/router-generator/tests/route-modules/installations/routeScope.snapshot.ts @@ -0,0 +1,13 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +export * as orgCatalog from './routeScope.gen.namespace1' + +export * as userCatalog from './routeScope.gen.namespace2' + +export * as account from './routeScope.gen.namespace0' diff --git a/packages/router-generator/tests/route-modules/installations/routeScope.userCatalog.snapshot.ts b/packages/router-generator/tests/route-modules/installations/routeScope.userCatalog.snapshot.ts new file mode 100644 index 0000000000..cf2bccb8c5 --- /dev/null +++ b/packages/router-generator/tests/route-modules/installations/routeScope.userCatalog.snapshot.ts @@ -0,0 +1,255 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import type { ScopedRouter, HostedRouter } from '@tanstack/react-router' + +import type { Router as FixtureCatalogRouter } from '@fixture/catalog/route-types' + +import type { MountedModuleHostParams } from './routeTree.gen' + +type Router = ScopedRouter< + HostedRouter< + FixtureCatalogRouter, + MountedModuleHostParams['@fixture/catalog#userCatalog'] + >, + '@fixture/catalog#userCatalog' +> + +import { + bindRouteScopeLink, + bindRouteScopeCreateLink, + bindRouteScopeLinkOptions, + bindRouteScopeNavigate, + bindRouteScopeUseNavigate, + bindRouteScopeRedirect, + bindRouteScopeMatchRoute, + bindRouteScopeUseMatchRoute, + bindRouteScopeUseRouter, + bindRouteScopeGetRouteApi, + bindRouteScopeUseMatch, + bindRouteScopeUseMatches, + bindRouteScopeUseParentMatches, + bindRouteScopeUseChildMatches, + bindRouteScopeUseLoaderData, + bindRouteScopeUseLoaderDeps, + bindRouteScopeUseSearch, + bindRouteScopeUseParams, + bindRouteScopeUseRouteContext, + bindRouteScopeUseLocation, + bindRouteScopeUseRouterState, + bindRouteScopeUseLinkProps, + bindRouteScopeUseBlocker, + bindRouteScopeNotFound, +} from '@tanstack/react-router/_internal/route-module' + +import type { RouteScope } from '@tanstack/react-router' + +export const Link: RouteScope['Link'] = + /* @__PURE__ */ bindRouteScopeLink('@fixture/catalog#userCatalog') + +export const createLink: RouteScope['createLink'] = + /* @__PURE__ */ bindRouteScopeCreateLink( + '@fixture/catalog#userCatalog', + ) + +export const linkOptions: RouteScope['linkOptions'] = + /* @__PURE__ */ bindRouteScopeLinkOptions( + '@fixture/catalog#userCatalog', + ) + +export const Navigate: RouteScope['Navigate'] = + /* @__PURE__ */ bindRouteScopeNavigate('@fixture/catalog#userCatalog') + +export const useNavigate: RouteScope['useNavigate'] = + /* @__PURE__ */ bindRouteScopeUseNavigate( + '@fixture/catalog#userCatalog', + ) + +export const redirect: RouteScope['redirect'] = + /* @__PURE__ */ bindRouteScopeRedirect('@fixture/catalog#userCatalog') + +export const MatchRoute: RouteScope['MatchRoute'] = + /* @__PURE__ */ bindRouteScopeMatchRoute( + '@fixture/catalog#userCatalog', + ) + +export const useMatchRoute: RouteScope['useMatchRoute'] = + /* @__PURE__ */ bindRouteScopeUseMatchRoute( + '@fixture/catalog#userCatalog', + ) + +export const useRouter: RouteScope['useRouter'] = + /* @__PURE__ */ bindRouteScopeUseRouter( + '@fixture/catalog#userCatalog', + ) + +export const getRouteApi: RouteScope['getRouteApi'] = + /* @__PURE__ */ bindRouteScopeGetRouteApi( + '@fixture/catalog#userCatalog', + ) + +export const useMatch: RouteScope['useMatch'] = + /* @__PURE__ */ bindRouteScopeUseMatch('@fixture/catalog#userCatalog') + +export const useMatches: RouteScope['useMatches'] = + /* @__PURE__ */ bindRouteScopeUseMatches( + '@fixture/catalog#userCatalog', + ) + +export const useParentMatches: RouteScope['useParentMatches'] = + /* @__PURE__ */ bindRouteScopeUseParentMatches( + '@fixture/catalog#userCatalog', + ) + +export const useChildMatches: RouteScope['useChildMatches'] = + /* @__PURE__ */ bindRouteScopeUseChildMatches( + '@fixture/catalog#userCatalog', + ) + +export const useLoaderData: RouteScope['useLoaderData'] = + /* @__PURE__ */ bindRouteScopeUseLoaderData( + '@fixture/catalog#userCatalog', + ) + +export const useLoaderDeps: RouteScope['useLoaderDeps'] = + /* @__PURE__ */ bindRouteScopeUseLoaderDeps( + '@fixture/catalog#userCatalog', + ) + +export const useSearch: RouteScope['useSearch'] = + /* @__PURE__ */ bindRouteScopeUseSearch( + '@fixture/catalog#userCatalog', + ) + +export const useParams: RouteScope['useParams'] = + /* @__PURE__ */ bindRouteScopeUseParams( + '@fixture/catalog#userCatalog', + ) + +export const useRouteContext: RouteScope['useRouteContext'] = + /* @__PURE__ */ bindRouteScopeUseRouteContext( + '@fixture/catalog#userCatalog', + ) + +export const useLocation: RouteScope['useLocation'] = + /* @__PURE__ */ bindRouteScopeUseLocation( + '@fixture/catalog#userCatalog', + ) + +export const useRouterState: RouteScope['useRouterState'] = + /* @__PURE__ */ bindRouteScopeUseRouterState( + '@fixture/catalog#userCatalog', + ) + +export const useLinkProps: RouteScope['useLinkProps'] = + /* @__PURE__ */ bindRouteScopeUseLinkProps( + '@fixture/catalog#userCatalog', + ) + +export const useBlocker: RouteScope['useBlocker'] = + /* @__PURE__ */ bindRouteScopeUseBlocker( + '@fixture/catalog#userCatalog', + ) + +export const notFound: RouteScope['notFound'] = + /* @__PURE__ */ bindRouteScopeNotFound('@fixture/catalog#userCatalog') + +import type { + ValidateLinkOptions as RouterValidateLinkOptions, + ValidateLinkOptionsArray as RouterValidateLinkOptionsArray, + ValidateNavigateOptions as RouterValidateNavigateOptions, + ValidateNavigateOptionsArray as RouterValidateNavigateOptionsArray, + ValidateRedirectOptions as RouterValidateRedirectOptions, + ValidateRedirectOptionsArray as RouterValidateRedirectOptionsArray, + ValidateFromPath as RouterValidateFromPath, + ValidateToPath as RouterValidateToPath, + ValidateSearch as RouterValidateSearch, + ValidateParams as RouterValidateParams, + ValidateId as RouterValidateId, + ValidateUseSearchOptions as RouterValidateUseSearchOptions, + ValidateUseParamsOptions as RouterValidateUseParamsOptions, +} from '@tanstack/react-router' + +export type ValidateLinkOptions< + TOptions = unknown, + TDefaultFrom extends string = string, + TComp = 'a', +> = RouterValidateLinkOptions + +export type ValidateLinkOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, + TComp = 'a', +> = RouterValidateLinkOptionsArray + +export type ValidateNavigateOptions< + TOptions = unknown, + TDefaultFrom extends string = string, +> = RouterValidateNavigateOptions + +export type ValidateNavigateOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, +> = RouterValidateNavigateOptionsArray + +export type ValidateRedirectOptions< + TOptions = unknown, + TDefaultFrom extends string = string, +> = RouterValidateRedirectOptions + +export type ValidateRedirectOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, +> = RouterValidateRedirectOptionsArray + +export type ValidateFromPath = RouterValidateFromPath< + Router, + TFrom +> + +export type ValidateToPath< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateToPath + +export type ValidateSearch< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateSearch + +export type ValidateParams< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateParams + +export type ValidateId = RouterValidateId< + Router, + TId +> + +export type ValidateUseSearchOptions = RouterValidateUseSearchOptions< + TOptions, + Router +> + +export type ValidateUseParamsOptions = RouterValidateUseParamsOptions< + TOptions, + Router +> + +import type { + AnyRouteMatch, + KnownRouteMatchUnion, +} from '@tanstack/react-router' + +/** Narrows a full router match to the routes installed in this scope. */ +export function isScopedMatch( + match: AnyRouteMatch, +): match is KnownRouteMatchUnion { + return match.routeId.startsWith('@fixture/catalog#userCatalog:') +} diff --git a/packages/router-generator/tests/route-modules/installations/routeTree.snapshot.ts b/packages/router-generator/tests/route-modules/installations/routeTree.snapshot.ts new file mode 100644 index 0000000000..c87fdf44e5 --- /dev/null +++ b/packages/router-generator/tests/route-modules/installations/routeTree.snapshot.ts @@ -0,0 +1,157 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { mountRouteModule } from '@tanstack/react-router/_internal/route-module' +import { routeModule as FixtureCatalogRouteModule } from '@fixture/catalog/route-module' +import { routeModule as FixtureAccountRouteModule } from '@fixture/account/route-module' +import type { + MountedRoutesById, + InstallationRoutesById, +} from '@tanstack/react-router' +import type { InstalledRoutesById as FixtureCatalogInstalledRoutesById } from '@fixture/catalog/route-types' +import type { InstalledRoutesById as FixtureAccountInstalledRoutesById } from '@fixture/account/route-types' + +import { Route as rootRouteImport } from './routes/__root' +import { Route as OrgsOrgIdRouteImport } from './routes/orgs.$orgId' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' + +const OrgsOrgIdRoute = OrgsOrgIdRouteImport.update({ + id: '/orgs/$orgId', + path: '/orgs/$orgId', + getParentRoute: () => rootRouteImport, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/users/$userId', + path: '/users/$userId', + getParentRoute: () => rootRouteImport, +} as any) + +const FixtureCatalogOrgCatalogModuleRoute: typeof FixtureCatalogRouteModule = + mountRouteModule(FixtureCatalogRouteModule, { + parent: () => OrgsOrgIdRoute, + at: '/catalog', + as: 'orgCatalog', + }) + +const FixtureCatalogUserCatalogModuleRoute: typeof FixtureCatalogRouteModule = + mountRouteModule(FixtureCatalogRouteModule, { + parent: () => UsersUserIdRoute, + at: '/catalog', + as: 'userCatalog', + }) + +const FixtureAccountModuleRoute: typeof FixtureAccountRouteModule = + mountRouteModule(FixtureAccountRouteModule, { + parent: () => OrgsOrgIdRoute, + at: '/account', + uses: { '@fixture/catalog': '@fixture/catalog#orgCatalog' }, + }) + +/** The path params of the routes above each mounted route module. */ +export interface MountedModuleHostParams { + '@fixture/catalog#orgCatalog': (typeof OrgsOrgIdRoute)['types']['allParams'] + '@fixture/catalog#userCatalog': (typeof UsersUserIdRoute)['types']['allParams'] + '@fixture/account': (typeof OrgsOrgIdRoute)['types']['allParams'] +} + +export interface FileRoutesByFullPath { + '/orgs/$orgId': typeof OrgsOrgIdRouteWithChildren + '/users/$userId': typeof UsersUserIdRouteWithChildren +} +export interface FileRoutesByTo { + '/orgs/$orgId': typeof OrgsOrgIdRouteWithChildren + '/users/$userId': typeof UsersUserIdRouteWithChildren +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/orgs/$orgId': typeof OrgsOrgIdRouteWithChildren + '/users/$userId': typeof UsersUserIdRouteWithChildren +} +interface RouteModuleRoutesById + extends + FileRoutesById, + MountedRoutesById< + InstallationRoutesById< + FixtureCatalogInstalledRoutesById, + '@fixture/catalog', + 'orgCatalog' + > + >, + MountedRoutesById< + InstallationRoutesById< + FixtureCatalogInstalledRoutesById, + '@fixture/catalog', + 'userCatalog' + > + >, + MountedRoutesById {} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/orgs/$orgId' | '/users/$userId' + fileRoutesByTo: FileRoutesByTo + to: '/orgs/$orgId' | '/users/$userId' + id: keyof RouteModuleRoutesById + fileRoutesById: RouteModuleRoutesById +} +export interface RootRouteChildren { + OrgsOrgIdRoute: typeof OrgsOrgIdRouteWithChildren + UsersUserIdRoute: typeof UsersUserIdRouteWithChildren +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/orgs/$orgId': { + id: '/orgs/$orgId' + path: '/orgs/$orgId' + fullPath: '/orgs/$orgId' + preLoaderRoute: typeof OrgsOrgIdRouteImport + parentRoute: typeof rootRouteImport + } + '/users/$userId': { + id: '/users/$userId' + path: '/users/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +interface OrgsOrgIdRouteChildren { + FixtureCatalogOrgCatalogModuleRoute: typeof FixtureCatalogOrgCatalogModuleRoute + FixtureAccountModuleRoute: typeof FixtureAccountModuleRoute +} + +const OrgsOrgIdRouteChildren: OrgsOrgIdRouteChildren = { + FixtureCatalogOrgCatalogModuleRoute: FixtureCatalogOrgCatalogModuleRoute, + FixtureAccountModuleRoute: FixtureAccountModuleRoute, +} + +const OrgsOrgIdRouteWithChildren = OrgsOrgIdRoute._addFileChildren( + OrgsOrgIdRouteChildren, +) + +interface UsersUserIdRouteChildren { + FixtureCatalogUserCatalogModuleRoute: typeof FixtureCatalogUserCatalogModuleRoute +} + +const UsersUserIdRouteChildren: UsersUserIdRouteChildren = { + FixtureCatalogUserCatalogModuleRoute: FixtureCatalogUserCatalogModuleRoute, +} + +const UsersUserIdRouteWithChildren = UsersUserIdRoute._addFileChildren( + UsersUserIdRouteChildren, +) + +const rootRouteChildren: RootRouteChildren = { + OrgsOrgIdRoute: OrgsOrgIdRouteWithChildren, + UsersUserIdRoute: UsersUserIdRouteWithChildren, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/packages/router-generator/tests/route-modules/module/routeContract.snapshot.ts b/packages/router-generator/tests/route-modules/module/routeContract.snapshot.ts new file mode 100644 index 0000000000..10b610b38f --- /dev/null +++ b/packages/router-generator/tests/route-modules/module/routeContract.snapshot.ts @@ -0,0 +1,33 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import type { RouteModuleRouter } from './routeScope.gen' +import type { FileRoutesById, routeTree } from './routeTree.gen' + +/** The route tree of "@fixture/catalog": its module root with all its routes. */ +export type RouteModuleTree = typeof routeTree + +/** The router type of "@fixture/catalog" (module-local paths, qualified ids). */ +export type Router = RouteModuleRouter + +/** The routes of "@fixture/catalog" by qualified id, without other modules. */ +export type OwnRoutesById = FileRoutesById + +/** All routes installed with "@fixture/catalog", including the modules it mounts. */ +export interface InstalledRoutesById extends FileRoutesById {} + +/** The routers of "@fixture/catalog" and of every module it mounts, by module id. */ +export interface InstalledRouters { + '@fixture/catalog': Router +} + +/** + * The path params above every module "@fixture/catalog" installs, relative to its + * root. Packages that mount "@fixture/catalog" under path params add their own. + */ +export interface InstalledHostParams {} diff --git a/packages/router-generator/tests/route-modules/module/routeModule.snapshot.ts b/packages/router-generator/tests/route-modules/module/routeModule.snapshot.ts new file mode 100644 index 0000000000..5c40aa007d --- /dev/null +++ b/packages/router-generator/tests/route-modules/module/routeModule.snapshot.ts @@ -0,0 +1,10 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +/** The root route of this module with all its routes. Mount it with `mountRouteModule`. */ +export { routeTree as routeModule } from './routeTree.gen' diff --git a/packages/router-generator/tests/route-modules/module/routeScope.snapshot.ts b/packages/router-generator/tests/route-modules/module/routeScope.snapshot.ts new file mode 100644 index 0000000000..a7a85ea7a8 --- /dev/null +++ b/packages/router-generator/tests/route-modules/module/routeScope.snapshot.ts @@ -0,0 +1,277 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { bindCreateModuleRoot } from '@tanstack/react-router/_internal/route-module' + +import { createFileRoute as createFrameworkFileRoute } from '@tanstack/react-router' + +import type { ScopeRouter, FileRouteScope } from '@tanstack/react-router' + +import type { FileRoutesByPath, routeTree } from './routeTree.gen' + +export type RouteModuleRouter = ScopeRouter< + typeof routeTree, + '@fixture/catalog' +> + +export interface RouteModuleRegister { + router: RouteModuleRouter +} + +export const createFileRoute = createFrameworkFileRoute as FileRouteScope< + FileRoutesByPath, + RouteModuleRegister, + '@fixture/catalog' +>['createFileRoute'] + +export const createModuleRoot = /* @__PURE__ */ bindCreateModuleRoot< + RouteModuleRegister, + '@fixture/catalog' +>('@fixture/catalog') + +import { + bindRouteScopeLink, + bindRouteScopeCreateLink, + bindRouteScopeLinkOptions, + bindRouteScopeNavigate, + bindRouteScopeUseNavigate, + bindRouteScopeRedirect, + bindRouteScopeMatchRoute, + bindRouteScopeUseMatchRoute, + bindRouteScopeUseRouter, + bindRouteScopeGetRouteApi, + bindRouteScopeUseMatch, + bindRouteScopeUseMatches, + bindRouteScopeUseParentMatches, + bindRouteScopeUseChildMatches, + bindRouteScopeUseLoaderData, + bindRouteScopeUseLoaderDeps, + bindRouteScopeUseSearch, + bindRouteScopeUseParams, + bindRouteScopeUseRouteContext, + bindRouteScopeUseLocation, + bindRouteScopeUseRouterState, + bindRouteScopeUseLinkProps, + bindRouteScopeUseBlocker, + bindRouteScopeNotFound, +} from '@tanstack/react-router/_internal/route-module' + +import type { RouteScope } from '@tanstack/react-router' + +export const Link: RouteScope['Link'] = + /* @__PURE__ */ bindRouteScopeLink('@fixture/catalog') + +export const createLink: RouteScope['createLink'] = + /* @__PURE__ */ bindRouteScopeCreateLink( + '@fixture/catalog', + ) + +export const linkOptions: RouteScope['linkOptions'] = + /* @__PURE__ */ bindRouteScopeLinkOptions( + '@fixture/catalog', + ) + +export const Navigate: RouteScope['Navigate'] = + /* @__PURE__ */ bindRouteScopeNavigate('@fixture/catalog') + +export const useNavigate: RouteScope['useNavigate'] = + /* @__PURE__ */ bindRouteScopeUseNavigate( + '@fixture/catalog', + ) + +export const redirect: RouteScope['redirect'] = + /* @__PURE__ */ bindRouteScopeRedirect('@fixture/catalog') + +export const MatchRoute: RouteScope['MatchRoute'] = + /* @__PURE__ */ bindRouteScopeMatchRoute( + '@fixture/catalog', + ) + +export const useMatchRoute: RouteScope['useMatchRoute'] = + /* @__PURE__ */ bindRouteScopeUseMatchRoute( + '@fixture/catalog', + ) + +export const useRouter: RouteScope['useRouter'] = + /* @__PURE__ */ bindRouteScopeUseRouter('@fixture/catalog') + +export const getRouteApi: RouteScope['getRouteApi'] = + /* @__PURE__ */ bindRouteScopeGetRouteApi( + '@fixture/catalog', + ) + +export const useMatch: RouteScope['useMatch'] = + /* @__PURE__ */ bindRouteScopeUseMatch('@fixture/catalog') + +export const useMatches: RouteScope['useMatches'] = + /* @__PURE__ */ bindRouteScopeUseMatches( + '@fixture/catalog', + ) + +export const useParentMatches: RouteScope['useParentMatches'] = + /* @__PURE__ */ bindRouteScopeUseParentMatches( + '@fixture/catalog', + ) + +export const useChildMatches: RouteScope['useChildMatches'] = + /* @__PURE__ */ bindRouteScopeUseChildMatches( + '@fixture/catalog', + ) + +export const useLoaderData: RouteScope['useLoaderData'] = + /* @__PURE__ */ bindRouteScopeUseLoaderData( + '@fixture/catalog', + ) + +export const useLoaderDeps: RouteScope['useLoaderDeps'] = + /* @__PURE__ */ bindRouteScopeUseLoaderDeps( + '@fixture/catalog', + ) + +export const useSearch: RouteScope['useSearch'] = + /* @__PURE__ */ bindRouteScopeUseSearch('@fixture/catalog') + +export const useParams: RouteScope['useParams'] = + /* @__PURE__ */ bindRouteScopeUseParams('@fixture/catalog') + +export const useRouteContext: RouteScope['useRouteContext'] = + /* @__PURE__ */ bindRouteScopeUseRouteContext( + '@fixture/catalog', + ) + +export const useLocation: RouteScope['useLocation'] = + /* @__PURE__ */ bindRouteScopeUseLocation( + '@fixture/catalog', + ) + +export const useRouterState: RouteScope['useRouterState'] = + /* @__PURE__ */ bindRouteScopeUseRouterState( + '@fixture/catalog', + ) + +export const useLinkProps: RouteScope['useLinkProps'] = + /* @__PURE__ */ bindRouteScopeUseLinkProps( + '@fixture/catalog', + ) + +export const useBlocker: RouteScope['useBlocker'] = + /* @__PURE__ */ bindRouteScopeUseBlocker( + '@fixture/catalog', + ) + +export const notFound: RouteScope['notFound'] = + /* @__PURE__ */ bindRouteScopeNotFound('@fixture/catalog') + +import type { + ValidateLinkOptions as RouterValidateLinkOptions, + ValidateLinkOptionsArray as RouterValidateLinkOptionsArray, + ValidateNavigateOptions as RouterValidateNavigateOptions, + ValidateNavigateOptionsArray as RouterValidateNavigateOptionsArray, + ValidateRedirectOptions as RouterValidateRedirectOptions, + ValidateRedirectOptionsArray as RouterValidateRedirectOptionsArray, + ValidateFromPath as RouterValidateFromPath, + ValidateToPath as RouterValidateToPath, + ValidateSearch as RouterValidateSearch, + ValidateParams as RouterValidateParams, + ValidateId as RouterValidateId, + ValidateUseSearchOptions as RouterValidateUseSearchOptions, + ValidateUseParamsOptions as RouterValidateUseParamsOptions, +} from '@tanstack/react-router' + +export type ValidateLinkOptions< + TOptions = unknown, + TDefaultFrom extends string = string, + TComp = 'a', +> = RouterValidateLinkOptions + +export type ValidateLinkOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, + TComp = 'a', +> = RouterValidateLinkOptionsArray< + RouteModuleRouter, + TOptions, + TDefaultFrom, + TComp +> + +export type ValidateNavigateOptions< + TOptions = unknown, + TDefaultFrom extends string = string, +> = RouterValidateNavigateOptions + +export type ValidateNavigateOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, +> = RouterValidateNavigateOptionsArray< + RouteModuleRouter, + TOptions, + TDefaultFrom +> + +export type ValidateRedirectOptions< + TOptions = unknown, + TDefaultFrom extends string = string, +> = RouterValidateRedirectOptions + +export type ValidateRedirectOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, +> = RouterValidateRedirectOptionsArray< + RouteModuleRouter, + TOptions, + TDefaultFrom +> + +export type ValidateFromPath = RouterValidateFromPath< + RouteModuleRouter, + TFrom +> + +export type ValidateToPath< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateToPath + +export type ValidateSearch< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateSearch + +export type ValidateParams< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateParams + +export type ValidateId = RouterValidateId< + RouteModuleRouter, + TId +> + +export type ValidateUseSearchOptions = RouterValidateUseSearchOptions< + TOptions, + RouteModuleRouter +> + +export type ValidateUseParamsOptions = RouterValidateUseParamsOptions< + TOptions, + RouteModuleRouter +> + +import type { + AnyRouteMatch, + KnownRouteMatchUnion, +} from '@tanstack/react-router' + +/** Narrows a full router match to the routes installed in this scope. */ +export function isScopedMatch( + match: AnyRouteMatch, +): match is KnownRouteMatchUnion { + const localRouteId = match.localRouteId ?? '' + return localRouteId.startsWith('@fixture/catalog:') +} diff --git a/packages/router-generator/tests/route-modules/module/routeTree.snapshot.ts b/packages/router-generator/tests/route-modules/module/routeTree.snapshot.ts new file mode 100644 index 0000000000..386ce827d4 --- /dev/null +++ b/packages/router-generator/tests/route-modules/module/routeTree.snapshot.ts @@ -0,0 +1,112 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as ItemIdRouteImport } from './routes/$itemId' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as LayoutSaleRouteImport } from './routes/_layout/sale' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ItemIdRoute = ItemIdRouteImport.update({ + id: '/$itemId', + path: '/$itemId', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutSaleRoute = LayoutSaleRouteImport.update({ + id: '/sale', + path: '/sale', + getParentRoute: () => LayoutRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/$itemId': typeof ItemIdRoute + '/sale': typeof LayoutSaleRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/$itemId': typeof ItemIdRoute + '/sale': typeof LayoutSaleRoute +} +export interface FileRoutesById { + '@fixture/catalog:': typeof rootRouteImport + '@fixture/catalog:/': typeof IndexRoute + '@fixture/catalog:/$itemId': typeof ItemIdRoute + '@fixture/catalog:/_layout': typeof LayoutRouteWithChildren + '@fixture/catalog:/_layout/sale': typeof LayoutSaleRoute +} +interface RouteModuleRoutesById extends FileRoutesById {} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/$itemId' | '/sale' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/$itemId' | '/sale' + id: keyof RouteModuleRoutesById + fileRoutesById: RouteModuleRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ItemIdRoute: typeof ItemIdRoute + LayoutRoute: typeof LayoutRouteWithChildren +} + +export interface FileRoutesByPath { + '@fixture/catalog:/': { + id: '@fixture/catalog:/' + path: '/' + fullPath: '/' + parentRoute: typeof rootRouteImport + } + '@fixture/catalog:/$itemId': { + id: '@fixture/catalog:/$itemId' + path: '/$itemId' + fullPath: '/$itemId' + parentRoute: typeof rootRouteImport + } + '@fixture/catalog:/_layout': { + id: '@fixture/catalog:/_layout' + path: '' + fullPath: '/' + parentRoute: typeof rootRouteImport + } + '@fixture/catalog:/_layout/sale': { + id: '@fixture/catalog:/_layout/sale' + path: '/sale' + fullPath: '/sale' + parentRoute: typeof LayoutRoute + } +} + +interface LayoutRouteChildren { + LayoutSaleRoute: typeof LayoutSaleRoute +} + +const LayoutRouteChildren: LayoutRouteChildren = { + LayoutSaleRoute: LayoutSaleRoute, +} + +const LayoutRouteWithChildren = + LayoutRoute._addFileChildren(LayoutRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ItemIdRoute: ItemIdRoute, + LayoutRoute: LayoutRouteWithChildren, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/packages/router-generator/tests/route-modules/start-application/startModules.snapshot.ts b/packages/router-generator/tests/route-modules/start-application/startModules.snapshot.ts new file mode 100644 index 0000000000..df845b43ed --- /dev/null +++ b/packages/router-generator/tests/route-modules/start-application/startModules.snapshot.ts @@ -0,0 +1,34 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import type { + AssertStartModules, + ValidateStartModules, +} from '@tanstack/react-start' +import type { startInstance } from './start' +import { startModules as FixtureCatalogStartModules } from '@fixture/catalog/route-module' + +/** + * The TanStack Start fragments of every installed route module. Install them + * with `createStart(() => ({ extends: startModules }))`. + */ +export const startModules: readonly [...typeof FixtureCatalogStartModules] = [ + ...FixtureCatalogStartModules, +] + +/** + * Fails to type-check when `startInstance` does not install the fragments or + * does not provide the context they require. + */ +export type StartModulesCheck = AssertStartModules< + ValidateStartModules< + typeof startInstance, + typeof startModules, + readonly ['@fixture/catalog'] + > +> diff --git a/packages/router-generator/tests/route-modules/start-module/routeModule.snapshot.ts b/packages/router-generator/tests/route-modules/start-module/routeModule.snapshot.ts new file mode 100644 index 0000000000..91099aecb5 --- /dev/null +++ b/packages/router-generator/tests/route-modules/start-module/routeModule.snapshot.ts @@ -0,0 +1,18 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { start } from './start' + +/** The root route of this module with all its routes. Mount it with `mountRouteModule`. */ +export { routeTree as routeModule } from './routeTree.gen' + +/** + * The TanStack Start fragments of this module and of the modules it mounts. + * Applications install them with `createStart(() => ({ extends: startModules }))`. + */ +export const startModules: readonly [typeof start] = [start] diff --git a/packages/router-generator/tests/route-modules/start-module/routeScope.snapshot.ts b/packages/router-generator/tests/route-modules/start-module/routeScope.snapshot.ts new file mode 100644 index 0000000000..0f57ecad21 --- /dev/null +++ b/packages/router-generator/tests/route-modules/start-module/routeScope.snapshot.ts @@ -0,0 +1,306 @@ +/* eslint-disable */ + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { bindCreateModuleRoot } from '@tanstack/react-router/_internal/route-module' + +import { createFileRoute as createFrameworkFileRoute } from '@tanstack/react-router' + +import type { ScopeRouter, FileRouteScope } from '@tanstack/react-router' + +import type { FileRoutesByPath, routeTree } from './routeTree.gen' + +export type RouteModuleRouter = ScopeRouter< + typeof routeTree, + '@fixture/catalog' +> + +import { + createServerFn as createStartServerFn, + createMiddleware as createStartMiddleware, +} from '@tanstack/react-start' + +import { createStartModule as createStartModuleFor } from '@tanstack/react-start/_internal/route-module' + +import type { + CreateServerFn, + CreateMiddlewareFn, + StartModuleRegister, + StartModuleConfig, +} from '@tanstack/react-start' + +import type { start } from './start' + +export interface RouteModuleRegister extends StartModuleRegister<'@fixture/catalog'> { + router: RouteModuleRouter + ssr: true + config: StartModuleConfig +} + +export const createFileRoute = createFrameworkFileRoute as FileRouteScope< + FileRoutesByPath, + RouteModuleRegister, + '@fixture/catalog' +>['createFileRoute'] + +export const createModuleRoot = /* @__PURE__ */ bindCreateModuleRoot< + RouteModuleRegister, + '@fixture/catalog' +>('@fixture/catalog') + +import { + bindRouteScopeLink, + bindRouteScopeCreateLink, + bindRouteScopeLinkOptions, + bindRouteScopeNavigate, + bindRouteScopeUseNavigate, + bindRouteScopeRedirect, + bindRouteScopeMatchRoute, + bindRouteScopeUseMatchRoute, + bindRouteScopeUseRouter, + bindRouteScopeGetRouteApi, + bindRouteScopeUseMatch, + bindRouteScopeUseMatches, + bindRouteScopeUseParentMatches, + bindRouteScopeUseChildMatches, + bindRouteScopeUseLoaderData, + bindRouteScopeUseLoaderDeps, + bindRouteScopeUseSearch, + bindRouteScopeUseParams, + bindRouteScopeUseRouteContext, + bindRouteScopeUseLocation, + bindRouteScopeUseRouterState, + bindRouteScopeUseLinkProps, + bindRouteScopeUseBlocker, + bindRouteScopeNotFound, +} from '@tanstack/react-router/_internal/route-module' + +import type { RouteScope } from '@tanstack/react-router' + +export const Link: RouteScope['Link'] = + /* @__PURE__ */ bindRouteScopeLink('@fixture/catalog') + +export const createLink: RouteScope['createLink'] = + /* @__PURE__ */ bindRouteScopeCreateLink( + '@fixture/catalog', + ) + +export const linkOptions: RouteScope['linkOptions'] = + /* @__PURE__ */ bindRouteScopeLinkOptions( + '@fixture/catalog', + ) + +export const Navigate: RouteScope['Navigate'] = + /* @__PURE__ */ bindRouteScopeNavigate('@fixture/catalog') + +export const useNavigate: RouteScope['useNavigate'] = + /* @__PURE__ */ bindRouteScopeUseNavigate( + '@fixture/catalog', + ) + +export const redirect: RouteScope['redirect'] = + /* @__PURE__ */ bindRouteScopeRedirect('@fixture/catalog') + +export const MatchRoute: RouteScope['MatchRoute'] = + /* @__PURE__ */ bindRouteScopeMatchRoute( + '@fixture/catalog', + ) + +export const useMatchRoute: RouteScope['useMatchRoute'] = + /* @__PURE__ */ bindRouteScopeUseMatchRoute( + '@fixture/catalog', + ) + +export const useRouter: RouteScope['useRouter'] = + /* @__PURE__ */ bindRouteScopeUseRouter('@fixture/catalog') + +export const getRouteApi: RouteScope['getRouteApi'] = + /* @__PURE__ */ bindRouteScopeGetRouteApi( + '@fixture/catalog', + ) + +export const useMatch: RouteScope['useMatch'] = + /* @__PURE__ */ bindRouteScopeUseMatch('@fixture/catalog') + +export const useMatches: RouteScope['useMatches'] = + /* @__PURE__ */ bindRouteScopeUseMatches( + '@fixture/catalog', + ) + +export const useParentMatches: RouteScope['useParentMatches'] = + /* @__PURE__ */ bindRouteScopeUseParentMatches( + '@fixture/catalog', + ) + +export const useChildMatches: RouteScope['useChildMatches'] = + /* @__PURE__ */ bindRouteScopeUseChildMatches( + '@fixture/catalog', + ) + +export const useLoaderData: RouteScope['useLoaderData'] = + /* @__PURE__ */ bindRouteScopeUseLoaderData( + '@fixture/catalog', + ) + +export const useLoaderDeps: RouteScope['useLoaderDeps'] = + /* @__PURE__ */ bindRouteScopeUseLoaderDeps( + '@fixture/catalog', + ) + +export const useSearch: RouteScope['useSearch'] = + /* @__PURE__ */ bindRouteScopeUseSearch('@fixture/catalog') + +export const useParams: RouteScope['useParams'] = + /* @__PURE__ */ bindRouteScopeUseParams('@fixture/catalog') + +export const useRouteContext: RouteScope['useRouteContext'] = + /* @__PURE__ */ bindRouteScopeUseRouteContext( + '@fixture/catalog', + ) + +export const useLocation: RouteScope['useLocation'] = + /* @__PURE__ */ bindRouteScopeUseLocation( + '@fixture/catalog', + ) + +export const useRouterState: RouteScope['useRouterState'] = + /* @__PURE__ */ bindRouteScopeUseRouterState( + '@fixture/catalog', + ) + +export const useLinkProps: RouteScope['useLinkProps'] = + /* @__PURE__ */ bindRouteScopeUseLinkProps( + '@fixture/catalog', + ) + +export const useBlocker: RouteScope['useBlocker'] = + /* @__PURE__ */ bindRouteScopeUseBlocker( + '@fixture/catalog', + ) + +export const notFound: RouteScope['notFound'] = + /* @__PURE__ */ bindRouteScopeNotFound('@fixture/catalog') + +import type { + ValidateLinkOptions as RouterValidateLinkOptions, + ValidateLinkOptionsArray as RouterValidateLinkOptionsArray, + ValidateNavigateOptions as RouterValidateNavigateOptions, + ValidateNavigateOptionsArray as RouterValidateNavigateOptionsArray, + ValidateRedirectOptions as RouterValidateRedirectOptions, + ValidateRedirectOptionsArray as RouterValidateRedirectOptionsArray, + ValidateFromPath as RouterValidateFromPath, + ValidateToPath as RouterValidateToPath, + ValidateSearch as RouterValidateSearch, + ValidateParams as RouterValidateParams, + ValidateId as RouterValidateId, + ValidateUseSearchOptions as RouterValidateUseSearchOptions, + ValidateUseParamsOptions as RouterValidateUseParamsOptions, +} from '@tanstack/react-router' + +export type ValidateLinkOptions< + TOptions = unknown, + TDefaultFrom extends string = string, + TComp = 'a', +> = RouterValidateLinkOptions + +export type ValidateLinkOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, + TComp = 'a', +> = RouterValidateLinkOptionsArray< + RouteModuleRouter, + TOptions, + TDefaultFrom, + TComp +> + +export type ValidateNavigateOptions< + TOptions = unknown, + TDefaultFrom extends string = string, +> = RouterValidateNavigateOptions + +export type ValidateNavigateOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, +> = RouterValidateNavigateOptionsArray< + RouteModuleRouter, + TOptions, + TDefaultFrom +> + +export type ValidateRedirectOptions< + TOptions = unknown, + TDefaultFrom extends string = string, +> = RouterValidateRedirectOptions + +export type ValidateRedirectOptionsArray< + TOptions extends ReadonlyArray = ReadonlyArray, + TDefaultFrom extends string = string, +> = RouterValidateRedirectOptionsArray< + RouteModuleRouter, + TOptions, + TDefaultFrom +> + +export type ValidateFromPath = RouterValidateFromPath< + RouteModuleRouter, + TFrom +> + +export type ValidateToPath< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateToPath + +export type ValidateSearch< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateSearch + +export type ValidateParams< + TTo extends string | undefined = undefined, + TFrom extends string = string, +> = RouterValidateParams + +export type ValidateId = RouterValidateId< + RouteModuleRouter, + TId +> + +export type ValidateUseSearchOptions = RouterValidateUseSearchOptions< + TOptions, + RouteModuleRouter +> + +export type ValidateUseParamsOptions = RouterValidateUseParamsOptions< + TOptions, + RouteModuleRouter +> + +import type { + AnyRouteMatch, + KnownRouteMatchUnion, +} from '@tanstack/react-router' + +/** Narrows a full router match to the routes installed in this scope. */ +export function isScopedMatch( + match: AnyRouteMatch, +): match is KnownRouteMatchUnion { + const localRouteId = match.localRouteId ?? '' + return localRouteId.startsWith('@fixture/catalog:') +} + +export const createServerFn = + createStartServerFn as unknown as CreateServerFn + +export const createMiddleware = + createStartMiddleware as unknown as CreateMiddlewareFn< + StartModuleRegister<'@fixture/catalog'> + > + +export const createStartModule = + /* @__PURE__ */ createStartModuleFor('@fixture/catalog') diff --git a/packages/router-generator/tsconfig.json b/packages/router-generator/tsconfig.json index d1334dff90..597f7786cd 100644 --- a/packages/router-generator/tsconfig.json +++ b/packages/router-generator/tsconfig.json @@ -15,6 +15,7 @@ "tests/generator/**/routeTree.gen.js", "tests/generator/**/routeTree.gen.ts", "tests/generator/**/routeTree.snapshot.js", - "tests/generator/**/routeTree.snapshot.ts" + "tests/generator/**/routeTree.snapshot.ts", + "tests/route-modules/**" ] } diff --git a/packages/router-generator/tsconfig.legacy.json b/packages/router-generator/tsconfig.legacy.json index 604fde5556..f301a27d89 100644 --- a/packages/router-generator/tsconfig.legacy.json +++ b/packages/router-generator/tsconfig.legacy.json @@ -1,5 +1,5 @@ { "extends": "../../tsconfig.json", "include": ["src", "vite.config.ts", "tests"], - "exclude": ["tests/generator/**/**"] + "exclude": ["tests/generator/**/**", "tests/route-modules/**"] } diff --git a/packages/router-plugin/package.json b/packages/router-plugin/package.json index b4bc9a2a9e..8be10b1e1c 100644 --- a/packages/router-plugin/package.json +++ b/packages/router-plugin/package.json @@ -114,7 +114,7 @@ "!skills/_artifacts" ], "engines": { - "node": ">=20.19" + "node": ">=22.22.0" }, "dependencies": { "@babel/core": "catalog:", diff --git a/packages/router-plugin/src/core/code-splitter/compilers.ts b/packages/router-plugin/src/core/code-splitter/compilers.ts index 89cdae41ad..2c0f1cc022 100644 --- a/packages/router-plugin/src/core/code-splitter/compilers.ts +++ b/packages/router-plugin/src/core/code-splitter/compilers.ts @@ -1037,7 +1037,8 @@ export function compileCodeSplitVirtualRoute( splitMeta.localExporterIdent = splitNode.id.name } else if ( t.isFunctionExpression(splitNode) || - t.isArrowFunctionExpression(splitNode) + t.isArrowFunctionExpression(splitNode) || + t.isCallExpression(splitNode) ) { programPath.pushContainer( 'body', @@ -1077,40 +1078,6 @@ export function compileCodeSplitVirtualRoute( `Unexpected splitNode type ☝️: ${splitNode.type}`, ) } - } else if (t.isCallExpression(splitNode)) { - const outputSplitNodeCode = generateFromAst(splitNode).code - const splitNodeAst = babel.parse(outputSplitNodeCode) - - if (!splitNodeAst) { - throw new Error( - `Failed to parse the generated code for "${SPLIT_TYPE}" in the node type "${splitNode.type}"`, - ) - } - - const statement = splitNodeAst.program.body[0] - - if (!statement) { - throw new Error( - `Failed to parse the generated code for "${SPLIT_TYPE}" in the node type "${splitNode.type}" as no statement was found in the program body`, - ) - } - - if (t.isExpressionStatement(statement)) { - const expression = statement.expression - programPath.pushContainer( - 'body', - t.variableDeclaration('const', [ - t.variableDeclarator( - t.identifier(splitMeta.localExporterIdent), - expression, - ), - ]), - ) - } else { - throw new Error( - `Unexpected expression type encounter for "${SPLIT_TYPE}" in the node type "${splitNode.type}"`, - ) - } } else if (t.isConditionalExpression(splitNode)) { programPath.pushContainer( 'body', diff --git a/packages/router-plugin/src/core/hmr/handle-route-update.ts b/packages/router-plugin/src/core/hmr/handle-route-update.ts index 23b51d2432..07c1968c23 100644 --- a/packages/router-plugin/src/core/hmr/handle-route-update.ts +++ b/packages/router-plugin/src/core/hmr/handle-route-update.ts @@ -4,6 +4,7 @@ type AnyRouteWithPrivateProps = AnyRoute & { options: Record parentRoute: AnyRoute _lazy?: Promise | true + _template?: AnyRouteWithPrivateProps update: (options: Record) => unknown _path: string _id: string @@ -19,30 +20,48 @@ type AnyRouterWithPrivateState = AnyRouter & { _replaceRouteChunk: (route: AnyRoute, lazyFn: AnyRoute['lazyFn']) => void } +/** + * Applies a hot update of a route file to the live router. Returns whether + * the router had an older version of the route to update. + */ function handleRouteUpdate( routeId: string, newRoute: AnyRouteWithPrivateProps, -) { +): boolean { const router = window.__TSR_ROUTER__ as AnyRouterWithPrivateState const oldRoute = router.routesById[routeId] as | AnyRouteWithPrivateProps | undefined - if (!oldRoute) { - return + // The route of a route module the route tree installs several times is the + // template of one copy per installation: `#:/…` for + // `:/…`. The copies are updated, and the template stands in for + // the live route of the hot export. + const liveRoutes = oldRoute + ? [oldRoute] + : ( + Object.values(router.routesById) as Array + ).filter( + (route) => + route._template && route.id.replace(/#[^:]*:/, ':') === routeId, + ) + const previousRoute = oldRoute ?? liveRoutes[0]?._template + + if (!previousRoute || previousRoute === newRoute) { + return false } // Generated route-tree options are not present on the freshly imported route // module, but they must stay on the live route before rebuilding indexes. - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions: Record = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) + const generatedRouteOptionKeys = [ + 'id', + 'path', + 'getParentRoute', + '_module', + '_uses', + ] - const oldHasShellComponent = 'shellComponent' in oldRoute.options + const oldHasShellComponent = 'shellComponent' in previousRoute.options const newHasShellComponent = 'shellComponent' in newRoute.options const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent @@ -58,28 +77,45 @@ function handleRouteUpdate( // so we must explicitly preserve the old reference. // Preserve component identity so React doesn't remount. // React Fast Refresh patches the function bodies in-place. + // Installations share their template's components. const componentKeys = '__TSR_COMPONENT_TYPES__' as unknown as Array if (preserveComponentIdentity) { componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] + if (key in previousRoute.options && key in newRoute.options) { + newRoute.options[key] = previousRoute.options[key] } }) } - const nextOptions = { - ...newRoute.options, - ...generatedRouteOptions, + const updateRoute = (route: AnyRouteWithPrivateProps) => { + const nextOptions = { ...newRoute.options } + generatedRouteOptionKeys.forEach((key) => { + if (key in route.options) { + nextOptions[key] = route.options[key] + } + }) + route.options = nextOptions + route.update(nextOptions) } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) + liveRoutes.forEach((liveRoute) => { + updateRoute(liveRoute) + router._replaceRouteChunk(liveRoute, newRoute.lazyFn) + }) + if (!oldRoute) { + updateRoute(previousRoute) + } router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) + syncHotRouteExport(previousRoute) + if (!oldRoute) { + liveRoutes.forEach((liveRoute) => { + liveRoute._template = newRoute + }) + } router.resolvePathCache.clear() void router._refreshRoute?.() + return true function syncHotRouteExport(liveRoute: AnyRouteWithPrivateProps) { // routeTree.gen.ts mutates the original module export with generated diff --git a/packages/router-plugin/src/core/hmr/vite-adapter.ts b/packages/router-plugin/src/core/hmr/vite-adapter.ts index ba8d42a80a..3d4efe1a01 100644 --- a/packages/router-plugin/src/core/hmr/vite-adapter.ts +++ b/packages/router-plugin/src/core/hmr/vite-adapter.ts @@ -33,12 +33,12 @@ if (import.meta.hot) { if (initialRouteId) { hotData['tsr-route-id'] = initialRouteId } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { + if ( + initialRouteId && + typeof window !== 'undefined' && + window.__TSR_ROUTER__ && handleRouteUpdate(initialRouteId, Route) + ) { hotData['tsr-route-update-handled'] = Route } hot.accept((newModule) => { diff --git a/packages/router-plugin/src/core/hmr/webpack-adapter.ts b/packages/router-plugin/src/core/hmr/webpack-adapter.ts index eaf34ccfb1..e092daf5e1 100644 --- a/packages/router-plugin/src/core/hmr/webpack-adapter.ts +++ b/packages/router-plugin/src/core/hmr/webpack-adapter.ts @@ -73,12 +73,12 @@ if (import.meta.webpackHot) { if (routeId) { hotData['tsr-route-id'] = routeId } - const existingRoute = - typeof window !== 'undefined' && routeId - ? window.__TSR_ROUTER__?.routesById?.[routeId] - : undefined - if (routeId && existingRoute && existingRoute !== Route) { - (${handleRouteUpdateCode})(routeId, Route)${reactRefreshCall} + if ( + routeId && + typeof window !== 'undefined' && + window.__TSR_ROUTER__ && + (${handleRouteUpdateCode})(routeId, Route) + ) {${reactRefreshCall} } hot.dispose((data) => { if (routeId) { diff --git a/packages/router-plugin/src/core/router-generator-plugin.ts b/packages/router-plugin/src/core/router-generator-plugin.ts index 50dde9f55c..9cbd186db8 100644 --- a/packages/router-plugin/src/core/router-generator-plugin.ts +++ b/packages/router-plugin/src/core/router-generator-plugin.ts @@ -18,6 +18,9 @@ export function createRouterGeneratorPlugin( let ROOT: string = process.cwd() let userConfig: Config let generator: Generator + // Route modules: files outside the routes directory that change the route + // tree (package.json, manifests of mounted modules). Watchers add them. + let watchRouteModuleFiles: ((files: Array) => void) | undefined const getRoutesDirectoryPath = () => { return isAbsolute(userConfig.routesDirectory) @@ -57,6 +60,7 @@ export function createRouterGeneratorPlugin( try { await generator.run(generatorEvent) routerPluginContext.routesByFile = generator.getRoutesByFileMap() + watchRouteModuleFiles?.(generator.getRouteModuleWatchFiles()) } catch (e) { console.error(e) } @@ -76,6 +80,14 @@ export function createRouterGeneratorPlugin( initConfigAndGenerator({ root: config.root }) await generate() }, + configureServer(server) { + watchRouteModuleFiles = (files) => { + if (files.length) { + server.watcher.add(files) + } + } + watchRouteModuleFiles(generator.getRouteModuleWatchFiles()) + }, }, rspack(compiler) { initConfigAndGenerator() @@ -92,9 +104,22 @@ export function createRouterGeneratorPlugin( // rspack watcher doesn't register newly created files const routesDirectoryPath = getRoutesDirectoryPath() const chokidar = await import('chokidar') - handle = chokidar + const watcher = chokidar .watch(routesDirectoryPath, { ignoreInitial: true }) .on('add', (file) => generate({ file, event: 'create' })) + .on('change', (file) => { + if (generator.getRouteModuleWatchFiles().includes(file)) { + return generate({ file, event: 'update' }) + } + return undefined + }) + handle = watcher + watchRouteModuleFiles = (files) => { + if (files.length) { + watcher.add(files) + } + } + watchRouteModuleFiles(generator.getRouteModuleWatchFiles()) await generate() }) @@ -120,9 +145,22 @@ export function createRouterGeneratorPlugin( // webpack watcher doesn't register newly created files const routesDirectoryPath = getRoutesDirectoryPath() const chokidar = await import('chokidar') - handle = chokidar + const watcher = chokidar .watch(routesDirectoryPath, { ignoreInitial: true }) .on('add', (file) => generate({ file, event: 'create' })) + .on('change', (file) => { + if (generator.getRouteModuleWatchFiles().includes(file)) { + return generate({ file, event: 'update' }) + } + return undefined + }) + handle = watcher + watchRouteModuleFiles = (files) => { + if (files.length) { + watcher.add(files) + } + } + watchRouteModuleFiles(generator.getRouteModuleWatchFiles()) await generate() }) diff --git a/packages/router-plugin/tests/add-hmr.test.ts b/packages/router-plugin/tests/add-hmr.test.ts index 810f8e9b8d..215b0c0310 100644 --- a/packages/router-plugin/tests/add-hmr.test.ts +++ b/packages/router-plugin/tests/add-hmr.test.ts @@ -151,7 +151,7 @@ describe('add-hmr works', () => { const output = compileResult.code expect(output).toContain( - 'router._replaceRouteChunk(oldRoute, newRoute.lazyFn);', + 'router._replaceRouteChunk(liveRoute, newRoute.lazyFn);', ) expect(output).toContain('void router._refreshRoute?.();') expect(output).not.toContain('__routeContext') diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@true.tsx index c771483895..f09722725e 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@true.tsx @@ -44,17 +44,24 @@ if (import.meta.hot) { const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) { const router = window.__TSR_ROUTER__ const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return + const liveRoutes = oldRoute + ? [oldRoute] + : Object.values(router.routesById).filter( + (route) => + route._template && route.id.replace(/#[^:]*:/, ':') === routeId, + ) + const previousRoute = oldRoute ?? liveRoutes[0]?._template + if (!previousRoute || previousRoute === newRoute) { + return false } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options + const generatedRouteOptionKeys = [ + 'id', + 'path', + 'getParentRoute', + '_module', + '_uses', + ] + const oldHasShellComponent = 'shellComponent' in previousRoute.options const newHasShellComponent = 'shellComponent' in newRoute.options const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent @@ -67,19 +74,38 @@ if (import.meta.hot) { ] if (preserveComponentIdentity) { componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] + if (key in previousRoute.options && key in newRoute.options) { + newRoute.options[key] = previousRoute.options[key] } }) } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) + const updateRoute = (route) => { + const nextOptions = { ...newRoute.options } + generatedRouteOptionKeys.forEach((key) => { + if (key in route.options) { + nextOptions[key] = route.options[key] + } + }) + route.options = nextOptions + route.update(nextOptions) + } + liveRoutes.forEach((liveRoute) => { + updateRoute(liveRoute) + router._replaceRouteChunk(liveRoute, newRoute.lazyFn) + }) + if (!oldRoute) { + updateRoute(previousRoute) + } router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) + syncHotRouteExport(previousRoute) + if (!oldRoute) { + liveRoutes.forEach((liveRoute) => { + liveRoute._template = newRoute + }) + } router.resolvePathCache.clear() void router._refreshRoute?.() + return true function syncHotRouteExport(liveRoute) { newRoute.options = liveRoute.options newRoute.parentRoute = liveRoute.parentRoute @@ -93,12 +119,12 @@ if (import.meta.hot) { if (initialRouteId) { hotData['tsr-route-id'] = initialRouteId } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { + if ( + initialRouteId && + typeof window !== 'undefined' && + window.__TSR_ROUTER__ && handleRouteUpdate(initialRouteId, Route) + ) { hotData['tsr-route-update-handled'] = Route } hot.accept((newModule) => { diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@webpack-hot.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@webpack-hot.tsx index eb655d0287..547bc18788 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@webpack-hot.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/arrow-function@webpack-hot.tsx @@ -30,25 +30,31 @@ if (import.meta.webpackHot) { if (routeId) { hotData['tsr-route-id'] = routeId } - const existingRoute = - typeof window !== 'undefined' && routeId - ? window.__TSR_ROUTER__?.routesById?.[routeId] - : undefined - if (routeId && existingRoute && existingRoute !== Route) { - ;(function handleRouteUpdate(routeId, newRoute) { + if ( + routeId && + typeof window !== 'undefined' && + window.__TSR_ROUTER__ && + (function handleRouteUpdate(routeId, newRoute) { const router = window.__TSR_ROUTER__ const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return + const liveRoutes = oldRoute + ? [oldRoute] + : Object.values(router.routesById).filter( + (route) => + route._template && route.id.replace(/#[^:]*:/, ':') === routeId, + ) + const previousRoute = oldRoute ?? liveRoutes[0]?._template + if (!previousRoute || previousRoute === newRoute) { + return false } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options + const generatedRouteOptionKeys = [ + 'id', + 'path', + 'getParentRoute', + '_module', + '_uses', + ] + const oldHasShellComponent = 'shellComponent' in previousRoute.options const newHasShellComponent = 'shellComponent' in newRoute.options const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent @@ -61,19 +67,38 @@ if (import.meta.webpackHot) { ] if (preserveComponentIdentity) { componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] + if (key in previousRoute.options && key in newRoute.options) { + newRoute.options[key] = previousRoute.options[key] } }) } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) + const updateRoute = (route) => { + const nextOptions = { ...newRoute.options } + generatedRouteOptionKeys.forEach((key) => { + if (key in route.options) { + nextOptions[key] = route.options[key] + } + }) + route.options = nextOptions + route.update(nextOptions) + } + liveRoutes.forEach((liveRoute) => { + updateRoute(liveRoute) + router._replaceRouteChunk(liveRoute, newRoute.lazyFn) + }) + if (!oldRoute) { + updateRoute(previousRoute) + } router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) + syncHotRouteExport(previousRoute) + if (!oldRoute) { + liveRoutes.forEach((liveRoute) => { + liveRoute._template = newRoute + }) + } router.resolvePathCache.clear() void router._refreshRoute?.() + return true function syncHotRouteExport(liveRoute) { newRoute.options = liveRoute.options newRoute.parentRoute = liveRoute.parentRoute @@ -83,6 +108,7 @@ if (import.meta.webpackHot) { newRoute._to = liveRoute._to } })(routeId, Route) + ) { try { const tsrReactRefreshUtils = typeof __react_refresh_utils__ !== 'undefined' diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/createFileRoute-lowercase-components@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/createFileRoute-lowercase-components@true.tsx index bf94d5d3fd..607c1f118a 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/createFileRoute-lowercase-components@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/createFileRoute-lowercase-components@true.tsx @@ -63,17 +63,24 @@ if (import.meta.hot) { const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) { const router = window.__TSR_ROUTER__ const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return + const liveRoutes = oldRoute + ? [oldRoute] + : Object.values(router.routesById).filter( + (route) => + route._template && route.id.replace(/#[^:]*:/, ':') === routeId, + ) + const previousRoute = oldRoute ?? liveRoutes[0]?._template + if (!previousRoute || previousRoute === newRoute) { + return false } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options + const generatedRouteOptionKeys = [ + 'id', + 'path', + 'getParentRoute', + '_module', + '_uses', + ] + const oldHasShellComponent = 'shellComponent' in previousRoute.options const newHasShellComponent = 'shellComponent' in newRoute.options const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent @@ -86,19 +93,38 @@ if (import.meta.hot) { ] if (preserveComponentIdentity) { componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] + if (key in previousRoute.options && key in newRoute.options) { + newRoute.options[key] = previousRoute.options[key] } }) } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) + const updateRoute = (route) => { + const nextOptions = { ...newRoute.options } + generatedRouteOptionKeys.forEach((key) => { + if (key in route.options) { + nextOptions[key] = route.options[key] + } + }) + route.options = nextOptions + route.update(nextOptions) + } + liveRoutes.forEach((liveRoute) => { + updateRoute(liveRoute) + router._replaceRouteChunk(liveRoute, newRoute.lazyFn) + }) + if (!oldRoute) { + updateRoute(previousRoute) + } router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) + syncHotRouteExport(previousRoute) + if (!oldRoute) { + liveRoutes.forEach((liveRoute) => { + liveRoute._template = newRoute + }) + } router.resolvePathCache.clear() void router._refreshRoute?.() + return true function syncHotRouteExport(liveRoute) { newRoute.options = liveRoute.options newRoute.parentRoute = liveRoute.parentRoute @@ -112,12 +138,12 @@ if (import.meta.hot) { if (initialRouteId) { hotData['tsr-route-id'] = initialRouteId } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { + if ( + initialRouteId && + typeof window !== 'undefined' && + window.__TSR_ROUTER__ && handleRouteUpdate(initialRouteId, Route) + ) { hotData['tsr-route-update-handled'] = Route } hot.accept((newModule) => { diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-inline-component@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-inline-component@true.tsx index f12187ccd1..24ff42cb43 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-inline-component@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-inline-component@true.tsx @@ -29,17 +29,24 @@ if (import.meta.hot) { const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) { const router = window.__TSR_ROUTER__ const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return + const liveRoutes = oldRoute + ? [oldRoute] + : Object.values(router.routesById).filter( + (route) => + route._template && route.id.replace(/#[^:]*:/, ':') === routeId, + ) + const previousRoute = oldRoute ?? liveRoutes[0]?._template + if (!previousRoute || previousRoute === newRoute) { + return false } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options + const generatedRouteOptionKeys = [ + 'id', + 'path', + 'getParentRoute', + '_module', + '_uses', + ] + const oldHasShellComponent = 'shellComponent' in previousRoute.options const newHasShellComponent = 'shellComponent' in newRoute.options const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent @@ -52,19 +59,38 @@ if (import.meta.hot) { ] if (preserveComponentIdentity) { componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] + if (key in previousRoute.options && key in newRoute.options) { + newRoute.options[key] = previousRoute.options[key] } }) } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) + const updateRoute = (route) => { + const nextOptions = { ...newRoute.options } + generatedRouteOptionKeys.forEach((key) => { + if (key in route.options) { + nextOptions[key] = route.options[key] + } + }) + route.options = nextOptions + route.update(nextOptions) + } + liveRoutes.forEach((liveRoute) => { + updateRoute(liveRoute) + router._replaceRouteChunk(liveRoute, newRoute.lazyFn) + }) + if (!oldRoute) { + updateRoute(previousRoute) + } router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) + syncHotRouteExport(previousRoute) + if (!oldRoute) { + liveRoutes.forEach((liveRoute) => { + liveRoute._template = newRoute + }) + } router.resolvePathCache.clear() void router._refreshRoute?.() + return true function syncHotRouteExport(liveRoute) { newRoute.options = liveRoute.options newRoute.parentRoute = liveRoute.parentRoute @@ -78,12 +104,12 @@ if (import.meta.hot) { if (initialRouteId) { hotData['tsr-route-id'] = initialRouteId } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { + if ( + initialRouteId && + typeof window !== 'undefined' && + window.__TSR_ROUTER__ && handleRouteUpdate(initialRouteId, Route) + ) { hotData['tsr-route-update-handled'] = Route } hot.accept((newModule) => { diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-lowercase-components@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-lowercase-components@true.tsx index 9f8df0d43f..ec669709ed 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-lowercase-components@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute-lowercase-components@true.tsx @@ -45,17 +45,24 @@ if (import.meta.hot) { const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) { const router = window.__TSR_ROUTER__ const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return + const liveRoutes = oldRoute + ? [oldRoute] + : Object.values(router.routesById).filter( + (route) => + route._template && route.id.replace(/#[^:]*:/, ':') === routeId, + ) + const previousRoute = oldRoute ?? liveRoutes[0]?._template + if (!previousRoute || previousRoute === newRoute) { + return false } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options + const generatedRouteOptionKeys = [ + 'id', + 'path', + 'getParentRoute', + '_module', + '_uses', + ] + const oldHasShellComponent = 'shellComponent' in previousRoute.options const newHasShellComponent = 'shellComponent' in newRoute.options const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent @@ -68,19 +75,38 @@ if (import.meta.hot) { ] if (preserveComponentIdentity) { componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] + if (key in previousRoute.options && key in newRoute.options) { + newRoute.options[key] = previousRoute.options[key] } }) } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) + const updateRoute = (route) => { + const nextOptions = { ...newRoute.options } + generatedRouteOptionKeys.forEach((key) => { + if (key in route.options) { + nextOptions[key] = route.options[key] + } + }) + route.options = nextOptions + route.update(nextOptions) + } + liveRoutes.forEach((liveRoute) => { + updateRoute(liveRoute) + router._replaceRouteChunk(liveRoute, newRoute.lazyFn) + }) + if (!oldRoute) { + updateRoute(previousRoute) + } router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) + syncHotRouteExport(previousRoute) + if (!oldRoute) { + liveRoutes.forEach((liveRoute) => { + liveRoute._template = newRoute + }) + } router.resolvePathCache.clear() void router._refreshRoute?.() + return true function syncHotRouteExport(liveRoute) { newRoute.options = liveRoute.options newRoute.parentRoute = liveRoute.parentRoute @@ -94,12 +120,12 @@ if (import.meta.hot) { if (initialRouteId) { hotData['tsr-route-id'] = initialRouteId } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { + if ( + initialRouteId && + typeof window !== 'undefined' && + window.__TSR_ROUTER__ && handleRouteUpdate(initialRouteId, Route) + ) { hotData['tsr-route-update-handled'] = Route } hot.accept((newModule) => { diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute@true.tsx index 859380ef53..a282be1ddf 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRoute@true.tsx @@ -28,17 +28,24 @@ if (import.meta.hot) { const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) { const router = window.__TSR_ROUTER__ const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return + const liveRoutes = oldRoute + ? [oldRoute] + : Object.values(router.routesById).filter( + (route) => + route._template && route.id.replace(/#[^:]*:/, ':') === routeId, + ) + const previousRoute = oldRoute ?? liveRoutes[0]?._template + if (!previousRoute || previousRoute === newRoute) { + return false } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options + const generatedRouteOptionKeys = [ + 'id', + 'path', + 'getParentRoute', + '_module', + '_uses', + ] + const oldHasShellComponent = 'shellComponent' in previousRoute.options const newHasShellComponent = 'shellComponent' in newRoute.options const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent @@ -51,19 +58,38 @@ if (import.meta.hot) { ] if (preserveComponentIdentity) { componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] + if (key in previousRoute.options && key in newRoute.options) { + newRoute.options[key] = previousRoute.options[key] } }) } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) + const updateRoute = (route) => { + const nextOptions = { ...newRoute.options } + generatedRouteOptionKeys.forEach((key) => { + if (key in route.options) { + nextOptions[key] = route.options[key] + } + }) + route.options = nextOptions + route.update(nextOptions) + } + liveRoutes.forEach((liveRoute) => { + updateRoute(liveRoute) + router._replaceRouteChunk(liveRoute, newRoute.lazyFn) + }) + if (!oldRoute) { + updateRoute(previousRoute) + } router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) + syncHotRouteExport(previousRoute) + if (!oldRoute) { + liveRoutes.forEach((liveRoute) => { + liveRoute._template = newRoute + }) + } router.resolvePathCache.clear() void router._refreshRoute?.() + return true function syncHotRouteExport(liveRoute) { newRoute.options = liveRoute.options newRoute.parentRoute = liveRoute.parentRoute @@ -77,12 +103,12 @@ if (import.meta.hot) { if (initialRouteId) { hotData['tsr-route-id'] = initialRouteId } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { + if ( + initialRouteId && + typeof window !== 'undefined' && + window.__TSR_ROUTER__ && handleRouteUpdate(initialRouteId, Route) + ) { hotData['tsr-route-update-handled'] = Route } hot.accept((newModule) => { diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRouteWithContext-type-args@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRouteWithContext-type-args@true.tsx index 9d942f65a2..2a3fe2203e 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRouteWithContext-type-args@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/createRootRouteWithContext-type-args@true.tsx @@ -36,17 +36,24 @@ if (import.meta.hot) { const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) { const router = window.__TSR_ROUTER__ const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return + const liveRoutes = oldRoute + ? [oldRoute] + : Object.values(router.routesById).filter( + (route) => + route._template && route.id.replace(/#[^:]*:/, ':') === routeId, + ) + const previousRoute = oldRoute ?? liveRoutes[0]?._template + if (!previousRoute || previousRoute === newRoute) { + return false } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options + const generatedRouteOptionKeys = [ + 'id', + 'path', + 'getParentRoute', + '_module', + '_uses', + ] + const oldHasShellComponent = 'shellComponent' in previousRoute.options const newHasShellComponent = 'shellComponent' in newRoute.options const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent @@ -59,19 +66,38 @@ if (import.meta.hot) { ] if (preserveComponentIdentity) { componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] + if (key in previousRoute.options && key in newRoute.options) { + newRoute.options[key] = previousRoute.options[key] } }) } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) + const updateRoute = (route) => { + const nextOptions = { ...newRoute.options } + generatedRouteOptionKeys.forEach((key) => { + if (key in route.options) { + nextOptions[key] = route.options[key] + } + }) + route.options = nextOptions + route.update(nextOptions) + } + liveRoutes.forEach((liveRoute) => { + updateRoute(liveRoute) + router._replaceRouteChunk(liveRoute, newRoute.lazyFn) + }) + if (!oldRoute) { + updateRoute(previousRoute) + } router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) + syncHotRouteExport(previousRoute) + if (!oldRoute) { + liveRoutes.forEach((liveRoute) => { + liveRoute._template = newRoute + }) + } router.resolvePathCache.clear() void router._refreshRoute?.() + return true function syncHotRouteExport(liveRoute) { newRoute.options = liveRoute.options newRoute.parentRoute = liveRoute.parentRoute @@ -85,12 +111,12 @@ if (import.meta.hot) { if (initialRouteId) { hotData['tsr-route-id'] = initialRouteId } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { + if ( + initialRouteId && + typeof window !== 'undefined' && + window.__TSR_ROUTER__ && handleRouteUpdate(initialRouteId, Route) + ) { hotData['tsr-route-update-handled'] = Route } hot.accept((newModule) => { diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/explicit-undefined-component@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/explicit-undefined-component@true.tsx index 555c8fdd6c..c9fa437474 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/explicit-undefined-component@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/explicit-undefined-component@true.tsx @@ -27,17 +27,24 @@ if (import.meta.hot) { const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) { const router = window.__TSR_ROUTER__ const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return + const liveRoutes = oldRoute + ? [oldRoute] + : Object.values(router.routesById).filter( + (route) => + route._template && route.id.replace(/#[^:]*:/, ':') === routeId, + ) + const previousRoute = oldRoute ?? liveRoutes[0]?._template + if (!previousRoute || previousRoute === newRoute) { + return false } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options + const generatedRouteOptionKeys = [ + 'id', + 'path', + 'getParentRoute', + '_module', + '_uses', + ] + const oldHasShellComponent = 'shellComponent' in previousRoute.options const newHasShellComponent = 'shellComponent' in newRoute.options const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent @@ -50,19 +57,38 @@ if (import.meta.hot) { ] if (preserveComponentIdentity) { componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] + if (key in previousRoute.options && key in newRoute.options) { + newRoute.options[key] = previousRoute.options[key] } }) } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) + const updateRoute = (route) => { + const nextOptions = { ...newRoute.options } + generatedRouteOptionKeys.forEach((key) => { + if (key in route.options) { + nextOptions[key] = route.options[key] + } + }) + route.options = nextOptions + route.update(nextOptions) + } + liveRoutes.forEach((liveRoute) => { + updateRoute(liveRoute) + router._replaceRouteChunk(liveRoute, newRoute.lazyFn) + }) + if (!oldRoute) { + updateRoute(previousRoute) + } router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) + syncHotRouteExport(previousRoute) + if (!oldRoute) { + liveRoutes.forEach((liveRoute) => { + liveRoute._template = newRoute + }) + } router.resolvePathCache.clear() void router._refreshRoute?.() + return true function syncHotRouteExport(liveRoute) { newRoute.options = liveRoute.options newRoute.parentRoute = liveRoute.parentRoute @@ -76,12 +102,12 @@ if (import.meta.hot) { if (initialRouteId) { hotData['tsr-route-id'] = initialRouteId } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { + if ( + initialRouteId && + typeof window !== 'undefined' && + window.__TSR_ROUTER__ && handleRouteUpdate(initialRouteId, Route) + ) { hotData['tsr-route-update-handled'] = Route } hot.accept((newModule) => { diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/function-declaration@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/function-declaration@true.tsx index 9e27af7d69..54f0b976c2 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/function-declaration@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/function-declaration@true.tsx @@ -44,17 +44,24 @@ if (import.meta.hot) { const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) { const router = window.__TSR_ROUTER__ const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return + const liveRoutes = oldRoute + ? [oldRoute] + : Object.values(router.routesById).filter( + (route) => + route._template && route.id.replace(/#[^:]*:/, ':') === routeId, + ) + const previousRoute = oldRoute ?? liveRoutes[0]?._template + if (!previousRoute || previousRoute === newRoute) { + return false } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options + const generatedRouteOptionKeys = [ + 'id', + 'path', + 'getParentRoute', + '_module', + '_uses', + ] + const oldHasShellComponent = 'shellComponent' in previousRoute.options const newHasShellComponent = 'shellComponent' in newRoute.options const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent @@ -67,19 +74,38 @@ if (import.meta.hot) { ] if (preserveComponentIdentity) { componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] + if (key in previousRoute.options && key in newRoute.options) { + newRoute.options[key] = previousRoute.options[key] } }) } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) + const updateRoute = (route) => { + const nextOptions = { ...newRoute.options } + generatedRouteOptionKeys.forEach((key) => { + if (key in route.options) { + nextOptions[key] = route.options[key] + } + }) + route.options = nextOptions + route.update(nextOptions) + } + liveRoutes.forEach((liveRoute) => { + updateRoute(liveRoute) + router._replaceRouteChunk(liveRoute, newRoute.lazyFn) + }) + if (!oldRoute) { + updateRoute(previousRoute) + } router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) + syncHotRouteExport(previousRoute) + if (!oldRoute) { + liveRoutes.forEach((liveRoute) => { + liveRoute._template = newRoute + }) + } router.resolvePathCache.clear() void router._refreshRoute?.() + return true function syncHotRouteExport(liveRoute) { newRoute.options = liveRoute.options newRoute.parentRoute = liveRoute.parentRoute @@ -93,12 +119,12 @@ if (import.meta.hot) { if (initialRouteId) { hotData['tsr-route-id'] = initialRouteId } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { + if ( + initialRouteId && + typeof window !== 'undefined' && + window.__TSR_ROUTER__ && handleRouteUpdate(initialRouteId, Route) + ) { hotData['tsr-route-update-handled'] = Route } hot.accept((newModule) => { diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/multi-component@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/multi-component@true.tsx index 1a134b88da..119c3d54d3 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/multi-component@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/multi-component@true.tsx @@ -59,17 +59,24 @@ if (import.meta.hot) { const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) { const router = window.__TSR_ROUTER__ const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return + const liveRoutes = oldRoute + ? [oldRoute] + : Object.values(router.routesById).filter( + (route) => + route._template && route.id.replace(/#[^:]*:/, ':') === routeId, + ) + const previousRoute = oldRoute ?? liveRoutes[0]?._template + if (!previousRoute || previousRoute === newRoute) { + return false } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options + const generatedRouteOptionKeys = [ + 'id', + 'path', + 'getParentRoute', + '_module', + '_uses', + ] + const oldHasShellComponent = 'shellComponent' in previousRoute.options const newHasShellComponent = 'shellComponent' in newRoute.options const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent @@ -82,19 +89,38 @@ if (import.meta.hot) { ] if (preserveComponentIdentity) { componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] + if (key in previousRoute.options && key in newRoute.options) { + newRoute.options[key] = previousRoute.options[key] } }) } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) + const updateRoute = (route) => { + const nextOptions = { ...newRoute.options } + generatedRouteOptionKeys.forEach((key) => { + if (key in route.options) { + nextOptions[key] = route.options[key] + } + }) + route.options = nextOptions + route.update(nextOptions) + } + liveRoutes.forEach((liveRoute) => { + updateRoute(liveRoute) + router._replaceRouteChunk(liveRoute, newRoute.lazyFn) + }) + if (!oldRoute) { + updateRoute(previousRoute) + } router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) + syncHotRouteExport(previousRoute) + if (!oldRoute) { + liveRoutes.forEach((liveRoute) => { + liveRoute._template = newRoute + }) + } router.resolvePathCache.clear() void router._refreshRoute?.() + return true function syncHotRouteExport(liveRoute) { newRoute.options = liveRoute.options newRoute.parentRoute = liveRoute.parentRoute @@ -108,12 +134,12 @@ if (import.meta.hot) { if (initialRouteId) { hotData['tsr-route-id'] = initialRouteId } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { + if ( + initialRouteId && + typeof window !== 'undefined' && + window.__TSR_ROUTER__ && handleRouteUpdate(initialRouteId, Route) + ) { hotData['tsr-route-update-handled'] = Route } hot.accept((newModule) => { diff --git a/packages/router-plugin/tests/add-hmr/snapshots/react/string-literal-keys@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/react/string-literal-keys@true.tsx index b3bc82d69e..8ec72b3cdd 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/react/string-literal-keys@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/react/string-literal-keys@true.tsx @@ -59,17 +59,24 @@ if (import.meta.hot) { const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) { const router = window.__TSR_ROUTER__ const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return + const liveRoutes = oldRoute + ? [oldRoute] + : Object.values(router.routesById).filter( + (route) => + route._template && route.id.replace(/#[^:]*:/, ':') === routeId, + ) + const previousRoute = oldRoute ?? liveRoutes[0]?._template + if (!previousRoute || previousRoute === newRoute) { + return false } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options + const generatedRouteOptionKeys = [ + 'id', + 'path', + 'getParentRoute', + '_module', + '_uses', + ] + const oldHasShellComponent = 'shellComponent' in previousRoute.options const newHasShellComponent = 'shellComponent' in newRoute.options const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent @@ -82,19 +89,38 @@ if (import.meta.hot) { ] if (preserveComponentIdentity) { componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] + if (key in previousRoute.options && key in newRoute.options) { + newRoute.options[key] = previousRoute.options[key] } }) } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) + const updateRoute = (route) => { + const nextOptions = { ...newRoute.options } + generatedRouteOptionKeys.forEach((key) => { + if (key in route.options) { + nextOptions[key] = route.options[key] + } + }) + route.options = nextOptions + route.update(nextOptions) + } + liveRoutes.forEach((liveRoute) => { + updateRoute(liveRoute) + router._replaceRouteChunk(liveRoute, newRoute.lazyFn) + }) + if (!oldRoute) { + updateRoute(previousRoute) + } router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) + syncHotRouteExport(previousRoute) + if (!oldRoute) { + liveRoutes.forEach((liveRoute) => { + liveRoute._template = newRoute + }) + } router.resolvePathCache.clear() void router._refreshRoute?.() + return true function syncHotRouteExport(liveRoute) { newRoute.options = liveRoute.options newRoute.parentRoute = liveRoute.parentRoute @@ -108,12 +134,12 @@ if (import.meta.hot) { if (initialRouteId) { hotData['tsr-route-id'] = initialRouteId } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { + if ( + initialRouteId && + typeof window !== 'undefined' && + window.__TSR_ROUTER__ && handleRouteUpdate(initialRouteId, Route) + ) { hotData['tsr-route-update-handled'] = Route } hot.accept((newModule) => { diff --git a/packages/router-plugin/tests/add-hmr/snapshots/solid/arrow-function@true.tsx b/packages/router-plugin/tests/add-hmr/snapshots/solid/arrow-function@true.tsx index 05fa745c4b..e6c1902915 100644 --- a/packages/router-plugin/tests/add-hmr/snapshots/solid/arrow-function@true.tsx +++ b/packages/router-plugin/tests/add-hmr/snapshots/solid/arrow-function@true.tsx @@ -13,36 +13,62 @@ if (import.meta.hot) { const handleRouteUpdate = function handleRouteUpdate(routeId, newRoute) { const router = window.__TSR_ROUTER__ const oldRoute = router.routesById[routeId] - if (!oldRoute) { - return + const liveRoutes = oldRoute + ? [oldRoute] + : Object.values(router.routesById).filter( + (route) => + route._template && route.id.replace(/#[^:]*:/, ':') === routeId, + ) + const previousRoute = oldRoute ?? liveRoutes[0]?._template + if (!previousRoute || previousRoute === newRoute) { + return false } - const generatedRouteOptionKeys = new Set(['id', 'path', 'getParentRoute']) - const generatedRouteOptions = {} - generatedRouteOptionKeys.forEach((key) => { - if (key in oldRoute.options) { - generatedRouteOptions[key] = oldRoute.options[key] - } - }) - const oldHasShellComponent = 'shellComponent' in oldRoute.options + const generatedRouteOptionKeys = [ + 'id', + 'path', + 'getParentRoute', + '_module', + '_uses', + ] + const oldHasShellComponent = 'shellComponent' in previousRoute.options const newHasShellComponent = 'shellComponent' in newRoute.options const preserveComponentIdentity = oldHasShellComponent === newHasShellComponent const componentKeys = [] if (preserveComponentIdentity) { componentKeys.forEach((key) => { - if (key in oldRoute.options && key in newRoute.options) { - newRoute.options[key] = oldRoute.options[key] + if (key in previousRoute.options && key in newRoute.options) { + newRoute.options[key] = previousRoute.options[key] } }) } - const nextOptions = { ...newRoute.options, ...generatedRouteOptions } - oldRoute.options = nextOptions - oldRoute.update(nextOptions) - router._replaceRouteChunk(oldRoute, newRoute.lazyFn) + const updateRoute = (route) => { + const nextOptions = { ...newRoute.options } + generatedRouteOptionKeys.forEach((key) => { + if (key in route.options) { + nextOptions[key] = route.options[key] + } + }) + route.options = nextOptions + route.update(nextOptions) + } + liveRoutes.forEach((liveRoute) => { + updateRoute(liveRoute) + router._replaceRouteChunk(liveRoute, newRoute.lazyFn) + }) + if (!oldRoute) { + updateRoute(previousRoute) + } router.setRoutes(router.buildRouteTree()) - syncHotRouteExport(oldRoute) + syncHotRouteExport(previousRoute) + if (!oldRoute) { + liveRoutes.forEach((liveRoute) => { + liveRoute._template = newRoute + }) + } router.resolvePathCache.clear() void router._refreshRoute?.() + return true function syncHotRouteExport(liveRoute) { newRoute.options = liveRoute.options newRoute.parentRoute = liveRoute.parentRoute @@ -56,12 +82,12 @@ if (import.meta.hot) { if (initialRouteId) { hotData['tsr-route-id'] = initialRouteId } - const existingRoute = - typeof window !== 'undefined' && initialRouteId - ? window.__TSR_ROUTER__?.routesById?.[initialRouteId] - : undefined - if (initialRouteId && existingRoute && existingRoute !== Route) { + if ( + initialRouteId && + typeof window !== 'undefined' && + window.__TSR_ROUTER__ && handleRouteUpdate(initialRouteId, Route) + ) { hotData['tsr-route-update-handled'] = Route } hot.accept((newModule) => { diff --git a/packages/router-plugin/tests/code-splitter.test.ts b/packages/router-plugin/tests/code-splitter.test.ts index 96807e4d42..af1aac51e4 100644 --- a/packages/router-plugin/tests/code-splitter.test.ts +++ b/packages/router-plugin/tests/code-splitter.test.ts @@ -59,114 +59,117 @@ const testGroups: Array<{ name: string; groupings: CodeSplitGroupings }> = [ ] describe('code-splitter works', () => { - describe.each(frameworks)('FRAMEWORK=%s', (framework) => { - describe.each(testGroups)( - 'SPLIT_GROUP=$name', - async ({ groupings: grouping, name: groupName }) => { - const dirs = getFrameworkDir(framework) - const filenames = await readdir(dirs.files) + describe.each([...frameworks, 'vue'] as const)( + 'FRAMEWORK=%s', + (framework) => { + describe.each(testGroups)( + 'SPLIT_GROUP=$name', + async ({ groupings: grouping, name: groupName }) => { + const dirs = getFrameworkDir(framework) + const filenames = await readdir(dirs.files) - it.each(filenames)( - `should compile "reference" for "%s"`, - async (filename) => { - const file = await readFile(path.join(dirs.files, filename)) - const code = file.toString() + it.each(filenames)( + `should compile "reference" for "%s"`, + async (filename) => { + const file = await readFile(path.join(dirs.files, filename)) + const code = file.toString() - const sharedBindings = computeSharedBindings({ - code, - codeSplitGroupings: grouping, - }) - - const compileResult = compileCodeSplitReferenceRoute({ - code, - filename, - id: filename, - addHmr: false, - codeSplitGroupings: grouping, - targetFramework: framework, - sharedBindings: - sharedBindings.size > 0 ? sharedBindings : undefined, - }) - - await expect( - await formatSnapshot(compileResult?.code || code, filename), - ).toMatchFileSnapshot( - path.join(dirs.snapshots, groupName, filename), - ) - }, - ) - - it.each(filenames)( - `should compile "virtual" for "%s"`, - async (filename) => { - const file = await readFile(path.join(dirs.files, filename)) - const code = file.toString() - - const sharedBindings = computeSharedBindings({ - code, - codeSplitGroupings: grouping, - }) - - for (const targets of grouping) { - const ident = createIdentifier(targets) - - const splitResult = compileCodeSplitVirtualRoute({ + const sharedBindings = computeSharedBindings({ code, - filename: `${filename}?${ident}`, - splitTargets: targets, + codeSplitGroupings: grouping, + }) + + const compileResult = compileCodeSplitReferenceRoute({ + code, + filename, + id: filename, + addHmr: false, + codeSplitGroupings: grouping, + targetFramework: framework, sharedBindings: sharedBindings.size > 0 ? sharedBindings : undefined, }) + await expect( + await formatSnapshot(compileResult?.code || code, filename), + ).toMatchFileSnapshot( + path.join(dirs.snapshots, groupName, filename), + ) + }, + ) + + it.each(filenames)( + `should compile "virtual" for "%s"`, + async (filename) => { + const file = await readFile(path.join(dirs.files, filename)) + const code = file.toString() + + const sharedBindings = computeSharedBindings({ + code, + codeSplitGroupings: grouping, + }) + + for (const targets of grouping) { + const ident = createIdentifier(targets) + + const splitResult = compileCodeSplitVirtualRoute({ + code, + filename: `${filename}?${ident}`, + splitTargets: targets, + sharedBindings: + sharedBindings.size > 0 ? sharedBindings : undefined, + }) + + const snapshotFilename = path.join( + dirs.snapshots, + groupName, + `${filename.replace('.tsx', '')}@${ident}.tsx`, + ) + await expect( + await formatSnapshot(splitResult.code, filename), + ).toMatchFileSnapshot(snapshotFilename) + } + }, + ) + + it.each(filenames)( + `should compile "shared" for "%s"`, + async (filename) => { + const file = await readFile(path.join(dirs.files, filename)) + const code = file.toString() + + const sharedBindings = computeSharedBindings({ + code, + codeSplitGroupings: grouping, + }) + const snapshotFilename = path.join( dirs.snapshots, groupName, - `${filename.replace('.tsx', '')}@${ident}.tsx`, + `${filename.replace('.tsx', '')}@shared.tsx`, ) + + if (sharedBindings.size === 0) { + // No shared module — snapshot should be empty string + await expect('').toMatchFileSnapshot(snapshotFilename) + return + } + + const sharedResult = compileCodeSplitSharedRoute({ + code, + sharedBindings, + filename: `${filename}?tsr-shared=1`, + }) + await expect( - await formatSnapshot(splitResult.code, filename), + await formatSnapshot(sharedResult.code, filename), ).toMatchFileSnapshot(snapshotFilename) - } - }, - ) - - it.each(filenames)( - `should compile "shared" for "%s"`, - async (filename) => { - const file = await readFile(path.join(dirs.files, filename)) - const code = file.toString() - - const sharedBindings = computeSharedBindings({ - code, - codeSplitGroupings: grouping, - }) - - const snapshotFilename = path.join( - dirs.snapshots, - groupName, - `${filename.replace('.tsx', '')}@shared.tsx`, - ) - - if (sharedBindings.size === 0) { - // No shared module — snapshot should be empty string - await expect('').toMatchFileSnapshot(snapshotFilename) - return - } - - const sharedResult = compileCodeSplitSharedRoute({ - code, - sharedBindings, - filename: `${filename}?tsr-shared=1`, - }) - - await expect( - await formatSnapshot(sharedResult.code, filename), - ).toMatchFileSnapshot(snapshotFilename) - }, - ) - }, - ) - }) + }, + ) + }, + ) + }, + ) }) describe('React Refresh virtual route compiler plugin', () => { diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline-memo-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline-memo-component.tsx new file mode 100644 index 0000000000..d258b0d353 --- /dev/null +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline-memo-component.tsx @@ -0,0 +1,7 @@ +const $$splitComponentImporter = () => + import('inline-memo-component.tsx?tsr-split=component') +import { lazyRouteComponent } from '@tanstack/react-router' +import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/')({ + component: lazyRouteComponent($$splitComponentImporter, 'component'), +}) diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline-memo-component@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline-memo-component@component.tsx new file mode 100644 index 0000000000..cd233c2328 --- /dev/null +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline-memo-component@component.tsx @@ -0,0 +1,6 @@ +import { memo } from 'react' +const SplitComponent = memo(() => { + const label: string = 'Inline memo component' + return
{label}
+}) +export { SplitComponent as component } diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline-memo-component@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline-memo-component@errorComponent.tsx new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline-memo-component@notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline-memo-component@notFoundComponent.tsx new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline-memo-component@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/1-default/inline-memo-component@shared.tsx new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline-memo-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline-memo-component.tsx new file mode 100644 index 0000000000..564de9a8f6 --- /dev/null +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline-memo-component.tsx @@ -0,0 +1,7 @@ +const $$splitComponentImporter = () => + import('inline-memo-component.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') +import { lazyRouteComponent } from '@tanstack/react-router' +import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/')({ + component: lazyRouteComponent($$splitComponentImporter, 'component'), +}) diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline-memo-component@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline-memo-component@component---errorComponent---notFoundComponent---pendingComponent.tsx new file mode 100644 index 0000000000..cd233c2328 --- /dev/null +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline-memo-component@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -0,0 +1,6 @@ +import { memo } from 'react' +const SplitComponent = memo(() => { + const label: string = 'Inline memo component' + return
{label}
+}) +export { SplitComponent as component } diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline-memo-component@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline-memo-component@loader.tsx new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline-memo-component@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/2-components-combined-loader-separate/inline-memo-component@shared.tsx new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline-memo-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline-memo-component.tsx new file mode 100644 index 0000000000..971872b321 --- /dev/null +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline-memo-component.tsx @@ -0,0 +1,7 @@ +const $$splitComponentImporter = () => + import('inline-memo-component.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') +import { lazyRouteComponent } from '@tanstack/react-router' +import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/')({ + component: lazyRouteComponent($$splitComponentImporter, 'component'), +}) diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline-memo-component@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline-memo-component@component---loader---notFoundComponent---pendingComponent.tsx new file mode 100644 index 0000000000..cd233c2328 --- /dev/null +++ b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline-memo-component@component---loader---notFoundComponent---pendingComponent.tsx @@ -0,0 +1,6 @@ +import { memo } from 'react' +const SplitComponent = memo(() => { + const label: string = 'Inline memo component' + return
{label}
+}) +export { SplitComponent as component } diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline-memo-component@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline-memo-component@errorComponent.tsx new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline-memo-component@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/react/3-all-combined-errorComponent-separate/inline-memo-component@shared.tsx new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/router-plugin/tests/code-splitter/snapshots/vue/1-default/inline-define-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/vue/1-default/inline-define-component.tsx new file mode 100644 index 0000000000..ca23589440 --- /dev/null +++ b/packages/router-plugin/tests/code-splitter/snapshots/vue/1-default/inline-define-component.tsx @@ -0,0 +1,7 @@ +const $$splitComponentImporter = () => + import('inline-define-component.tsx?tsr-split=component') +import { lazyRouteComponent } from '@tanstack/vue-router' +import { createFileRoute } from '@tanstack/vue-router' +export const Route = createFileRoute('/')({ + component: lazyRouteComponent($$splitComponentImporter, 'component'), +}) diff --git a/packages/router-plugin/tests/code-splitter/snapshots/vue/1-default/inline-define-component@component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/vue/1-default/inline-define-component@component.tsx new file mode 100644 index 0000000000..db88804cf9 --- /dev/null +++ b/packages/router-plugin/tests/code-splitter/snapshots/vue/1-default/inline-define-component@component.tsx @@ -0,0 +1,8 @@ +import { defineComponent } from 'vue' +const SplitComponent = defineComponent({ + setup() { + const label: string = 'Inline Vue component' + return () =>
{label}
+ }, +}) +export { SplitComponent as component } diff --git a/packages/router-plugin/tests/code-splitter/snapshots/vue/1-default/inline-define-component@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/vue/1-default/inline-define-component@errorComponent.tsx new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/router-plugin/tests/code-splitter/snapshots/vue/1-default/inline-define-component@notFoundComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/vue/1-default/inline-define-component@notFoundComponent.tsx new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/router-plugin/tests/code-splitter/snapshots/vue/1-default/inline-define-component@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/vue/1-default/inline-define-component@shared.tsx new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/router-plugin/tests/code-splitter/snapshots/vue/2-components-combined-loader-separate/inline-define-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/vue/2-components-combined-loader-separate/inline-define-component.tsx new file mode 100644 index 0000000000..c21a096049 --- /dev/null +++ b/packages/router-plugin/tests/code-splitter/snapshots/vue/2-components-combined-loader-separate/inline-define-component.tsx @@ -0,0 +1,7 @@ +const $$splitComponentImporter = () => + import('inline-define-component.tsx?tsr-split=component---errorComponent---notFoundComponent---pendingComponent') +import { lazyRouteComponent } from '@tanstack/vue-router' +import { createFileRoute } from '@tanstack/vue-router' +export const Route = createFileRoute('/')({ + component: lazyRouteComponent($$splitComponentImporter, 'component'), +}) diff --git a/packages/router-plugin/tests/code-splitter/snapshots/vue/2-components-combined-loader-separate/inline-define-component@component---errorComponent---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/vue/2-components-combined-loader-separate/inline-define-component@component---errorComponent---notFoundComponent---pendingComponent.tsx new file mode 100644 index 0000000000..db88804cf9 --- /dev/null +++ b/packages/router-plugin/tests/code-splitter/snapshots/vue/2-components-combined-loader-separate/inline-define-component@component---errorComponent---notFoundComponent---pendingComponent.tsx @@ -0,0 +1,8 @@ +import { defineComponent } from 'vue' +const SplitComponent = defineComponent({ + setup() { + const label: string = 'Inline Vue component' + return () =>
{label}
+ }, +}) +export { SplitComponent as component } diff --git a/packages/router-plugin/tests/code-splitter/snapshots/vue/2-components-combined-loader-separate/inline-define-component@loader.tsx b/packages/router-plugin/tests/code-splitter/snapshots/vue/2-components-combined-loader-separate/inline-define-component@loader.tsx new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/router-plugin/tests/code-splitter/snapshots/vue/2-components-combined-loader-separate/inline-define-component@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/vue/2-components-combined-loader-separate/inline-define-component@shared.tsx new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/router-plugin/tests/code-splitter/snapshots/vue/3-all-combined-errorComponent-separate/inline-define-component.tsx b/packages/router-plugin/tests/code-splitter/snapshots/vue/3-all-combined-errorComponent-separate/inline-define-component.tsx new file mode 100644 index 0000000000..eacbb6dcb3 --- /dev/null +++ b/packages/router-plugin/tests/code-splitter/snapshots/vue/3-all-combined-errorComponent-separate/inline-define-component.tsx @@ -0,0 +1,7 @@ +const $$splitComponentImporter = () => + import('inline-define-component.tsx?tsr-split=component---loader---notFoundComponent---pendingComponent') +import { lazyRouteComponent } from '@tanstack/vue-router' +import { createFileRoute } from '@tanstack/vue-router' +export const Route = createFileRoute('/')({ + component: lazyRouteComponent($$splitComponentImporter, 'component'), +}) diff --git a/packages/router-plugin/tests/code-splitter/snapshots/vue/3-all-combined-errorComponent-separate/inline-define-component@component---loader---notFoundComponent---pendingComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/vue/3-all-combined-errorComponent-separate/inline-define-component@component---loader---notFoundComponent---pendingComponent.tsx new file mode 100644 index 0000000000..db88804cf9 --- /dev/null +++ b/packages/router-plugin/tests/code-splitter/snapshots/vue/3-all-combined-errorComponent-separate/inline-define-component@component---loader---notFoundComponent---pendingComponent.tsx @@ -0,0 +1,8 @@ +import { defineComponent } from 'vue' +const SplitComponent = defineComponent({ + setup() { + const label: string = 'Inline Vue component' + return () =>
{label}
+ }, +}) +export { SplitComponent as component } diff --git a/packages/router-plugin/tests/code-splitter/snapshots/vue/3-all-combined-errorComponent-separate/inline-define-component@errorComponent.tsx b/packages/router-plugin/tests/code-splitter/snapshots/vue/3-all-combined-errorComponent-separate/inline-define-component@errorComponent.tsx new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/router-plugin/tests/code-splitter/snapshots/vue/3-all-combined-errorComponent-separate/inline-define-component@shared.tsx b/packages/router-plugin/tests/code-splitter/snapshots/vue/3-all-combined-errorComponent-separate/inline-define-component@shared.tsx new file mode 100644 index 0000000000..e69de29bb2 diff --git a/packages/router-plugin/tests/code-splitter/test-files/react/inline-memo-component.tsx b/packages/router-plugin/tests/code-splitter/test-files/react/inline-memo-component.tsx new file mode 100644 index 0000000000..bbb68c9e8f --- /dev/null +++ b/packages/router-plugin/tests/code-splitter/test-files/react/inline-memo-component.tsx @@ -0,0 +1,9 @@ +import { memo } from 'react' +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: memo(() => { + const label: string = 'Inline memo component' + return
{label}
+ }), +}) diff --git a/packages/router-plugin/tests/code-splitter/test-files/vue/inline-define-component.tsx b/packages/router-plugin/tests/code-splitter/test-files/vue/inline-define-component.tsx new file mode 100644 index 0000000000..2d564835c9 --- /dev/null +++ b/packages/router-plugin/tests/code-splitter/test-files/vue/inline-define-component.tsx @@ -0,0 +1,11 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/')({ + component: defineComponent({ + setup() { + const label: string = 'Inline Vue component' + return () =>
{label}
+ }, + }), +}) diff --git a/packages/router-plugin/tests/handle-route-update.test.ts b/packages/router-plugin/tests/handle-route-update.test.ts index 9c8e239fe2..af7d6a86f8 100644 --- a/packages/router-plugin/tests/handle-route-update.test.ts +++ b/packages/router-plugin/tests/handle-route-update.test.ts @@ -8,6 +8,7 @@ import { createNonReactiveReadonlyStore, trimPathRight, } from '@tanstack/router-core' +import { mountRouteModule } from '@tanstack/router-core/_internal/route-module' import { describe, expect, it, onTestFinished, vi } from 'vitest' import { Fragment, act, createElement } from 'react' import { createPortal } from 'react-dom' @@ -35,7 +36,7 @@ const getHandleRouteUpdate = () => { return new Function(`return ${getHandleRouteUpdateCode([])}`)() as ( routeId: string, newRoute: AnyRoute, - ) => void + ) => boolean } function asAnyRoute(route: TRoute): TRoute & AnyRoute { @@ -133,7 +134,7 @@ function runHandleRouteUpdate( ) { const restoreWindow = withWindowRouter(router) try { - getHandleRouteUpdate()(routeId, asAnyRoute(newRoute)) + return getHandleRouteUpdate()(routeId, asAnyRoute(newRoute)) } finally { restoreWindow() } @@ -649,4 +650,75 @@ describe('handleRouteUpdate', () => { expect(document.head.querySelector('script[src="/hot-head.js"]')).toBeNull() expect(document.head.querySelector('script[src="/hot-body.js"]')).toBeNull() }) + + it('updates every installation of a route module installed several times', () => { + const rootRoute = new BaseRootRoute({}) + const orgRoute = new BaseRoute({ + getParentRoute: () => asAnyRoute(rootRoute), + path: '/orgs/$orgId', + }) + const userRoute = new BaseRoute({ + getParentRoute: () => asAnyRoute(rootRoute), + path: '/users/$userId', + }) + const settingsRoot = asAnyRoute( + new BaseRoute({ _module: '@acme/settings' } as any), + ) + const profileRoute = asAnyRoute( + new BaseRoute({ + getParentRoute: () => settingsRoot, + path: '/profile', + loader: () => 'old', + }), + ) + settingsRoot.addChildren([profileRoute]) + const install = (parent: AnyRoute, as: string) => + mountRouteModule(settingsRoot, { + parent: () => parent, + at: '/settings', + as, + } as any) + const router = createTestRouter( + rootRoute.addChildren([ + orgRoute.addChildren([install(asAnyRoute(orgRoute), 'orgSettings')]), + userRoute.addChildren([install(asAnyRoute(userRoute), 'userSettings')]), + ]), + ) + const copies = [ + '@acme/settings#orgSettings:/profile', + '@acme/settings#userSettings:/profile', + ].map((id) => router.routesById[id] as AnyRoute) + + const loader = () => 'new' + const hotProfileRoute = new BaseRoute({ loader } as any) + expect( + runHandleRouteUpdate(router, '@acme/settings:/profile', hotProfileRoute), + ).toBe(true) + + for (const copy of copies) { + expect(copy.options.loader).toBe(loader) + expect(router.routesById[copy.id]).toBe(copy) + } + // The hot export is the new template, with the module-local id. + expect(hotProfileRoute.id).toBe('@acme/settings:/profile') + expect(hotProfileRoute.fullPath).toBe('/profile') + expect( + runHandleRouteUpdate(router, '@acme/settings:/profile', hotProfileRoute), + ).toBe(false) + + const component = () => null + runHandleRouteUpdate( + router, + '@acme/settings:', + new BaseRoute({ _module: '@acme/settings', component } as any), + ) + expect( + ['orgSettings', 'userSettings'].map( + (as) => router.routesById[`@acme/settings#${as}:`]?.options.component, + ), + ).toEqual([component, component]) + expect(Object.keys(router.routesById)).toContain( + '@acme/settings#userSettings:/profile', + ) + }) }) diff --git a/packages/router-vite-plugin/package.json b/packages/router-vite-plugin/package.json index 4b566bbe81..4e700debed 100644 --- a/packages/router-vite-plugin/package.json +++ b/packages/router-vite-plugin/package.json @@ -61,7 +61,7 @@ "src" ], "engines": { - "node": ">=20.19" + "node": ">=22.22.0" }, "dependencies": { "@tanstack/router-plugin": "workspace:*" diff --git a/packages/solid-router/package.json b/packages/solid-router/package.json index 80840069ea..4697de4364 100644 --- a/packages/solid-router/package.json +++ b/packages/solid-router/package.json @@ -90,7 +90,21 @@ "default": "./dist/cjs/ssr/client.cjs" } }, - "./package.json": "./package.json" + "./package.json": "./package.json", + "./_internal/route-module": { + "solid": { + "types": "./dist/source/route-module-internal.d.ts", + "default": "./dist/source/route-module-internal.js" + }, + "import": { + "types": "./dist/esm/route-module-internal.d.ts", + "default": "./dist/esm/route-module-internal.js" + }, + "require": { + "types": "./dist/cjs/route-module-internal.d.cts", + "default": "./dist/cjs/route-module-internal.cjs" + } + } }, "sideEffects": false, "files": [ diff --git a/packages/solid-router/src/Match.tsx b/packages/solid-router/src/Match.tsx index 37c4020c03..bc4eb2ae72 100644 --- a/packages/solid-router/src/Match.tsx +++ b/packages/solid-router/src/Match.tsx @@ -1,3 +1,4 @@ +import { resolveRouteId } from '@tanstack/router-core/_internal/route-module' import * as Solid from 'solid-js' import { rootRouteId } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' @@ -141,7 +142,13 @@ export const Match = (props: { routeId: string }) => { notFoundError.routeId ??= currentMatch().routeId - if (notFoundError.routeId !== currentMatch().routeId) { + if ( + (resolveRouteId?.( + router, + notFoundError.routeId, + currentMatch().routeId, + ) ?? notFoundError.routeId) !== currentMatch().routeId + ) { throw notFoundError } diff --git a/packages/solid-router/src/Matches.tsx b/packages/solid-router/src/Matches.tsx index d2dd1a681a..454bcb7cc6 100644 --- a/packages/solid-router/src/Matches.tsx +++ b/packages/solid-router/src/Matches.tsx @@ -18,12 +18,14 @@ import type { MakeRouteMatchUnion, MaskOptions, MatchRouteOptions, + Register, RegisteredRouter, + RegisteredRouterOf, ResolveRoute, ToSubOptionsProps, } from '@tanstack/router-core' -declare module '@tanstack/router-core' { +declare module '@tanstack/router-core/extensions' { export interface RouteMatchExtensions { meta?: Array links?: Array @@ -127,6 +129,24 @@ export type UseMatchRouteOptions< MaskOptions & MatchRouteOptions +/** + * The signature of `useMatchRoute`, typed against the router of `TDefaultRegister` unless a + * router type is passed explicitly. Route modules export a `useMatchRoute` of + * this type. + */ +export type UseMatchRouteFn = < + TRouter extends AnyRouter = RegisteredRouterOf, +>() => < + const TFrom extends string = string, + const TTo extends string | undefined = undefined, + const TMaskFrom extends string = TFrom, + const TMaskTo extends string = '', +>( + opts: UseMatchRouteOptions, +) => Solid.Accessor< + false | Expand['types']['allParams']> +> + export function useMatchRoute() { const router = useRouter() @@ -173,6 +193,20 @@ export type MakeMatchRouteOptions< | Solid.JSX.Element } +/** + * The signature of `MatchRoute`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `MatchRoute` of this type. + */ +export type MatchRouteFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TFrom extends string = string, + const TTo extends string | undefined = undefined, + const TMaskFrom extends string = TFrom, + const TMaskTo extends string = '', +>( + props: MakeMatchRouteOptions, +) => any + export function MatchRoute< TRouter extends AnyRouter = RegisteredRouter, const TFrom extends string = string, @@ -206,6 +240,17 @@ export type UseMatchesResult< TSelected, > = unknown extends TSelected ? Array> : TSelected +/** + * The signature of `useMatches`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useMatches` of this type. + */ +export type UseMatchesFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TSelected = unknown, +>( + opts?: UseMatchesBaseOptions, +) => Solid.Accessor> + export function useMatches< TRouter extends AnyRouter = RegisteredRouter, TSelected = unknown, @@ -223,6 +268,17 @@ export function useMatches< }) as Solid.Accessor> } +/** + * The signature of `useParentMatches`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useParentMatches` of this type. + */ +export type UseParentMatchesFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TSelected = unknown, +>( + opts?: UseMatchesBaseOptions, +) => Solid.Accessor> + export function useParentMatches< TRouter extends AnyRouter = RegisteredRouter, TSelected = unknown, @@ -242,6 +298,17 @@ export function useParentMatches< } as any) } +/** + * The signature of `useChildMatches`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useChildMatches` of this type. + */ +export type UseChildMatchesFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TSelected = unknown, +>( + opts?: UseMatchesBaseOptions, +) => Solid.Accessor> + export function useChildMatches< TRouter extends AnyRouter = RegisteredRouter, TSelected = unknown, diff --git a/packages/solid-router/src/fileRoute.ts b/packages/solid-router/src/fileRoute.ts index a1fcae713f..fc6a9bba08 100644 --- a/packages/solid-router/src/fileRoute.ts +++ b/packages/solid-router/src/fileRoute.ts @@ -53,6 +53,81 @@ export function createFileRoute< } } +/** + * The route factory returned by `createFileRoute(path)`. `TDefaultRegister` + * is the scope of the created route: the application's `Register`, or the + * scope register of a route module. + */ +export type FileRouteFactory< + TFilePath extends string, + TParentRoute extends AnyRoute, + TId extends RouteConstraints['TId'], + TPath extends RouteConstraints['TPath'], + TFullPath extends RouteConstraints['TFullPath'], + TDefaultRegister = Register, +> = < + TRegister = TDefaultRegister, + TSearchValidator = undefined, + TParams = ResolveParams, + TRouteContextFn = AnyContext, + TBeforeLoadFn = AnyContext, + TLoaderDeps extends Record = {}, + TLoaderFn = undefined, + TChildren = unknown, + TSSR = unknown, + const TMiddlewares = unknown, + THandlers = undefined, +>( + options?: FileBaseRouteOptions< + TRegister, + TParentRoute, + TId, + TPath, + TSearchValidator, + TParams, + TLoaderDeps, + TLoaderFn, + AnyContext, + TRouteContextFn, + TBeforeLoadFn, + AnyContext, + TSSR, + TMiddlewares, + THandlers + > & + UpdatableRouteOptions< + TParentRoute, + TId, + TFullPath, + TParams, + TSearchValidator, + TLoaderFn, + TLoaderDeps, + AnyContext, + TRouteContextFn, + TBeforeLoadFn + >, +) => Route< + TRegister, + TParentRoute, + TPath, + TFullPath, + TFilePath, + TId, + TSearchValidator, + TParams, + AnyContext, + TRouteContextFn, + TBeforeLoadFn, + TLoaderDeps, + TLoaderFn, + TChildren, + unknown, + TSSR, + TMiddlewares, + THandlers +> + /** @deprecated It's no longer recommended to use the `FileRoute` class directly. Instead, use `createFileRoute('/path/to/file')(options)` to create a file route. @@ -74,68 +149,13 @@ export class FileRoute< this.silent = _opts?.silent } - createRoute = < - TRegister = Register, - TSearchValidator = undefined, - TParams = ResolveParams, - TRouteContextFn = AnyContext, - TBeforeLoadFn = AnyContext, - TLoaderDeps extends Record = {}, - TLoaderFn = undefined, - TChildren = unknown, - TSSR = unknown, - const TMiddlewares = unknown, - THandlers = undefined, - >( - options?: FileBaseRouteOptions< - TRegister, - TParentRoute, - TId, - TPath, - TSearchValidator, - TParams, - TLoaderDeps, - TLoaderFn, - AnyContext, - TRouteContextFn, - TBeforeLoadFn, - AnyContext, - TSSR, - TMiddlewares, - THandlers - > & - UpdatableRouteOptions< - TParentRoute, - TId, - TFullPath, - TParams, - TSearchValidator, - TLoaderFn, - TLoaderDeps, - AnyContext, - TRouteContextFn, - TBeforeLoadFn - >, - ): Route< - TRegister, - TParentRoute, - TPath, - TFullPath, + createRoute: FileRouteFactory< TFilePath, + TParentRoute, TId, - TSearchValidator, - TParams, - AnyContext, - TRouteContextFn, - TBeforeLoadFn, - TLoaderDeps, - TLoaderFn, - TChildren, - unknown, - TSSR, - TMiddlewares, - THandlers - > => { + TPath, + TFullPath + > = (options) => { if (process.env.NODE_ENV !== 'production') { if (!this.silent) { console.warn( @@ -182,7 +202,7 @@ export function FileRouteLoader< return (loaderFn) => loaderFn as any } -declare module '@tanstack/router-core' { +declare module '@tanstack/router-core/extensions' { export interface LazyRoute { useMatch: UseMatchRoute useRouteContext: UseRouteContextRoute diff --git a/packages/solid-router/src/index.tsx b/packages/solid-router/src/index.tsx index 9b1026a6b8..7d472f2a0d 100644 --- a/packages/solid-router/src/index.tsx +++ b/packages/solid-router/src/index.tsx @@ -151,6 +151,8 @@ export type { LoaderFnContext, MakeRouteMatch, MakeRouteMatchUnion, + KnownRouteMatchUnion, + ForeignRouteMatch, RouteMatch, AnyRouteMatch, RouteContextFn, @@ -271,9 +273,54 @@ export type { ErrorRouteComponent, NotFoundRouteComponent, } from './route' +// `createFileRoute` returns router-core's `Route`, and `Route` above is this +// package's class: declarations name the type of file routes through this +// export, so they need no import of `@tanstack/router-core`. +export type { Route as RouteCore } from '@tanstack/router-core' export { createRouter, Router } from './router' +export type { + FileRoutesByPathEntry, + FileRouteScope, + RouteScope, +} from './routeModule' +export type { FileRouteFactory } from './fileRoute' +export type { + HostedRouter, + InstallationRoutesById, + MountedRoutesById, + ModuleRootRoute, + ModuleRootRouteOptions, + MountRouteModuleOptions, + RedirectFn, + RegisteredRouterOf, + ScopeRouter, + ScopedRouter, + ScopedRouterView, + ValidateRouteModuleMount, + ValidateRouteModuleMountPath, +} from '@tanstack/router-core' +export type { GetRouteApiFn } from './route' +export type { CreateLinkFn, LinkOptionsFn } from './link' +export type { NavigateComponentFn, UseNavigateFn } from './useNavigate' +export type { + MatchRouteFn, + UseChildMatchesFn, + UseMatchRouteFn, + UseMatchesFn, + UseParentMatchesFn, +} from './Matches' +export type { UseRouterFn } from './useRouter' +export type { UseMatchFn } from './useMatch' +export type { UseLoaderDataFn } from './useLoaderData' +export type { UseLoaderDepsFn } from './useLoaderDeps' +export type { UseSearchFn } from './useSearch' +export type { UseParamsFn } from './useParams' +export type { UseRouteContextFn } from './useRouteContext' +export type { UseLocationFn } from './useLocation' +export type { UseRouterStateFn } from './useRouterState' + export { lazyFn, SearchParamError } from '@tanstack/router-core' export { RouterProvider, RouterContextProvider } from './RouterProvider' diff --git a/packages/solid-router/src/link.tsx b/packages/solid-router/src/link.tsx index 27bed97d92..77ac09412c 100644 --- a/packages/solid-router/src/link.tsx +++ b/packages/solid-router/src/link.tsx @@ -24,14 +24,27 @@ import type { Constrain, LinkOptions, ParsedLocation, + Register, RegisteredRouter, + RegisteredRouterOf, RoutePaths, + ScopedRouteOptions, } from '@tanstack/router-core' import type { ValidateLinkOptions, ValidateLinkOptionsArray, } from './typePrimitives' +export type UseLinkPropsFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TFrom extends string = string, + TTo extends string = '', + TMaskFrom extends string = TFrom, + TMaskTo extends string = '', +>( + options: UseLinkPropsOptions, +) => Solid.ComponentProps<'a'> + export function useLinkProps< TRouter extends AnyRouter = RegisteredRouter, TFrom extends RoutePaths | string = string, @@ -91,6 +104,9 @@ function createLinkProps( currentLocation() } } + // The nearest route resolves module destinations to the installation the + // Link renders under; other destinations ignore it. + dest._nearestRoute = routeId return dest } const dest = @@ -461,6 +477,9 @@ const NAVIGATION_KEYS = [ 'unsafeRelative', 'from', 'href', + // Internal route-module scope (see `scopeLocationOptions` in router-core). + '_module', + '_fromRoute', ] as const // Options the Link consumes; every other option is an element prop. const LINK_OPTION_KEYS = [ @@ -616,8 +635,9 @@ export type CreateLinkProps = LinkProps< export type LinkComponent< in out TComp, in out TDefaultFrom extends string = string, + in out TDefaultRegister = Register, > = < - TRouter extends AnyRouter = RegisteredRouter, + TRouter extends AnyRouter = RegisteredRouterOf, const TFrom extends string = TDefaultFrom, const TTo extends string | undefined = undefined, const TMaskFrom extends string = TFrom, @@ -628,10 +648,11 @@ export type LinkComponent< export interface LinkComponentRoute< in out TDefaultFrom extends string = string, + in out TDefaultRegister = Register, > { defaultFrom: TDefaultFrom; < - TRouter extends AnyRouter = RegisteredRouter, + TRouter extends AnyRouter = RegisteredRouterOf, const TTo extends string | undefined = undefined, const TMaskTo extends string = '', >( @@ -646,6 +667,14 @@ export interface LinkComponentRoute< ): Solid.JSX.Element } +/** + * The signature of `createLink`, creating links typed against the router of `TDefaultRegister`. + * Route modules export a `createLink` of this type. + */ +export type CreateLinkFn = ( + Comp: Constrain Solid.JSX.Element>, +) => LinkComponent + export function createLink( Comp: Constrain Solid.JSX.Element>, ): LinkComponent { @@ -702,12 +731,12 @@ export type LinkOptionsFnOptions< ? ValidateLinkOptionsArray : ValidateLinkOptions -export type LinkOptionsFn = < +export type LinkOptionsFn = < const TOptions, - TRouter extends AnyRouter = RegisteredRouter, + TRouter extends AnyRouter = RegisteredRouterOf, >( options: LinkOptionsFnOptions, -) => TOptions +) => ScopedRouteOptions export const linkOptions: LinkOptionsFn<'a'> = (options) => { return options as any diff --git a/packages/solid-router/src/route-module-internal.ts b/packages/solid-router/src/route-module-internal.ts new file mode 100644 index 0000000000..3ac86d6306 --- /dev/null +++ b/packages/solid-router/src/route-module-internal.ts @@ -0,0 +1,6 @@ +// Internal generated/framework wiring; use generated scopes to author modules. +export * from './routeModule' +export { + mountRouteModule, + getRouteModuleId, +} from '@tanstack/router-core/_internal/route-module' diff --git a/packages/solid-router/src/route.tsx b/packages/solid-router/src/route.tsx index 5bf786a0f6..210ad641ce 100644 --- a/packages/solid-router/src/route.tsx +++ b/packages/solid-router/src/route.tsx @@ -4,6 +4,7 @@ import { BaseRouteApi, notFound, } from '@tanstack/router-core' +import { getRouteNavigationScope } from '@tanstack/router-core/_internal/route-module' import { Link } from './link' import { useLoaderData } from './useLoaderData' import { useLoaderDeps } from './useLoaderDeps' @@ -23,6 +24,7 @@ import type { NotFoundRouteProps, Register, RegisteredRouter, + RegisteredRouterOf, ResolveFullPath, ResolveId, ResolveParams, @@ -48,7 +50,7 @@ import type * as Solid from 'solid-js' import type { UseRouteContextRoute } from './useRouteContext' import type { LinkComponentRoute } from './link' -declare module '@tanstack/router-core' { +declare module '@tanstack/router-core/extensions' { export interface ErrorBoundaryTypes { error: Error } @@ -71,18 +73,31 @@ declare module '@tanstack/router-core' { export interface RouteExtensions< in out TId extends string, in out TFullPath extends string, + in out TRegister, > { - useMatch: UseMatchRoute - useRouteContext: UseRouteContextRoute - useSearch: UseSearchRoute - useParams: UseParamsRoute - useLoaderDeps: UseLoaderDepsRoute - useLoaderData: UseLoaderDataRoute - useNavigate: () => UseNavigateResult - Link: LinkComponentRoute + useMatch: UseMatchRoute + useRouteContext: UseRouteContextRoute + useSearch: UseSearchRoute + useParams: UseParamsRoute + useLoaderDeps: UseLoaderDepsRoute + useLoaderData: UseLoaderDataRoute + useNavigate: () => UseNavigateResult + Link: LinkComponentRoute } } +/** + * The signature of `getRouteApi`, typed against the router of `TDefaultRegister` unless a + * router type is passed explicitly. Route modules export a `getRouteApi` of + * this type. + */ +export type GetRouteApiFn = < + const TId, + TRouter extends AnyRouter = RegisteredRouterOf, +>( + id: ConstrainLiteral>, +) => RouteApi + export function getRouteApi< const TId, TRouter extends AnyRouter = RegisteredRouter, @@ -101,48 +116,63 @@ export class RouteApi< super({ id }) } - useMatch: UseMatchRoute = (opts) => { + useMatch: UseMatchRoute = (opts) => { return useMatch({ ...opts, from: this.id } as any) as any } - useRouteContext: UseRouteContextRoute = (opts) => { + useRouteContext: UseRouteContextRoute = (opts) => { return useRouteContext({ ...(opts as any), from: this.id }) } - useSearch: UseSearchRoute = (opts) => { + useSearch: UseSearchRoute = (opts) => { return useSearch({ ...opts, from: this.id } as any) } - useParams: UseParamsRoute = (opts) => { + useParams: UseParamsRoute = (opts) => { return useParams({ ...opts, from: this.id } as any) } - useLoaderDeps: UseLoaderDepsRoute = (opts) => { + useLoaderDeps: UseLoaderDepsRoute = (opts) => { return useLoaderDeps({ ...opts, from: this.id, strict: false } as any) } - useLoaderData: UseLoaderDataRoute = (opts) => { + useLoaderData: UseLoaderDataRoute = (opts) => { return useLoaderData({ ...opts, from: this.id, strict: false } as any) } useNavigate = (): UseNavigateResult< - RouteTypesById['fullPath'] + RouteTypesById['fullPath'], + { router: TRouter } > => { const router = useRouter() - return useNavigate({ from: router.routesById[this.id as string].fullPath }) + return useNavigate( + getRouteNavigationScope( + this.id as string, + router.routesById[this.id as string]?.fullPath, + ) as any, + ) as any } notFound = (opts?: NotFoundError) => { return notFound({ routeId: this.id as string, ...opts }) } - Link: LinkComponentRoute['fullPath']> = (( - props, - ) => { + Link: LinkComponentRoute< + RouteTypesById['fullPath'], + { router: TRouter } + > = ((props) => { const router = useRouter() - const fullPath = router.routesById[this.id as string].fullPath - return - }) as LinkComponentRoute['fullPath']> + const fullPath = router.routesById[this.id as string]?.fullPath + return ( + + ) + }) as LinkComponentRoute< + RouteTypesById['fullPath'], + { router: TRouter } + > } export class Route< @@ -240,37 +270,44 @@ export class Route< super(options) } - useMatch: UseMatchRoute = (opts) => { + useMatch: UseMatchRoute = (opts) => { return useMatch({ ...opts, from: this.id } as any) as any } - useRouteContext: UseRouteContextRoute = (opts?) => { + useRouteContext: UseRouteContextRoute = (opts?) => { return useRouteContext({ ...(opts as any), from: this.id }) as any } - useSearch: UseSearchRoute = (opts) => { + useSearch: UseSearchRoute = (opts) => { return useSearch({ ...opts, from: this.id } as any) } - useParams: UseParamsRoute = (opts) => { + useParams: UseParamsRoute = (opts) => { return useParams({ ...opts, from: this.id } as any) } - useLoaderDeps: UseLoaderDepsRoute = (opts) => { + useLoaderDeps: UseLoaderDepsRoute = (opts) => { return useLoaderDeps({ ...opts, from: this.id } as any) } - useLoaderData: UseLoaderDataRoute = (opts) => { + useLoaderData: UseLoaderDataRoute = (opts) => { return useLoaderData({ ...opts, from: this.id } as any) } - useNavigate = (): UseNavigateResult => { - return useNavigate({ from: this.fullPath }) + useNavigate = (): UseNavigateResult => { + return useNavigate( + getRouteNavigationScope(this.id, this.fullPath) as any, + ) as any } - Link: LinkComponentRoute = ((props) => { - return - }) as LinkComponentRoute + Link: LinkComponentRoute = ((props) => { + return ( + + ) + }) as LinkComponentRoute } export function createRoute< @@ -469,37 +506,37 @@ export class RootRoute< super(options) } - useMatch: UseMatchRoute = (opts) => { + useMatch: UseMatchRoute = (opts) => { return useMatch({ ...opts, from: this.id } as any) as any } - useRouteContext: UseRouteContextRoute = (opts) => { + useRouteContext: UseRouteContextRoute = (opts) => { return useRouteContext({ ...(opts as any), from: this.id }) } - useSearch: UseSearchRoute = (opts) => { + useSearch: UseSearchRoute = (opts) => { return useSearch({ ...opts, from: this.id } as any) } - useParams: UseParamsRoute = (opts) => { + useParams: UseParamsRoute = (opts) => { return useParams({ ...opts, from: this.id } as any) } - useLoaderDeps: UseLoaderDepsRoute = (opts) => { + useLoaderDeps: UseLoaderDepsRoute = (opts) => { return useLoaderDeps({ ...opts, from: this.id } as any) } - useLoaderData: UseLoaderDataRoute = (opts) => { + useLoaderData: UseLoaderDataRoute = (opts) => { return useLoaderData({ ...opts, from: this.id } as any) } - useNavigate = (): UseNavigateResult<'/'> => { - return useNavigate({ from: this.fullPath }) + useNavigate = (): UseNavigateResult<'/', TRegister> => { + return useNavigate({ from: this.fullPath }) as any } - Link: LinkComponentRoute<'/'> = ((props) => { + Link: LinkComponentRoute<'/', TRegister> = ((props) => { return - }) as LinkComponentRoute<'/'> + }) as LinkComponentRoute<'/', TRegister> } export function createRouteMask< diff --git a/packages/solid-router/src/routeModule.tsx b/packages/solid-router/src/routeModule.tsx new file mode 100644 index 0000000000..2bd62b1e20 --- /dev/null +++ b/packages/solid-router/src/routeModule.tsx @@ -0,0 +1,435 @@ +import { mergeProps, useContext } from 'solid-js' +import { notFound } from '@tanstack/router-core' +import { + bindRouteScopeOptions, + createScopedRedirect, + getInstallationRouteIdMapper, + getScopedRouterView, +} from '@tanstack/router-core/_internal/route-module' +import { Route, getRouteApi } from './route' +import { Link, useLinkProps } from './link' +import { useBlocker } from './useBlocker' +import { Navigate, useNavigate } from './useNavigate' +import { + MatchRoute, + useChildMatches, + useMatchRoute, + useMatches, + useParentMatches, +} from './Matches' +import { useRouter } from './useRouter' +import { nearestMatchContext } from './matchContext' +import { useMatch } from './useMatch' +import { useLoaderData } from './useLoaderData' +import { useLoaderDeps } from './useLoaderDeps' +import { useSearch } from './useSearch' +import { useParams } from './useParams' +import { useRouteContext } from './useRouteContext' +import { useLocation } from './useLocation' +import { useRouterState } from './useRouterState' +import type { UseBlockerFn } from './useBlocker' +import type * as Solid from 'solid-js' +import type { + AnyContext, + AnyRoute, + AnyRouter, + ModuleRootRoute, + ModuleRootRouteOptions, + NotFoundError, + RedirectFn, + RouteIds, + ScopedRouterView, +} from '@tanstack/router-core' +import type { FileRouteFactory } from './fileRoute' +import type { GetRouteApiFn } from './route' +import type { + CreateLinkFn, + LinkComponent, + LinkOptionsFn, + UseLinkPropsFn, +} from './link' +import type { NavigateComponentFn, UseNavigateFn } from './useNavigate' +import type { + MatchRouteFn, + UseChildMatchesFn, + UseMatchRouteFn, + UseMatchesFn, + UseParentMatchesFn, +} from './Matches' +import type { UseMatchFn } from './useMatch' +import type { UseLoaderDataFn } from './useLoaderData' +import type { UseLoaderDepsFn } from './useLoaderDeps' +import type { UseSearchFn } from './useSearch' +import type { UseParamsFn } from './useParams' +import type { UseRouteContextFn } from './useRouteContext' +import type { UseLocationFn } from './useLocation' +import type { UseRouterStateFn } from './useRouterState' + +/** An entry of a generated module-local `FileRoutesByPath` interface. */ +export interface FileRoutesByPathEntry { + id: string + path: string + fullPath: string + parentRoute: AnyRoute +} + +// Entries reference the route files, whose types depend on these factories: +// read one property at a time and never constrain or check whole entries. +type FileRouteEntry = + TFileRoutesByPath[TFilePath & keyof TFileRoutesByPath] +type FileRouteParent = + FileRouteEntry extends { + parentRoute: infer TParentRoute extends AnyRoute + } + ? TParentRoute + : never +type FileRouteId = + FileRouteEntry extends { + id: infer TId extends string + } + ? TId + : never +type FileRoutePath = + FileRouteEntry extends { + path: infer TPath extends string + } + ? TPath + : never +type FileRouteFullPath = + FileRouteEntry extends { + fullPath: infer TFullPath extends string + } + ? TFullPath + : never + +/** + * Route factories of a route module, typed against the module's generated + * `FileRoutesByPath` and its scope register instead of the application's + * global registrations. + */ +export interface FileRouteScope< + TFileRoutesByPath, + TRegister, + TModuleId extends string, +> { + /** `createFileRoute`, typed against the module's own route files. */ + createFileRoute: ( + path?: TFilePath, + ) => FileRouteFactory< + FileRouteId, + FileRouteParent, + FileRouteId, + FileRoutePath, + FileRouteFullPath, + TRegister + > + /** + * Creates the module root. `TRouterContext` is the router context the module + * requires from the route it is mounted under. + */ + createModuleRoot: () => < + TRouteContextFn = AnyContext, + TBeforeLoadFn = AnyContext, + TSearchValidator = undefined, + TLoaderDeps extends Record = {}, + TLoaderFn = undefined, + TSSR = unknown, + const TServerMiddlewares = unknown, + THandlers = undefined, + >( + options?: ModuleRootRouteOptions< + TModuleId, + TRegister, + TSearchValidator, + TRouterContext, + TRouteContextFn, + TBeforeLoadFn, + TLoaderDeps, + TLoaderFn, + TSSR, + TServerMiddlewares, + THandlers + >, + ) => ModuleRootRoute< + TModuleId, + TRegister, + TSearchValidator, + TRouterContext, + TRouteContextFn, + TBeforeLoadFn, + TLoaderDeps, + TLoaderFn, + unknown, + unknown, + TSSR, + TServerMiddlewares, + THandlers + > +} + +/** Binds only the module-root factory used by generated route scopes. */ +export function bindCreateModuleRoot( + moduleId: TModuleId, +): FileRouteScope['createModuleRoot'] { + return () => (options) => + new Route({ ...(options as any), _module: moduleId }) as any +} + +/** + * The routing APIs of a route scope, typed against `TRouter`. + * + * Path-based APIs (`Link`, `useNavigate`, `redirect`, ...) address routes by + * the module-local paths of the module: they work wherever the module is + * mounted. Id-based APIs (`useMatch`, `getRouteApi`, ...) take qualified route + * ids such as `@acme/products:/$productId`. + */ +export interface RouteScope { + Link: LinkComponent<'a', string, { router: TRouter }> + createLink: CreateLinkFn<{ router: TRouter }> + linkOptions: LinkOptionsFn<'a', { router: TRouter }> + Navigate: NavigateComponentFn<{ router: TRouter }> + useNavigate: UseNavigateFn<{ router: TRouter }> + useLinkProps: UseLinkPropsFn<{ router: TRouter }> + useBlocker: UseBlockerFn<{ router: TRouter }> + notFound: ( + options?: Omit & { + routeId?: RouteIds + }, + ) => NotFoundError + redirect: RedirectFn<{ router: TRouter }> + MatchRoute: MatchRouteFn<{ router: TRouter }> + useMatchRoute: UseMatchRouteFn<{ router: TRouter }> + /** + * The router, viewed from the module: its `navigate`, `buildLocation`, + * `preloadRoute` and `matchRoute` take module-local paths. + */ + useRouter: (opts?: { warn?: boolean }) => ScopedRouterView + getRouteApi: GetRouteApiFn<{ router: TRouter }> + useMatch: UseMatchFn<{ router: TRouter }> + useMatches: UseMatchesFn<{ router: TRouter }> + useParentMatches: UseParentMatchesFn<{ router: TRouter }> + useChildMatches: UseChildMatchesFn<{ router: TRouter }> + useLoaderData: UseLoaderDataFn<{ router: TRouter }> + useLoaderDeps: UseLoaderDepsFn<{ router: TRouter }> + useSearch: UseSearchFn<{ router: TRouter }> + useParams: UseParamsFn<{ router: TRouter }> + useRouteContext: UseRouteContextFn<{ router: TRouter }> + useLocation: UseLocationFn<{ router: TRouter }> + useRouterState: UseRouterStateFn<{ router: TRouter }> +} + +// Each generated ESM export binds only its own API. These functions allocate +// closures/components; they never access a router or register runtime state. +function bindOptions(moduleId: string): (options: any) => any { + const router = useRouter() + const routeId = useContext(nearestMatchContext)[0 /* route id */]() + return (options: any) => + bindRouteScopeOptions(moduleId, options ?? {}, router, routeId) +} + +function bindIdHook(moduleId: string, hook: (options: any) => any) { + const toInstallation = getInstallationRouteIdMapper(moduleId) + return toInstallation + ? (options?: { from?: string }) => + hook({ ...options, from: toInstallation(options?.from) }) + : hook +} + +export function bindRouteScopeLink( + moduleId: string, +): RouteScope['Link'] { + const AnyLink = Link as (props: any) => Solid.JSX.Element + return ((props: object) => { + const bind = bindOptions(moduleId) + return + }) as any +} + +export function bindRouteScopeCreateLink( + moduleId: string, +): RouteScope['createLink'] { + const AnyLink = Link as (props: any) => Solid.JSX.Element + return ((Comp: unknown) => (props: object) => { + const bind = bindOptions(moduleId) + return + }) as any +} + +export function bindRouteScopeNavigate( + moduleId: string, +): RouteScope['Navigate'] { + const AnyNavigate = Navigate as (props: any) => null + return ((props: object) => { + const bind = bindOptions(moduleId) + return + }) as any +} + +export function bindRouteScopeMatchRoute( + moduleId: string, +): RouteScope['MatchRoute'] { + const AnyMatchRoute = MatchRoute as (props: any) => any + return ((props: object) => { + const bind = bindOptions(moduleId) + const routeId = useContext(nearestMatchContext)[0 /* route id */]() + return + }) as any +} + +export function bindRouteScopeUseLinkProps( + moduleId: string, +): RouteScope['useLinkProps'] { + return ((options: any) => { + const bind = bindOptions(moduleId) + return useLinkProps( + mergeProps(options, { + get _module() { + return bind(options)._module + }, + }) as any, + ) + }) as any +} + +export function bindRouteScopeLinkOptions( + moduleId: string, +): RouteScope['linkOptions'] { + return ((options: any) => + Array.isArray(options) + ? options.map((option) => bindRouteScopeOptions(moduleId, option)) + : bindRouteScopeOptions(moduleId, options)) as any +} + +export function bindRouteScopeUseNavigate( + moduleId: string, +): RouteScope['useNavigate'] { + return ((options?: any) => { + const bind = bindOptions(moduleId) + const navigate = useNavigate(bind(options)) + return (next: any) => navigate(bind(next)) + }) as any +} + +export function bindRouteScopeRedirect( + moduleId: string, +): RouteScope['redirect'] { + return createScopedRedirect(moduleId) +} + +export function bindRouteScopeUseMatchRoute( + moduleId: string, +): RouteScope['useMatchRoute'] { + return (() => { + const bind = bindOptions(moduleId) + const matchRoute = useMatchRoute() + const routeId = useContext(nearestMatchContext)[0 /* route id */]() + return (options: any) => + matchRoute({ ...bind(options), _nearestRoute: routeId }) + }) as any +} + +export function bindRouteScopeUseRouter( + moduleId: string, +): RouteScope['useRouter'] { + return ((options?: { warn?: boolean }) => + getScopedRouterView( + useRouter(options), + moduleId, + useContext(nearestMatchContext)[0 /* route id */](), + )) as any +} + +export function bindRouteScopeGetRouteApi( + moduleId: string, +): RouteScope['getRouteApi'] { + const toInstallation = getInstallationRouteIdMapper(moduleId) + return ( + toInstallation + ? (id: string) => getRouteApi(toInstallation(id) as never) + : getRouteApi + ) as any +} + +export function bindRouteScopeUseMatch( + moduleId: string, +): RouteScope['useMatch'] { + return bindIdHook(moduleId, useMatch) as any +} + +export function bindRouteScopeUseLoaderData( + moduleId: string, +): RouteScope['useLoaderData'] { + return bindIdHook(moduleId, useLoaderData) as any +} + +export function bindRouteScopeUseLoaderDeps( + moduleId: string, +): RouteScope['useLoaderDeps'] { + return bindIdHook(moduleId, useLoaderDeps) as any +} + +export function bindRouteScopeUseSearch( + moduleId: string, +): RouteScope['useSearch'] { + return bindIdHook(moduleId, useSearch) as any +} + +export function bindRouteScopeUseParams( + moduleId: string, +): RouteScope['useParams'] { + return bindIdHook(moduleId, useParams) as any +} + +export function bindRouteScopeUseRouteContext( + moduleId: string, +): RouteScope['useRouteContext'] { + return bindIdHook(moduleId, useRouteContext) as any +} + +export function bindRouteScopeUseMatches( + _moduleId: string, +): RouteScope['useMatches'] { + return useMatches as any +} + +export function bindRouteScopeUseParentMatches( + _moduleId: string, +): RouteScope['useParentMatches'] { + return useParentMatches as any +} + +export function bindRouteScopeUseChildMatches( + _moduleId: string, +): RouteScope['useChildMatches'] { + return useChildMatches as any +} + +export function bindRouteScopeUseLocation( + _moduleId: string, +): RouteScope['useLocation'] { + return useLocation as any +} + +export function bindRouteScopeUseRouterState( + _moduleId: string, +): RouteScope['useRouterState'] { + return useRouterState as any +} + +export function bindRouteScopeUseBlocker( + _moduleId: string, +): RouteScope['useBlocker'] { + return useBlocker as any +} + +export function bindRouteScopeNotFound( + moduleId: string, +): RouteScope['notFound'] { + const toInstallation = getInstallationRouteIdMapper(moduleId) + return ((options?: any) => + notFound( + toInstallation && options?.routeId + ? { ...options, routeId: toInstallation(options.routeId) } + : options, + )) as any +} diff --git a/packages/solid-router/src/router.ts b/packages/solid-router/src/router.ts index 3fce7c9d75..b7fa9c05d0 100644 --- a/packages/solid-router/src/router.ts +++ b/packages/solid-router/src/router.ts @@ -14,7 +14,7 @@ import type { } from './route' import type { JSX } from 'solid-js' -declare module '@tanstack/router-core' { +declare module '@tanstack/router-core/extensions' { export interface RouterOptionsExtensions { /** * The default `component` a route should use if no component is provided. diff --git a/packages/solid-router/src/useBlocker.tsx b/packages/solid-router/src/useBlocker.tsx index 566a58d1ca..c6d5b0213d 100644 --- a/packages/solid-router/src/useBlocker.tsx +++ b/packages/solid-router/src/useBlocker.tsx @@ -1,3 +1,4 @@ +import { isServer } from '@tanstack/router-core/isServer' import * as Solid from 'solid-js' import { useRouter } from './useRouter' import type { @@ -11,6 +12,8 @@ import type { AnyRouter, ParseRoute, RegisteredRouter, + RegisteredRouterOf, + RouteScopeMarker, } from '@tanstack/router-core' type ShouldBlockFnLocation< @@ -30,14 +33,21 @@ type AnyShouldBlockFnLocation = ShouldBlockFnLocation type MakeShouldBlockFnLocationUnion< TRouter extends AnyRouter = RegisteredRouter, TRoute extends AnyRoute = ParseRoute, -> = TRoute extends any +> = TRouter['routeTree'] extends RouteScopeMarker ? ShouldBlockFnLocation< - TRoute['id'], - TRoute['fullPath'], - TRoute['types']['allParams'], - TRoute['types']['fullSearchSchema'] + string, + string, + Record, + Record > - : never + : TRoute extends any + ? ShouldBlockFnLocation< + TRoute['id'], + TRoute['fullPath'], + TRoute['types']['allParams'], + TRoute['types']['fullSearchSchema'] + > + : never type BlockerResolver = | { @@ -134,6 +144,16 @@ function _resolveBlockerOpts( } } +/** The generated module hook observes navigation across the entire application. */ +export type UseBlockerFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TWithResolver extends boolean = false, +>( + opts: UseBlockerOpts, +) => TWithResolver extends true + ? Solid.Accessor> + : void + export function useBlocker< TRouter extends AnyRouter = RegisteredRouter, TWithResolver extends boolean = false, @@ -171,14 +191,19 @@ export function useBlocker( const router = useRouter() - const [resolver, setResolver] = Solid.createSignal({ + const idle: BlockerResolver = { status: 'idle', current: undefined, next: undefined, action: undefined, proceed: undefined, reset: undefined, - }) + } + if (isServer ?? router.isServer) { + return () => idle + } + + const [resolver, setResolver] = Solid.createSignal(idle) Solid.createEffect(() => { const blockerFnComposed = async (blockerFnArgs: BlockerFnArgs) => { diff --git a/packages/solid-router/src/useLoaderData.tsx b/packages/solid-router/src/useLoaderData.tsx index 7b56918708..c873a21838 100644 --- a/packages/solid-router/src/useLoaderData.tsx +++ b/packages/solid-router/src/useLoaderData.tsx @@ -2,7 +2,9 @@ import { useMatch } from './useMatch' import type { Accessor } from 'solid-js' import type { AnyRouter, + Register, RegisteredRouter, + RegisteredRouterOf, ResolveUseLoaderData, StrictOrFrom, UseLoaderDataResult, @@ -25,13 +27,26 @@ export type UseLoaderDataOptions< > = StrictOrFrom & UseLoaderDataBaseOptions -export type UseLoaderDataRoute = < - TRouter extends AnyRouter = RegisteredRouter, +export type UseLoaderDataRoute = < + TRouter extends AnyRouter = RegisteredRouterOf, TSelected = unknown, >( opts?: UseLoaderDataBaseOptions, ) => Accessor> +/** + * The signature of `useLoaderData`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useLoaderData` of this type. + */ +export type UseLoaderDataFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TFrom extends string | undefined = undefined, + TStrict extends boolean = true, + TSelected = unknown, +>( + opts: UseLoaderDataOptions, +) => Accessor> + export function useLoaderData< TRouter extends AnyRouter = RegisteredRouter, const TFrom extends string | undefined = undefined, diff --git a/packages/solid-router/src/useLoaderDeps.tsx b/packages/solid-router/src/useLoaderDeps.tsx index 41664f0af7..d5eb5bb526 100644 --- a/packages/solid-router/src/useLoaderDeps.tsx +++ b/packages/solid-router/src/useLoaderDeps.tsx @@ -2,7 +2,9 @@ import { useMatch } from './useMatch' import type { Accessor } from 'solid-js' import type { AnyRouter, + Register, RegisteredRouter, + RegisteredRouterOf, ResolveUseLoaderDeps, StrictOrFrom, UseLoaderDepsResult, @@ -23,13 +25,25 @@ export type UseLoaderDepsOptions< > = StrictOrFrom & UseLoaderDepsBaseOptions -export type UseLoaderDepsRoute = < - TRouter extends AnyRouter = RegisteredRouter, +export type UseLoaderDepsRoute = < + TRouter extends AnyRouter = RegisteredRouterOf, TSelected = unknown, >( opts?: UseLoaderDepsBaseOptions, ) => Accessor> +/** + * The signature of `useLoaderDeps`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useLoaderDeps` of this type. + */ +export type UseLoaderDepsFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TFrom extends string | undefined = undefined, + TSelected = unknown, +>( + opts: UseLoaderDepsOptions, +) => Accessor> + export function useLoaderDeps< TRouter extends AnyRouter = RegisteredRouter, const TFrom extends string | undefined = undefined, diff --git a/packages/solid-router/src/useLocation.tsx b/packages/solid-router/src/useLocation.tsx index 5c968443bb..06c9226d4b 100644 --- a/packages/solid-router/src/useLocation.tsx +++ b/packages/solid-router/src/useLocation.tsx @@ -3,7 +3,9 @@ import { replaceEqualDeep } from '@tanstack/router-core' import { useRouter } from './useRouter' import type { AnyRouter, + Register, RegisteredRouter, + RegisteredRouterOf, RouterState, } from '@tanstack/router-core' import type { Accessor } from 'solid-js' @@ -19,6 +21,17 @@ export type UseLocationResult< ? RouterState['location'] : TSelected +/** + * The signature of `useLocation`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useLocation` of this type. + */ +export type UseLocationFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TSelected = unknown, +>( + opts?: UseLocationBaseOptions, +) => Accessor> + export function useLocation< TRouter extends AnyRouter = RegisteredRouter, TSelected = unknown, diff --git a/packages/solid-router/src/useMatch.tsx b/packages/solid-router/src/useMatch.tsx index 8d5443cb4e..faf415ce09 100644 --- a/packages/solid-router/src/useMatch.tsx +++ b/packages/solid-router/src/useMatch.tsx @@ -1,12 +1,16 @@ import * as Solid from 'solid-js' import { invariant, replaceEqualDeep } from '@tanstack/router-core' +import { resolveRouteId } from '@tanstack/router-core/_internal/route-module' import { nearestMatchContext } from './matchContext' import { useRouter } from './useRouter' import type { AnyRouter, MakeRouteMatch, MakeRouteMatchUnion, + Register, RegisteredRouter, + RegisteredRouterOf, + RouteScopeMarker, StrictOrFrom, ThrowConstraint, ThrowOrOptional, @@ -20,13 +24,17 @@ export interface UseMatchBaseOptions< TSelected, > { select?: ( - match: MakeRouteMatch, + match: TRouter['routeTree'] extends RouteScopeMarker + ? TStrict extends true + ? MakeRouteMatch + : MakeRouteMatchUnion + : MakeRouteMatch, ) => TSelected shouldThrow?: TThrow } -export type UseMatchRoute = < - TRouter extends AnyRouter = RegisteredRouter, +export type UseMatchRoute = < + TRouter extends AnyRouter = RegisteredRouterOf, TSelected = unknown, TThrow extends boolean = true, >( @@ -55,6 +63,28 @@ export type UseMatchResult< : MakeRouteMatchUnion : TSelected +/** + * The signature of `useMatch`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useMatch` of this type. + */ +export type UseMatchFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TFrom extends string | undefined = undefined, + TStrict extends boolean = true, + TThrow extends boolean = true, + TSelected = unknown, +>( + opts: UseMatchOptions< + TRouter, + TFrom, + TStrict, + ThrowConstraint, + TSelected + >, +) => Solid.Accessor< + ThrowOrOptional, TThrow> +> + export function useMatch< TRouter extends AnyRouter = RegisteredRouter, const TFrom extends string | undefined = undefined, @@ -75,10 +105,23 @@ export function useMatch< const router = useRouter() const contextMatch = Solid.useContext(nearestMatchContext) const nearestMatch = opts.from ? undefined : contextMatch + // `from` can be the module-local id of a module installed several times: + // it resolves through the nearest match. A live match never changes route, + // so read it once without tracking. + const nearestRouteId = + resolveRouteId && opts.from + ? Solid.untrack(contextMatch[0 /* route id */]) + : undefined const match = () => { if (opts.from) { - return router.stores.getMatchStore(opts.from).get() + return router.stores + .getMatchStore( + resolveRouteId + ? resolveRouteId(router, opts.from, nearestRouteId) + : opts.from, + ) + .get() } return nearestMatch?.[1 /* match */]() @@ -107,7 +150,13 @@ export function useMatch< return undefined } - const res = opts.select ? opts.select(selectedMatch) : selectedMatch + const res = opts.select + ? opts.select( + selectedMatch as unknown as Parameters< + NonNullable + >[0], + ) + : selectedMatch if (prev === undefined) return res as TSelected return replaceEqualDeep(prev, res) as TSelected }) as any diff --git a/packages/solid-router/src/useNavigate.tsx b/packages/solid-router/src/useNavigate.tsx index 40e51ced6b..ca094d420e 100644 --- a/packages/solid-router/src/useNavigate.tsx +++ b/packages/solid-router/src/useNavigate.tsx @@ -1,29 +1,71 @@ import * as Solid from 'solid-js' +import { isServer } from '@tanstack/router-core/isServer' +import { nearestMatchContext } from './matchContext' import { useRouter } from './useRouter' import type { AnyRouter, + CompatibleRouteScope, FromPathOption, NavigateOptions, + Register, RegisteredRouter, + RegisteredRouterOf, + RouteModuleScope, UseNavigateResult, } from '@tanstack/router-core' +/** + * The signature of `useNavigate`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useNavigate` of this type. + */ +export type UseNavigateFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TDefaultFrom extends string = string, +>(_defaultOpts?: { + from?: FromPathOption + _module?: RouteModuleScope> +}) => UseNavigateResult + export function useNavigate< TRouter extends AnyRouter = RegisteredRouter, TDefaultFrom extends string = string, >(_defaultOpts?: { from?: FromPathOption -}): UseNavigateResult { +}): UseNavigateResult { const router = useRouter() + // Route-module APIs also pass the internal `_module`/`_fromRoute` scope, + // which resolves to the installation of the nearest match. A live match + // never changes route, so read it once without tracking. + const defaults = _defaultOpts as + | { from?: string; _module?: RouteModuleScope; _fromRoute?: string } + | undefined + const routeId = Solid.useContext(nearestMatchContext)[0 /* routeId */]() return ((options: NavigateOptions) => { return router.navigate({ + _module: defaults?._module, + _fromRoute: defaults?._fromRoute, + _nearestRoute: routeId, ...options, - from: options.from ?? _defaultOpts?.from, + from: options.from ?? defaults?.from, }) - }) as UseNavigateResult + }) as UseNavigateResult } +/** + * The signature of `Navigate`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `Navigate` of this type. + */ +export type NavigateComponentFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TFrom extends string = string, + const TTo extends string | undefined = undefined, + const TMaskFrom extends string = TFrom, + const TMaskTo extends string = '', +>( + props: NavigateOptions, +) => null + export function Navigate< TRouter extends AnyRouter = RegisteredRouter, const TFrom extends string = string, @@ -31,13 +73,18 @@ export function Navigate< const TMaskFrom extends string = TFrom, const TMaskTo extends string = '', >(props: NavigateOptions): null { - const { navigate } = useRouter() + const router = useRouter() + if (isServer ?? router.isServer) { + return null + } + const navigate = useNavigate() - Solid.onMount(() => { - navigate({ - ...props, - }) - }) + Solid.createEffect( + Solid.on( + () => ({ ...props }), + (options) => navigate(options), + ), + ) return null } diff --git a/packages/solid-router/src/useParams.tsx b/packages/solid-router/src/useParams.tsx index bec382bbb9..fd41295284 100644 --- a/packages/solid-router/src/useParams.tsx +++ b/packages/solid-router/src/useParams.tsx @@ -2,7 +2,9 @@ import { useMatch } from './useMatch' import type { Accessor } from 'solid-js' import type { AnyRouter, + Register, RegisteredRouter, + RegisteredRouterOf, ResolveUseParams, StrictOrFrom, ThrowConstraint, @@ -30,8 +32,8 @@ export type UseParamsOptions< > = StrictOrFrom & UseParamsBaseOptions -export type UseParamsRoute = < - TRouter extends AnyRouter = RegisteredRouter, +export type UseParamsRoute = < + TRouter extends AnyRouter = RegisteredRouterOf, TSelected = unknown, TThrow extends boolean = true, >( @@ -46,6 +48,28 @@ export type UseParamsRoute = < ThrowOrOptional, TThrow> > +/** + * The signature of `useParams`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useParams` of this type. + */ +export type UseParamsFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TFrom extends string | undefined = undefined, + TStrict extends boolean = true, + TThrow extends boolean = true, + TSelected = unknown, +>( + opts: UseParamsOptions< + TRouter, + TFrom, + TStrict, + ThrowConstraint, + TSelected + >, +) => Accessor< + ThrowOrOptional, TThrow> +> + export function useParams< TRouter extends AnyRouter = RegisteredRouter, const TFrom extends string | undefined = undefined, diff --git a/packages/solid-router/src/useRouteContext.ts b/packages/solid-router/src/useRouteContext.ts index 4a9ef1d786..07220a95ec 100644 --- a/packages/solid-router/src/useRouteContext.ts +++ b/packages/solid-router/src/useRouteContext.ts @@ -2,19 +2,34 @@ import { useMatch } from './useMatch' import type { Accessor } from 'solid-js' import type { AnyRouter, + Register, RegisteredRouter, + RegisteredRouterOf, UseRouteContextBaseOptions, UseRouteContextOptions, UseRouteContextResult, } from '@tanstack/router-core' -export type UseRouteContextRoute = < - TRouter extends AnyRouter = RegisteredRouter, +export type UseRouteContextRoute = < + TRouter extends AnyRouter = RegisteredRouterOf, TSelected = unknown, >( opts?: UseRouteContextBaseOptions, ) => Accessor> +/** + * The signature of `useRouteContext`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useRouteContext` of this type. + */ +export type UseRouteContextFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TFrom extends string | undefined = undefined, + TStrict extends boolean = true, + TSelected = unknown, +>( + opts: UseRouteContextOptions, +) => Accessor> + export function useRouteContext< TRouter extends AnyRouter = RegisteredRouter, const TFrom extends string | undefined = undefined, diff --git a/packages/solid-router/src/useRouter.tsx b/packages/solid-router/src/useRouter.tsx index 344afe90ed..df8919b347 100644 --- a/packages/solid-router/src/useRouter.tsx +++ b/packages/solid-router/src/useRouter.tsx @@ -1,6 +1,21 @@ import * as Solid from 'solid-js' import { routerContext } from './routerContext' -import type { AnyRouter, RegisteredRouter } from '@tanstack/router-core' +import type { + AnyRouter, + Register, + RegisteredRouter, + RegisteredRouterOf, +} from '@tanstack/router-core' + +/** + * The signature of `useRouter`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useRouter` of this type. + */ +export type UseRouterFn = < + TRouter extends AnyRouter = RegisteredRouterOf, +>(opts?: { + warn?: boolean +}) => TRouter export function useRouter(opts?: { warn?: boolean diff --git a/packages/solid-router/src/useRouterState.tsx b/packages/solid-router/src/useRouterState.tsx index 382e35d2d2..e822f9829e 100644 --- a/packages/solid-router/src/useRouterState.tsx +++ b/packages/solid-router/src/useRouterState.tsx @@ -4,7 +4,9 @@ import { replaceEqualDeep } from '@tanstack/router-core' import { useRouter } from './useRouter' import type { AnyRouter, + Register, RegisteredRouter, + RegisteredRouterOf, RouterState, } from '@tanstack/router-core' import type { Accessor } from 'solid-js' @@ -19,6 +21,17 @@ export type UseRouterStateResult< TSelected, > = unknown extends TSelected ? RouterState : TSelected +/** + * The signature of `useRouterState`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useRouterState` of this type. + */ +export type UseRouterStateFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TSelected = unknown, +>( + opts?: UseRouterStateOptions, +) => Accessor> + export function useRouterState< TRouter extends AnyRouter = RegisteredRouter, TSelected = unknown, @@ -36,7 +49,7 @@ export function useRouterState< // The expression must stay inlined in the `if` so bundlers fold the // browser-build constant `isServer = false` and drop this server block. if (isServer ?? router.isServer) { - const state = router.stores.__store.get() as RouterState< + const state = router.stores.__store.get() as unknown as RouterState< TRouter['routeTree'] > const selected = ( @@ -56,7 +69,11 @@ export function useRouterState< const select = opts.select return Solid.createMemo((prev: TSelected | undefined) => { - const res = select(router.stores.__store.get()) + const res = select( + router.stores.__store.get() as unknown as RouterState< + TRouter['routeTree'] + >, + ) if (prev === undefined) return res return replaceEqualDeep(prev, res) }) as Accessor> diff --git a/packages/solid-router/src/useSearch.tsx b/packages/solid-router/src/useSearch.tsx index 79ed25ccb4..37a6ade190 100644 --- a/packages/solid-router/src/useSearch.tsx +++ b/packages/solid-router/src/useSearch.tsx @@ -2,7 +2,9 @@ import { useMatch } from './useMatch' import type { Accessor } from 'solid-js' import type { AnyRouter, + Register, RegisteredRouter, + RegisteredRouterOf, ResolveUseSearch, StrictOrFrom, ThrowConstraint, @@ -30,8 +32,8 @@ export type UseSearchOptions< > = StrictOrFrom & UseSearchBaseOptions -export type UseSearchRoute = < - TRouter extends AnyRouter = RegisteredRouter, +export type UseSearchRoute = < + TRouter extends AnyRouter = RegisteredRouterOf, TSelected = unknown, TThrow extends boolean = true, >( @@ -46,6 +48,28 @@ export type UseSearchRoute = < ThrowOrOptional, TThrow> > +/** + * The signature of `useSearch`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useSearch` of this type. + */ +export type UseSearchFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TFrom extends string | undefined = undefined, + TStrict extends boolean = true, + TThrow extends boolean = true, + TSelected = unknown, +>( + opts: UseSearchOptions< + TRouter, + TFrom, + TStrict, + ThrowConstraint, + TSelected + >, +) => Accessor< + ThrowOrOptional, TThrow> +> + export function useSearch< TRouter extends AnyRouter = RegisteredRouter, const TFrom extends string | undefined = undefined, diff --git a/packages/solid-router/tests/blocker-server.test.tsx b/packages/solid-router/tests/blocker-server.test.tsx new file mode 100644 index 0000000000..899436d676 --- /dev/null +++ b/packages/solid-router/tests/blocker-server.test.tsx @@ -0,0 +1,32 @@ +import { afterEach, expect, test, vi } from 'vitest' +import { cleanup, render, screen } from '@solidjs/testing-library' +import { + RouterContextProvider, + createMemoryHistory, + createRootRoute, + createRouter, + useBlocker, +} from '../src' + +afterEach(cleanup) + +test('a server router does not register navigation blockers', async () => { + const history = createMemoryHistory({ initialEntries: ['/'] }) + const block = vi.spyOn(history, 'block') + const router = createRouter({ + routeTree: createRootRoute(), + history, + isServer: true, + }) + function Observer() { + const state = useBlocker({ shouldBlockFn: () => true, withResolver: true }) + return {state().status} + } + render(() => ( + + {() => } + + )) + await screen.findByText('idle') + expect(block).not.toHaveBeenCalled() +}) diff --git a/packages/solid-router/tests/navigate-options-parity.test.tsx b/packages/solid-router/tests/navigate-options-parity.test.tsx new file mode 100644 index 0000000000..287d5fc9ba --- /dev/null +++ b/packages/solid-router/tests/navigate-options-parity.test.tsx @@ -0,0 +1,74 @@ +import { createSignal } from 'solid-js' +import { afterEach, expect, test } from 'vitest' +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@solidjs/testing-library' +import { + Navigate, + Outlet, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(cleanup) + +test('Navigate responds to option changes while mounted', async () => { + function component() { + const [id, setId] = createSignal('one') + const [q, setQ] = createSignal('first') + const [replace, setReplace] = createSignal(true) + return ( + <> + + + + + + ) + } + const root = createRootRoute({ component }) + const item = createRoute({ getParentRoute: () => root, path: '/items/$id' }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createRouter({ routeTree: root.addChildren([item]), history }) + render(() => ) + await waitFor(() => + expect(router.state.location.href).toBe('/items/one?q=first'), + ) + const initialLength = history.length + await fireEvent.click(screen.getByText('Change params')) + await waitFor(() => + expect(router.state.location.href).toBe('/items/two?q=first'), + ) + expect(history.length).toBe(initialLength + 1) + await fireEvent.click(screen.getByText('Change search')) + await waitFor(() => + expect(router.state.location.href).toBe('/items/two?q=second'), + ) + expect(history.length).toBe(initialLength + 1) +}) diff --git a/packages/solid-router/tests/routeApi.test-d.tsx b/packages/solid-router/tests/routeApi.test-d.tsx index e6770e2652..1e19789806 100644 --- a/packages/solid-router/tests/routeApi.test-d.tsx +++ b/packages/solid-router/tests/routeApi.test-d.tsx @@ -124,7 +124,7 @@ describe('getRouteApi', () => { test('Link', () => { const Link = invoiceRouteApi.Link expectTypeOf(Link).toEqualTypeOf< - LinkComponentRoute<'/invoices/$invoiceId'> + LinkComponentRoute<'/invoices/$invoiceId', { router: DefaultRouter }> >() }) }) diff --git a/packages/solid-router/tests/server/Navigate.test.tsx b/packages/solid-router/tests/server/Navigate.test.tsx new file mode 100644 index 0000000000..589b3e2b8c --- /dev/null +++ b/packages/solid-router/tests/server/Navigate.test.tsx @@ -0,0 +1,34 @@ +import { renderToString } from 'solid-js/web' +import { expect, test, vi } from 'vitest' +import { + Navigate, + RouterContextProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../../src' + +test('Navigate leaves the request location unchanged during server rendering', () => { + const root = createRootRoute() + const next = createRoute({ getParentRoute: () => root, path: '/next' }) + const router = createRouter({ + routeTree: root.addChildren([next]), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, + }) + const navigate = vi.spyOn(router, 'navigate') + const html = renderToString(() => ( + + {() => ( + <> + + Request content + + )} + + )) + expect(html).toContain('Request content') + expect(navigate).not.toHaveBeenCalled() + expect(router.state.location.href).toBe('/') +}) diff --git a/packages/solid-router/vite.config.ts b/packages/solid-router/vite.config.ts index 3c9e49ec37..033f3da887 100644 --- a/packages/solid-router/vite.config.ts +++ b/packages/solid-router/vite.config.ts @@ -56,6 +56,7 @@ export default defineConfig((env) => tsconfigPath: './tsconfig.build.json', entry: [ './src/index.tsx', + './src/route-module-internal.ts', './src/index.dev.tsx', './src/ssr/client.ts', './src/ssr/server.ts', diff --git a/packages/solid-start/package.json b/packages/solid-start/package.json index 5b197ba97c..97796dfc6f 100644 --- a/packages/solid-start/package.json +++ b/packages/solid-start/package.json @@ -105,7 +105,13 @@ "default": "./dist/esm/client-only.js" } }, - "./package.json": "./package.json" + "./package.json": "./package.json", + "./_internal/route-module": { + "import": { + "types": "./dist/esm/route-module-internal.d.ts", + "default": "./dist/esm/route-module-internal.js" + } + } }, "sideEffects": false, "files": [ @@ -116,7 +122,7 @@ "!skills/_artifacts" ], "engines": { - "node": ">=22.12.0" + "node": ">=22.22.0" }, "dependencies": { "@tanstack/solid-router": "workspace:*", diff --git a/packages/solid-start/src/index.ts b/packages/solid-start/src/index.ts index bc5560978d..dd6cc74e07 100644 --- a/packages/solid-start/src/index.ts +++ b/packages/solid-start/src/index.ts @@ -1,5 +1,6 @@ export { useServerFn } from './useServerFn' export * from '@tanstack/start-client-core' +export type { StartModuleRequirements } from '@tanstack/start-client-core' // Explicit re-exports shadow `export *` above so these public-API names are // registered on the namespace at link time (via Vite SSR's `defineExport` // at fileStartIndex), surviving the cold-start SSR cycle through user diff --git a/packages/solid-start/src/route-module-internal.ts b/packages/solid-start/src/route-module-internal.ts new file mode 100644 index 0000000000..8642a07276 --- /dev/null +++ b/packages/solid-start/src/route-module-internal.ts @@ -0,0 +1 @@ +export { createStartModule } from '@tanstack/start-client-core/_internal/route-module' diff --git a/packages/solid-start/vite.config.ts b/packages/solid-start/vite.config.ts index 2c1a42d0e4..e7d97bb1ff 100644 --- a/packages/solid-start/vite.config.ts +++ b/packages/solid-start/vite.config.ts @@ -26,6 +26,7 @@ export default mergeConfig( exclude: ['./src/default-entry'], entry: [ './src/index.ts', + './src/route-module-internal.ts', './src/client.tsx', './src/hydration.ts', './src/client-rpc.ts', diff --git a/packages/start-client-core/package.json b/packages/start-client-core/package.json index c74dce13aa..f55b0256c5 100644 --- a/packages/start-client-core/package.json +++ b/packages/start-client-core/package.json @@ -78,7 +78,13 @@ "default": "./dist/esm/hydration/runtime.js" } }, - "./package.json": "./package.json" + "./package.json": "./package.json", + "./_internal/route-module": { + "import": { + "types": "./dist/esm/route-module-internal.d.ts", + "default": "./dist/esm/route-module-internal.js" + } + } }, "imports": { "#tanstack-start-entry": { diff --git a/packages/start-client-core/src/createMiddleware.ts b/packages/start-client-core/src/createMiddleware.ts index 9b19833d09..7345ebdf14 100644 --- a/packages/start-client-core/src/createMiddleware.ts +++ b/packages/start-client-core/src/createMiddleware.ts @@ -1,4 +1,8 @@ -import type { StartInstanceOptions } from './createStart' +import type { + StartModuleIdOf, + StartModuleRequiredContext, + ValidateModuleMiddlewareConsumer, +} from './createStartModule' import type { AnyServerFn, ConstrainValidator, @@ -67,7 +71,7 @@ export type CreateMiddlewareResult< export interface FunctionMiddleware< TRegister, -> extends FunctionMiddlewareAfterMiddleware { +> extends FunctionMiddlewareAfterMiddleware { middleware: ( middlewares: Constrain< TNewMiddlewares, @@ -134,6 +138,7 @@ export interface FunctionMiddlewareTypes< in out TClientSendContext, > { type: 'function' + startModule: StartModuleIdOf middlewares: TMiddlewares input: ResolveValidatorInput allInput: IntersectAllValidatorInputs @@ -303,11 +308,14 @@ export type GlobalFetchRequestContext = Register extends { ? TRequestContext : AnyContext -export type GlobalServerRequestContext = TRegister extends { - config: StartInstanceOptions -} - ? AssignAllMiddleware - : AnyContext +export type GlobalServerRequestContext = Assign< + StartModuleRequiredContext, 'requestContext'>, + TRegister extends { + config: { '~types': { requestMiddleware: infer TRequestMiddlewares } } + } + ? AssignAllMiddleware + : AnyContext +> type __AssignAllServerRequestContext< TMiddlewares, @@ -340,11 +348,14 @@ export type AssignAllServerFnContext< > > -type GlobalServerFnContext = TRegister extends { - config: StartInstanceOptions -} - ? AssignAllMiddleware - : AnyContext +type GlobalServerFnContext = Assign< + StartModuleRequiredContext, 'functionContext'>, + TRegister extends { + config: { '~types': { functionMiddleware: infer TFunctionMiddlewares } } + } + ? AssignAllMiddleware + : AnyContext +> type __AssignAllServerFnContext< TMiddlewares, @@ -420,7 +431,8 @@ export interface FunctionMiddlewareServer< TServerSendContext, TNewServerContext, TSendContext - >, + > & + ValidateModuleMiddlewareConsumer, ) => FunctionMiddlewareAfterServer< TRegister, TMiddlewares, @@ -726,6 +738,7 @@ export interface RequestMiddlewareTypes< TServerContext, > { type: 'request' + startModule: StartModuleIdOf // this only exists so we can use request middlewares in server functions allInput: undefined // this only exists so we can use request middlewares in server functions @@ -747,7 +760,8 @@ export interface RequestMiddlewareAfterMiddleware export interface RequestMiddlewareServer { server: ( - fn: RequestServerFn, + fn: RequestServerFn & + ValidateModuleMiddlewareConsumer, ) => RequestMiddlewareAfterServer } diff --git a/packages/start-client-core/src/createServerFn.ts b/packages/start-client-core/src/createServerFn.ts index ea1566aa37..fe72eb18fc 100644 --- a/packages/start-client-core/src/createServerFn.ts +++ b/packages/start-client-core/src/createServerFn.ts @@ -29,6 +29,7 @@ import type { IntersectAllValidatorInputs, IntersectAllValidatorOutputs, } from './createMiddleware' +import type { ValidateModuleMiddlewareConsumer } from './createStartModule' export type ServerFnStrict = boolean | { input?: boolean; output?: boolean } @@ -723,7 +724,8 @@ export interface ServerFnHandler< TInputValidator, TNewResponse, TStrict - >, + > & + ValidateModuleMiddlewareConsumer, ) => Fetcher } diff --git a/packages/start-client-core/src/createStart.ts b/packages/start-client-core/src/createStart.ts index 0929bc3b31..f2962752fa 100644 --- a/packages/start-client-core/src/createStart.ts +++ b/packages/start-client-core/src/createStart.ts @@ -7,6 +7,8 @@ import type { CreateMiddlewareFn, } from './createMiddleware' import type { CustomFetch } from './createServerFn' +import type { AnyStartModule, WithStartModules } from './createStartModule' +import type { StartOptionList } from './startOptionList' import type { AnySerializationAdapter, Register, @@ -18,12 +20,18 @@ export interface StartInstanceOptions< in out TDefaultSsr, in out TRequestMiddlewares, in out TFunctionMiddlewares, + in out TStartModules = [], + in out TOwnRequestMiddlewares = TRequestMiddlewares, + in out TOwnFunctionMiddlewares = TFunctionMiddlewares, > { '~types': StartInstanceTypes< TSerializationAdapters, TDefaultSsr, TRequestMiddlewares, - TFunctionMiddlewares + TFunctionMiddlewares, + TStartModules, + TOwnRequestMiddlewares, + TOwnFunctionMiddlewares > serializationAdapters?: TSerializationAdapters defaultSsr?: TDefaultSsr @@ -55,6 +63,9 @@ export interface StartInstance< in out TDefaultSsr, in out TRequestMiddlewares, in out TFunctionMiddlewares, + in out TStartModules = [], + in out TOwnRequestMiddlewares = TRequestMiddlewares, + in out TOwnFunctionMiddlewares = TFunctionMiddlewares, > { getOptions: () => | Promise< @@ -62,14 +73,20 @@ export interface StartInstance< TSerializationAdapters, TDefaultSsr, TRequestMiddlewares, - TFunctionMiddlewares + TFunctionMiddlewares, + TStartModules, + TOwnRequestMiddlewares, + TOwnFunctionMiddlewares > > | StartInstanceOptions< TSerializationAdapters, TDefaultSsr, TRequestMiddlewares, - TFunctionMiddlewares + TFunctionMiddlewares, + TStartModules, + TOwnRequestMiddlewares, + TOwnFunctionMiddlewares > createMiddleware: CreateMiddlewareFn } @@ -79,11 +96,17 @@ export interface StartInstanceTypes< in out TDefaultSsr, in out TRequestMiddlewares, in out TFunctionMiddlewares, + in out TStartModules = [], + in out TOwnRequestMiddlewares = TRequestMiddlewares, + in out TOwnFunctionMiddlewares = TFunctionMiddlewares, > { serializationAdapters: TSerializationAdapters defaultSsr: TDefaultSsr requestMiddleware: TRequestMiddlewares functionMiddleware: TFunctionMiddlewares + startModules: TStartModules + ownRequestMiddleware: TOwnRequestMiddlewares + ownFunctionMiddleware: TOwnFunctionMiddlewares } function dedupeSerializationAdapters( @@ -101,9 +124,45 @@ function dedupeSerializationAdapters( } } +const startModuleOptionKeys = [ + 'serializationAdapters', + 'requestMiddleware', + 'functionMiddleware', +] as const + +/** + * Returns the options with the contributions of the installed route modules + * appended: the application's own entries first, each entry once. Middleware + * requirements are type-only. The factory's options object is not changed, so + * repeated `getOptions()` calls never accumulate. + */ +function installStartModules>( + options: T, + modules: ReadonlyArray, +): T { + const installed: Record = { ...options } + const fragments = Array.from(new Set(modules), (module) => + module.getOptions(), + ) + for (const key of startModuleOptionKeys) { + const merged = new Set(options[key]) + for (const fragment of fragments) { + fragment[key]?.forEach((entry: any) => merged.add(entry)) + } + installed[key] = Array.from(merged) + } + return installed as T +} + function dedupeOptions< - T extends { serializationAdapters?: ReadonlyArray }, + T extends { + serializationAdapters?: ReadonlyArray + extends?: ReadonlyArray + }, >(options: T): T { + if (options.extends) { + options = installStartModules(options, options.extends) + } if (options.serializationAdapters) { const deduped = new Set() dedupeSerializationAdapters( @@ -115,39 +174,104 @@ function dedupeOptions< return options } +/** + * Options of `createStart`: the Start instance options plus the Start + * fragments of installed route modules (`extends`). + */ +export type CreateStartOptions< + TSerializationAdapters, + TDefaultSsr, + TRequestMiddlewares, + TFunctionMiddlewares, + TStartModules, +> = Omit< + StartInstanceOptions< + TSerializationAdapters, + TDefaultSsr, + TRequestMiddlewares, + TFunctionMiddlewares + >, + '~types' +> & { + /** + * Start fragments of route modules to install, usually `startModules` from + * the generated `startModules.gen.ts`. Their serialization adapters and + * middleware run after the application's own. + */ + extends?: TStartModules +} + +type AnyCreateStartOptions = CreateStartOptions< + ReadonlyArray, + SSROption, + ReadonlyArray, + ReadonlyArray, + ReadonlyArray +> + export const createStart = < const TSerializationAdapters extends ReadonlyArray = [], TDefaultSsr extends SSROption = SSROption, const TRequestMiddlewares extends ReadonlyArray = [], const TFunctionMiddlewares extends ReadonlyArray = [], + const TStartModules extends ReadonlyArray = [], + const TOptions extends + | AnyCreateStartOptions + | Promise = + | AnyCreateStartOptions + | Promise, >( - getOptions: () => + getOptions: (() => | Promise< - Omit< - StartInstanceOptions< - TSerializationAdapters, - TDefaultSsr, - TRequestMiddlewares, - TFunctionMiddlewares - >, - '~types' - > - > - | Omit< - StartInstanceOptions< + CreateStartOptions< TSerializationAdapters, TDefaultSsr, TRequestMiddlewares, - TFunctionMiddlewares - >, - '~types' - >, + TFunctionMiddlewares, + TStartModules + > + > + | CreateStartOptions< + TSerializationAdapters, + TDefaultSsr, + TRequestMiddlewares, + TFunctionMiddlewares, + TStartModules + >) & + (() => TOptions), ): StartInstance< - TSerializationAdapters, + WithStartModules< + StartOptionList< + Awaited, + 'serializationAdapters', + TSerializationAdapters + >, + StartOptionList, 'extends', TStartModules>, + 'serializationAdapters' + >, TDefaultSsr, - TRequestMiddlewares, - TFunctionMiddlewares + WithStartModules< + StartOptionList< + Awaited, + 'requestMiddleware', + TRequestMiddlewares + >, + StartOptionList, 'extends', TStartModules>, + 'requestMiddleware' + >, + WithStartModules< + StartOptionList< + Awaited, + 'functionMiddleware', + TFunctionMiddlewares + >, + StartOptionList, 'extends', TStartModules>, + 'functionMiddleware' + >, + StartOptionList, 'extends', TStartModules>, + StartOptionList, 'requestMiddleware', TRequestMiddlewares>, + StartOptionList, 'functionMiddleware', TFunctionMiddlewares> > => { return { // A synchronous factory returns synchronously so callers can skip a @@ -160,18 +284,21 @@ export const createStart = < : dedupeOptions(options) }, createMiddleware: createMiddleware, - } as StartInstance< - TSerializationAdapters, - TDefaultSsr, - TRequestMiddlewares, - TFunctionMiddlewares - > + } as StartInstance } -export type AnyStartInstance = StartInstance -export type AnyStartInstanceOptions = StartInstanceOptions +export type AnyStartInstance = StartInstance +export type AnyStartInstanceOptions = StartInstanceOptions< + any, + any, + any, + any, + any, + any, + any +> -declare module '@tanstack/router-core' { +declare module '@tanstack/router-core/extensions' { interface SerializableExtensions { serverFn: { [TSS_SERVER_FUNCTION]: true } } diff --git a/packages/start-client-core/src/createStartModule.ts b/packages/start-client-core/src/createStartModule.ts new file mode 100644 index 0000000000..4a13646d76 --- /dev/null +++ b/packages/start-client-core/src/createStartModule.ts @@ -0,0 +1,797 @@ +import type { + AnyFunctionMiddleware, + AnyRequestMiddleware, + AssignAllServerFnContext, + AssignAllServerRequestContext, + GlobalFetchRequestContext, +} from './createMiddleware' +import type { + AnyStartInstance, + CreateStartOptions, + StartInstanceOptions, +} from './createStart' +import type { StartOptionList } from './startOptionList' +import type { + AnySerializationAdapter, + Assign, + SSROption, +} from '@tanstack/router-core' + +/** Type-only requirements of route modules, keyed by their package names. */ +export interface StartModuleRequirements {} + +/** A module's middleware register, independent of its contributed fragment. */ +export interface StartModuleRegister { + startModule: TModuleId +} + +export type StartModuleRequiredContext< + TModuleId extends string, + TKind extends 'requestContext' | 'functionContext', +> = [TModuleId] extends [never] + ? undefined + : TModuleId extends keyof StartModuleRequirements + ? TKind extends keyof StartModuleRequirements[TModuleId] + ? StartModuleRequirements[TModuleId][TKind] + : undefined + : undefined + +export type StartModuleIdOf = TRegister extends { + startModule: infer TModuleId extends string +} + ? TModuleId + : never + +/** Executable contributions; required context is declared in the registry. */ +export interface StartModuleOptions< + in out TSerializationAdapters, + in out TRequestMiddlewares, + in out TFunctionMiddlewares, +> { + serializationAdapters?: TSerializationAdapters + requestMiddleware?: TRequestMiddlewares + functionMiddleware?: TFunctionMiddlewares +} + +export interface StartModule< + in out TModuleId extends string, + in out TSerializationAdapters, + in out TRequestMiddlewares, + in out TFunctionMiddlewares, +> { + id: TModuleId + getOptions: () => StartModuleOptions< + TSerializationAdapters, + TRequestMiddlewares, + TFunctionMiddlewares + > +} + +export type AnyStartModule = StartModule + +/** Application settings cannot be applied by an executable module fragment. */ +type ApplicationOnlyOptions = { + [K in Exclude< + keyof CreateStartOptions, + StartModuleOptionKey + >]?: never +} + +export type CreateStartModuleFn = < + const TSerializationAdapters extends ReadonlyArray = + [], + const TRequestMiddlewares extends ReadonlyArray = [], + const TFunctionMiddlewares extends ReadonlyArray = [], + const TOptions extends { + serializationAdapters?: ReadonlyArray + requestMiddleware?: ReadonlyArray + functionMiddleware?: ReadonlyArray + } = StartModuleOptions< + TSerializationAdapters, + TRequestMiddlewares, + TFunctionMiddlewares + >, +>( + getOptions: (() => StartModuleOptions< + TSerializationAdapters, + TRequestMiddlewares, + TFunctionMiddlewares + > & + ApplicationOnlyOptions) & + (() => TOptions), +) => StartModule< + TModuleId, + StartOptionList, + StartOptionList, + StartOptionList +> + +/** @experimental Bound by generated scopes to the module's package name. */ +export function createStartModule( + moduleId: TModuleId, +): CreateStartModuleFn { + return ((getOptions) => ({ + id: moduleId, + getOptions, + })) as CreateStartModuleFn +} + +/** The contributions visible to a module's server functions and routes. */ +export type StartModuleConfig = + StartInstanceOptions< + StartModuleOption, + SSROption, + StartModuleOption, + StartModuleOption + > + +type StartModuleOptionKey = + | 'serializationAdapters' + | 'requestMiddleware' + | 'functionMiddleware' + +type StartModuleOption = + TModule extends StartModule< + any, + infer TSerializationAdapters, + infer TRequestMiddlewares, + infer TFunctionMiddlewares + > + ? { + serializationAdapters: TSerializationAdapters + requestMiddleware: TRequestMiddlewares + functionMiddleware: TFunctionMiddlewares + }[TKey] + : [] + +type Entries = TList extends ReadonlyArray ? TEntry : never + +type StartModulesEntries< + TModules, + TKey extends StartModuleOptionKey, + TEntries extends Array = [], +> = TModules extends readonly [infer TModule, ...infer TRest] + ? StartModuleOption extends infer TList extends + ReadonlyArray + ? StartModulesEntries + : TEntries + : TModules extends readonly [] + ? TEntries + : Array< + TEntries[number] | Entries, TKey>> + > + +export type WithStartModules< + TOwn extends ReadonlyArray, + TModules, + TKey extends StartModuleOptionKey, +> = TModules extends readonly [] + ? TOwn + : [...TOwn, ...StartModulesEntries] + +type InstanceTypes = Awaited< + ReturnType +>['~types'] + +type IsAny = 0 extends 1 & T ? true : false + +type ProvenModuleId = [TModule] extends [ + AnyStartModule, +] + ? IsAny extends true + ? never + : [TModule['id']] extends [TId] + ? TId extends TModule['id'] + ? TId + : never + : never + : never + +type Installed = + IsAny extends true + ? 'Cannot establish route module installation from an unknown extends list' + : TModules extends ReadonlyArray + ? number extends TModules['length'] + ? 'Cannot establish route module installation from a non-tuple extends list' + : TId extends { + [K in keyof TModules]: ProvenModuleId + }[number] + ? true + : `Route module '${TId}' is not installed: add 'extends: startModules' to createStart()` + : 'Cannot establish route module installation from an unknown extends list' + +type HasContributions = + Entries> extends never + ? false + : true + +type ValidateInstalled = TRequired extends readonly [ + infer TModule extends AnyStartModule, + ...infer TRest, +] + ? HasContributions extends false + ? ValidateInstalled + : Exclude, true> extends infer TError + ? [TError] extends [never] + ? ValidateInstalled + : TError + : never + : TRequired extends readonly [] + ? true + : 'Cannot establish required fragments from a non-tuple module list' + +type MissingKeys = Exclude & string + +type IncompatibleKeys = { + [K in keyof TNeed]-?: K extends keyof THave + ? [THave[K]] extends [TNeed[K]] + ? never + : K + : never +}[keyof TNeed] & + string + +type ValidateContext< + TId extends string, + TPhase extends string, + TProvided, + TRequired, + TWhere extends string = '', +> = [TRequired] extends [never] + ? `Route module '${TId}' declares impossible ${TPhase} context${TWhere}` + : [TRequired] extends [undefined] + ? true + : IsAny extends true + ? `Cannot establish ${TPhase} context for route module '${TId}' from any${TWhere}` + : [TProvided] extends [TRequired] + ? true + : [MissingKeys] extends [never] + ? [IncompatibleKeys] extends [never] + ? `Route module '${TId}' requires compatible ${TPhase} context${TWhere}` + : `Route module '${TId}' requires ${TPhase} context with incompatible field '${IncompatibleKeys}'${TWhere}` + : `Route module '${TId}' requires ${TPhase} context '${MissingKeys}' that is not provided${TWhere}` + +type ValidateConsumer< + TId extends string, + TPhase extends 'request' | 'function', + TContext, + TWhere extends string = '', +> = [TId] extends [never] + ? true + : TId extends unknown + ? ValidateContext< + TId, + 'request', + TContext, + StartModuleRequiredContext, + TWhere + > extends infer TRequest + ? [TRequest] extends [true] + ? TPhase extends 'function' + ? ValidateContext< + TId, + 'function', + TContext, + StartModuleRequiredContext, + TWhere + > + : true + : TRequest + : never + : never + +type RequiredContextKeys = [T] extends [never] + ? 'impossible' + : [T] extends [undefined] + ? never + : T extends unknown + ? keyof NonNullable + : never + +type RequiredContextKeysFor = TId extends string + ? + | RequiredContextKeys> + | RequiredContextKeys> + : never + +type ConsumerIds = TId extends string + ? + | RequiredContextKeys> + | RequiredContextKeys< + StartModuleRequiredContext + > extends never + ? never + : TId + : never + +type MiddlewareWork = { + middleware: TMiddleware + moduleId: TId + expanded: TExpanded +} + +type TagList = + IsAny extends true + ? Array> + : TList extends undefined + ? [] + : TList extends ReadonlyArray + ? { [K in keyof TList]: MiddlewareWork } + : Array> + +type TaggedContributions< + TModules, + TKey extends 'requestMiddleware' | 'functionMiddleware', + TEntries extends ReadonlyArray> = [], +> = TModules extends readonly [ + infer TModule extends AnyStartModule, + ...infer TRest, +] + ? TagList< + StartModuleOption, + TModule['id'] + > extends infer TTagged extends ReadonlyArray< + MiddlewareWork + > + ? TaggedContributions + : never + : TModules extends readonly [] + ? TEntries + : Array> + +type MiddlewareTypes = T extends { '~types': infer TTypes } ? TTypes : never + +type MiddlewareOwner = + MiddlewareTypes extends { + startModule: infer TId extends string + } + ? [TId] extends [never] + ? TFallback + : TId + : TFallback + +type NestedMiddleware = + MiddlewareTypes extends { middlewares: infer TList } ? TList : undefined + +type ContextState< + TContext = unknown, + TSeen = unknown, + TWriter extends string = string, +> = { + context: TContext + seen: TSeen + writer: TWriter +} + +type ContextPropertyKey = TKey extends number + ? number extends TKey + ? `${number}` | 'NaN' | 'Infinity' | '-Infinity' + : `${TKey}` + : TKey + +/** Index signatures also include template patterns such as `${number}`. */ +type HasContextIndex = true extends ( + TKeys extends PropertyKey + ? {} extends Record + ? true + : false + : never +) + ? true + : false + +type OverlappingContextValues< + TContext, + TKey extends PropertyKey, +> = TContext[keyof TContext & + keyof { + [K in keyof TContext as [ + ContextPropertyKey & ContextPropertyKey, + ] extends [never] + ? never + : K]: unknown + }] + +type GuaranteedContextProperties = { + [K in keyof TContext as {} extends Pick ? never : K]: TContext[K] +} + +type HasOptionalContextProperties = + keyof TContext extends keyof GuaranteedContextProperties + ? false + : true + +type WidenOptionalContext = { + [K in keyof TContext]: {} extends Pick + ? TContext[K] | OverlappingContextValues + : TContext[K] +} + +type RetainedContext = { + [K in keyof TLeft as ContextPropertyKey extends ContextPropertyKey< + keyof GuaranteedContextProperties + > + ? never + : K]: TLeft[K] | OverlappingContextValues +} + +/** + * Runtime context merges use JavaScript property identity. Numeric and string + * spellings must overwrite, not intersect into a misleading `never` value. + * Optional fields and index signatures may leave old keys present. Retain the + * left-hand presence and both possible values unless the right guarantees a key. + * This proof can conservatively retain a widened index after a finite repair. + */ +type AssignRequiredContext = + IsAny extends true + ? Assign + : TLeft extends object + ? TRight extends object + ? true extends + | HasOptionalContextProperties + | HasOptionalContextProperties + ? RetainedContext & WidenOptionalContext + : Extract extends never + ? Assign + : RetainedContext & TRight + : Assign + : Assign + +/** + * This walk proves required context; callback inference retains the full context + * separately. Keep correlated union branches and complete required field values, + * but avoid enumerating execute/skip combinations for unrelated fields. + * Indexed objects stay whole: projecting their keys can invent a required named + * property, or discard a property that violates an indexed requirement. + */ +type RequiredContext = + HasContextIndex extends true + ? TContext + : IsAny extends true + ? TContext + : TContext extends object + ? HasContextIndex extends true + ? TContext + : { + [K in keyof TContext as ContextPropertyKey extends ContextPropertyKey + ? K + : never]: TContext[K] + } + : TContext + +type Advance< + TState extends ContextState, + TMiddleware, + TId extends string, + TKeys extends PropertyKey, +> = + MiddlewareTypes extends { serverContext: infer TOutput } + ? RequiredContext extends infer TRequiredOutput + ? ContextState< + // Type equality cannot prove object identity. A structurally matching + // earlier middleware may be this same object, so both outcomes matter. + unknown extends TState['seen'] + ? + | TState['context'] + | AssignRequiredContext + : [Extract] extends [never] + ? AssignRequiredContext + : + | TState['context'] + | AssignRequiredContext, + TState['seen'] | TMiddleware, + [TOutput] extends [undefined] ? TState['writer'] : TId + > + : never + : 'Cannot establish the context produced by a middleware' + +/** Tail-recursive work queue follows nested dependencies before their consumer. */ +type Walk< + TQueue, + TState extends ContextState, + TPhase extends 'request' | 'function', + TKeys extends PropertyKey, +> = TQueue extends readonly [ + infer THead extends MiddlewareWork, + ...infer TRest, +] + ? MiddlewareOwner< + THead['middleware'], + THead['moduleId'] + > extends infer TOwner extends string + ? THead['expanded'] extends true + ? MiddlewareTypes extends { method: unknown } + ? // Server-function builders only contribute their middleware lists. + Walk + : ValidateConsumer< + TOwner, + TPhase, + TState['context'], + ` before middleware from '${TOwner}' (after '${TState['writer']}')` + > extends infer TCheck + ? [TCheck] extends [true] + ? Advance< + TState, + THead['middleware'], + TOwner, + TKeys + > extends infer TNext + ? TNext extends ContextState + ? Walk + : TNext + : never + : TCheck + : never + : Walk< + [ + ...TagList, TOwner>, + MiddlewareWork, + ...TRest, + ], + TState, + TPhase, + TKeys + > + : never + : TQueue extends readonly [] + ? TState + : `Cannot establish ${TPhase} context from a non-tuple middleware list` + +type RegisteredMiddleware< + TRegister, + TKey extends 'requestMiddleware' | 'functionMiddleware', +> = TRegister extends { config: { '~types': infer TTypes } } + ? TTypes[keyof TTypes & TKey] + : undefined + +/** Include nested global entries when deciding whether a local entry may skip. */ +type KnownMiddleware = TQueue extends readonly [ + infer THead, + ...infer TRest, +] + ? NestedMiddleware extends infer TNested + ? TNested extends ReadonlyArray + ? KnownMiddleware<[...TNested, ...TRest], TSeen | THead> + : KnownMiddleware + : never + : TQueue extends undefined | readonly [] + ? TSeen + : unknown + +type LocalContextState< + TRegister, + TPhase extends 'request' | 'function', + TKeys extends PropertyKey, +> = ContextState< + RequiredContext< + TPhase extends 'request' + ? AssignAllServerRequestContext + : AssignAllServerFnContext, + TKeys + >, + | KnownMiddleware> + | (TPhase extends 'function' + ? KnownMiddleware> + : never), + 'global middleware' +> + +/** Owners anywhere in a local chain, including widened lists and dependencies. */ +type LocalMiddlewareOwners = + TList extends ReadonlyArray + ? IsAny extends true + ? never + : TMiddleware extends unknown + ? + | MiddlewareOwner + | LocalMiddlewareOwners> + : never + : never + +/** Check a completed local chain only when attaching its server-side consumer. */ +export type ValidateModuleMiddlewareConsumer< + TRegister, + TMiddlewares, + TPhase extends 'request' | 'function', +> = [ + ConsumerIds | LocalMiddlewareOwners>, +] extends [never] + ? unknown + : Walk< + TagList, + LocalContextState< + TRegister, + TPhase, + RequiredContextKeysFor< + StartModuleIdOf | LocalMiddlewareOwners + > + >, + TPhase, + RequiredContextKeysFor< + StartModuleIdOf | LocalMiddlewareOwners + > + > extends infer TResult + ? [TResult] extends [ContextState] + ? ValidateConsumer< + StartModuleIdOf, + TPhase, + TResult['context'], + ' before the local server callback' + > extends infer TCheck + ? [TCheck] extends [true] + ? unknown + : TCheck + : never + : TResult + : never + +type ValidateConsumers< + TIds, + TRequestContext, + TFunctionContext, + TWhere extends string, +> = TIds extends readonly [infer TId extends string, ...infer TRest] + ? ValidateHostConsumer< + TId, + TRequestContext, + TFunctionContext, + TWhere + > extends infer TResult + ? [TResult] extends [true] + ? ValidateConsumers + : TResult + : never + : true + +type ValidateHostConsumer< + TId extends string, + TRequestContext, + TFunctionContext, + TWhere extends string, +> = TId extends unknown + ? ValidateContext< + TId, + 'request', + TRequestContext, + StartModuleRequiredContext, + TWhere + > extends infer TRequest + ? [TRequest] extends [true] + ? ValidateConsumer< + TId, + 'function', + TFunctionContext, + TWhere + > extends infer TFunction + ? [TFunction] extends [true] + ? true + : TFunction + : never + : TRequest + : never + : never + +type ValidateEffectiveContext< + TTypes, + TIds extends ReadonlyArray, + TKeys extends PropertyKey = RequiredContextKeysFor< + TIds[number] | ExecutedMiddlewareOwners + >, +> = + Walk< + TagList, + ContextState< + RequiredContext, + never, + 'handler.fetch' + >, + 'request', + TKeys + > extends infer TOwnRequest + ? [TOwnRequest] extends [ContextState] + ? Walk< + TagList< + TTypes[keyof TTypes & 'ownFunctionMiddleware'], + 'application' + >, + TOwnRequest, + 'function', + TKeys + > extends infer TOwnFunction + ? [TOwnFunction] extends [ContextState] + ? ValidateConsumers< + TIds, + TOwnRequest['context'], + TOwnFunction['context'], + ' from application middleware' + > extends infer THost + ? [THost] extends [true] + ? Walk< + TaggedContributions< + TTypes[keyof TTypes & 'startModules'], + 'requestMiddleware' + >, + TOwnRequest, + 'request', + TKeys + > extends infer TRequest + ? [TRequest] extends [ContextState] + ? Walk< + [ + ...TagList< + TTypes[keyof TTypes & 'ownFunctionMiddleware'], + 'application' + >, + ...TaggedContributions< + TTypes[keyof TTypes & 'startModules'], + 'functionMiddleware' + >, + ], + TRequest, + 'function', + TKeys + > extends infer TFunction + ? [TFunction] extends [ContextState] + ? ValidateConsumers< + TIds, + TRequest['context'], + TFunction['context'], + ' at terminal consumers' + > + : TFunction + : never + : TRequest + : never + : THost + : never + : TOwnFunction + : never + : TOwnRequest + : never + +/** Owners of executable entries, whether or not their routes are installed. */ +type ExecutedMiddlewareOwners = + | LocalMiddlewareOwners< + TTypes[keyof TTypes & ('requestMiddleware' | 'functionMiddleware')] + > + | (Entries< + TTypes[keyof TTypes & 'startModules'] + > extends infer TModule extends AnyStartModule + ? TModule['id'] + : never) + +/** + * Generated contracts supply installed package IDs separately from executable + * fragments, so requirement-only modules need no runtime witness. + */ +export type ValidateStartModules< + TInstance extends AnyStartInstance, + TModules extends ReadonlyArray, + TInstalledModuleIds extends ReadonlyArray = { + [K in keyof TModules]: TModules[K]['id'] + }, +> = + ValidateInstalled< + InstanceTypes['startModules'], + TModules + > extends infer TInstalled + ? [TInstalled] extends [true] + ? number extends TInstalledModuleIds['length'] + ? 'Cannot establish installed route modules from a non-tuple contract list' + : string extends TInstalledModuleIds[number] + ? 'Cannot establish installed route module requirements from unknown package identities' + : [ + ConsumerIds< + | TInstalledModuleIds[number] + | ExecutedMiddlewareOwners> + >, + ] extends [never] + ? true + : ValidateEffectiveContext< + InstanceTypes, + TInstalledModuleIds + > + : TInstalled + : never + +export type AssertStartModules = TResult diff --git a/packages/start-client-core/src/index.tsx b/packages/start-client-core/src/index.tsx index e9a8b92d85..f263afa8a1 100644 --- a/packages/start-client-core/src/index.tsx +++ b/packages/start-client-core/src/index.tsx @@ -22,6 +22,7 @@ export { export { createServerFn } from './createServerFn' export { createMiddleware, + type CreateMiddlewareFn, type IntersectAllValidatorInputs, type IntersectAllValidatorOutputs, type FunctionMiddlewareServerFn, @@ -62,6 +63,7 @@ export { type RequestServerResult, } from './createMiddleware' export type { + CreateServerFn, CompiledFetcherFnOptions, CompiledFetcherFn, CustomFetch, @@ -122,9 +124,22 @@ export { createStart } from './createStart' export type { AnyStartInstance, AnyStartInstanceOptions, + CreateStartOptions, StartInstance, StartInstanceOptions, } from './createStart' +export type { + AnyStartModule, + AssertStartModules, + CreateStartModuleFn, + StartModule, + StartModuleConfig, + StartModuleOptions, + StartModuleRegister, + StartModuleRequirements, + ValidateStartModules, + WithStartModules, +} from './createStartModule' export type { Register } from '@tanstack/router-core' export { getRouterInstance } from './getRouterInstance' diff --git a/packages/start-client-core/src/route-module-internal.ts b/packages/start-client-core/src/route-module-internal.ts new file mode 100644 index 0000000000..10b5a8c973 --- /dev/null +++ b/packages/start-client-core/src/route-module-internal.ts @@ -0,0 +1 @@ +export { createStartModule } from './createStartModule' diff --git a/packages/start-client-core/src/serverRoute.ts b/packages/start-client-core/src/serverRoute.ts index 511412683e..c70b8aa599 100644 --- a/packages/start-client-core/src/serverRoute.ts +++ b/packages/start-client-core/src/serverRoute.ts @@ -12,7 +12,7 @@ import type { AssignAllServerRequestContext, } from './createMiddleware' -declare module '@tanstack/router-core' { +declare module '@tanstack/router-core/extensions' { interface FilebaseRouteOptionsInterface< TRegister, TParentRoute extends AnyRoute = AnyRoute, diff --git a/packages/start-client-core/src/startOptionList.ts b/packages/start-client-core/src/startOptionList.ts new file mode 100644 index 0000000000..970796bca2 --- /dev/null +++ b/packages/start-client-core/src/startOptionList.ts @@ -0,0 +1,11 @@ +/** Absent or undefined factory options cannot prove their entries always run. */ +export type StartOptionList< + TOptions, + TKey extends PropertyKey, + TList extends ReadonlyArray, +> = + TOptions extends Record + ? undefined extends TOptions[TKey] + ? [] | TList + : TList + : [] | TList diff --git a/packages/start-client-core/src/tests/createStartModule.test-d.ts b/packages/start-client-core/src/tests/createStartModule.test-d.ts new file mode 100644 index 0000000000..8af1080f6a --- /dev/null +++ b/packages/start-client-core/src/tests/createStartModule.test-d.ts @@ -0,0 +1,331 @@ +import { expectTypeOf, test } from 'vitest' +import { createMiddleware } from '../createMiddleware' +import { createServerFn } from '../createServerFn' +import { createStart } from '../createStart' +import { createStartModule } from '../createStartModule' +import type { CreateMiddlewareFn } from '../createMiddleware' +import type { CreateServerFn } from '../createServerFn' +import type { + StartModuleConfig, + StartModuleRegister, + ValidateStartModules, +} from '../createStartModule' + +declare module '../createStartModule' { + interface StartModuleRequirements { + '@review/products': { + requestContext: { userId: string } + functionContext: { locale: string } + } + '@review/reader': { requestContext: { value: string } } + '@review/numeric': { requestContext: { value: number } } + '@review/function-only': { functionContext: { value: string } } + '@review/requirement-only': { requestContext: { userId: string } } + '@review/unused': { requestContext: { unrelated: never } } + } +} + +const createProductsMiddleware = + createMiddleware as unknown as CreateMiddlewareFn< + StartModuleRegister<'@review/products'> + > +const catalog = createProductsMiddleware({ type: 'function' }).server( + ({ context, next }) => { + expectTypeOf(context.userId).toEqualTypeOf() + expectTypeOf(context.locale).toEqualTypeOf() + return next({ context: { catalog: 'main' } }) + }, +) +const products = createStartModule('@review/products')(() => ({ + functionMiddleware: [catalog], +})) +interface ProductsRegister extends StartModuleRegister<'@review/products'> { + ssr: true + config: StartModuleConfig +} +const createProductsServerFn = + createServerFn as unknown as CreateServerFn +const auth = createMiddleware().server(({ next }) => { + return next({ context: { userId: 'u1' } }) +}) +const locale = createMiddleware({ type: 'function' }).server(({ next }) => { + return next({ context: { locale: 'en' } }) +}) +const value = createMiddleware().server(({ next }) => { + return next({ context: { value: 'valid' } }) +}) + +test('module context is independent of fragment inference and survives into server functions', () => { + createProductsMiddleware().server(({ context, next }) => { + expectTypeOf(context).toEqualTypeOf<{ userId: string }>() + return next() + }) + createProductsServerFn().handler(({ context }) => { + expectTypeOf(context.userId).toEqualTypeOf() + expectTypeOf(context.locale).toEqualTypeOf() + expectTypeOf(context.catalog).toEqualTypeOf() + }) +}) + +test('createStart preserves application and fragment types without runtime requirement entries', () => { + const start = createStart(() => ({ + extends: [products], + requestMiddleware: [auth], + functionMiddleware: [locale], + })) + type Types = Awaited>['~types'] + expectTypeOf().toEqualTypeOf< + readonly [typeof products] + >() + expectTypeOf().toEqualTypeOf< + readonly [typeof auth] + >() + expectTypeOf().toEqualTypeOf< + [typeof locale, typeof catalog] + >() + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() +}) + +test('an application without route modules retains its middleware inference', () => { + const start = createStart(() => ({ requestMiddleware: [auth] })) + type Types = Awaited>['~types'] + expectTypeOf().toEqualTypeOf< + readonly [typeof auth] + >() +}) + +test('request and function requirements are checked independently against host providers', () => { + const missingRequest = createStart(() => ({ + extends: [products], + functionMiddleware: [locale], + })) + const missingFunction = createStart(() => ({ + extends: [products], + requestMiddleware: [auth], + })) + expectTypeOf< + ValidateStartModules + >().not.toEqualTypeOf() + expectTypeOf< + ValidateStartModules + >().not.toEqualTypeOf() + const onlyFunctionProvider = createStart(() => ({ + functionMiddleware: [ + createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { value: 'valid' } }), + ), + ], + })) + expectTypeOf< + ValidateStartModules< + typeof onlyFunctionProvider, + [], + ['@review/function-only'] + > + >().toEqualTypeOf() + expectTypeOf< + ValidateStartModules + >().not.toEqualTypeOf() +}) + +test('requirements-only modules need no runtime fragment and unrelated augmentations stay inactive', () => { + const start = createStart(() => ({ requestMiddleware: [auth] })) + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() + const missing = createStart(() => ({})) + expectTypeOf< + ValidateStartModules + >().not.toEqualTypeOf() + expectTypeOf>().toEqualTypeOf() +}) + +test('all installed contracts remain obligations, including overlapping context keys', () => { + const start = createStart(() => ({ requestMiddleware: [value] })) + expectTypeOf< + ValidateStartModules< + typeof start, + [], + ['@review/reader', '@review/function-only'] + > + >().toEqualTypeOf() + expectTypeOf< + ValidateStartModules< + typeof start, + [], + ['@review/reader', '@review/numeric'] + > + >().not.toEqualTypeOf() +}) + +const createReaderMiddleware = + createMiddleware as unknown as CreateMiddlewareFn< + StartModuleRegister<'@review/reader'> + > +const reader = createReaderMiddleware({ type: 'function' }).server( + ({ context, next }) => { + expectTypeOf(context.value).toEqualTypeOf() + return next() + }, +) +const readerModule = createStartModule('@review/reader')(() => ({ + functionMiddleware: [reader], +})) +const overwrite = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { value: 1 } }), +) +const restore = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { value: 'restored', restored: true } }), +) +const overwriteModule = createStartModule('@review/overwrite')(() => ({ + functionMiddleware: [overwrite], +})) +const restoreModule = createStartModule('@review/restore')(() => ({ + functionMiddleware: [restore], +})) + +test('request requirements remain valid at function middleware consumers', () => { + const broken = createStart(() => ({ + requestMiddleware: [value], + extends: [overwriteModule, readerModule], + })) + expectTypeOf< + ValidateStartModules< + typeof broken, + [typeof readerModule], + ['@review/reader'] + > + >().not.toEqualTypeOf() +}) + +test('restoring context before a reader is valid, but restoration after it cannot hide the error', () => { + const before = createStart(() => ({ + requestMiddleware: [value], + extends: [overwriteModule, restoreModule, readerModule], + })) + const after = createStart(() => ({ + requestMiddleware: [value], + extends: [overwriteModule, readerModule, restoreModule], + })) + expectTypeOf< + ValidateStartModules< + typeof before, + [typeof readerModule], + ['@review/reader'] + > + >().toEqualTypeOf() + expectTypeOf< + ValidateStartModules< + typeof after, + [typeof readerModule], + ['@review/reader'] + > + >().not.toEqualTypeOf() +}) + +test('terminal requirement-only consumers see the completed request and function context', () => { + const requestOverwrite = createMiddleware().server(({ next }) => + next({ context: { value: 1 } }), + ) + const module = createStartModule('@review/overwrite-request')(() => ({ + requestMiddleware: [requestOverwrite], + })) + const brokenRequest = createStart(() => ({ + requestMiddleware: [value], + extends: [module], + })) + const brokenFunction = createStart(() => ({ + requestMiddleware: [value], + extends: [overwriteModule], + })) + expectTypeOf< + ValidateStartModules + >().not.toEqualTypeOf() + expectTypeOf< + ValidateStartModules + >().not.toEqualTypeOf() +}) + +test('a module contribution cannot provide an otherwise missing host requirement', () => { + const provider = createStartModule('@review/provider')(() => ({ + requestMiddleware: [value], + })) + const start = createStart(() => ({ extends: [provider, readerModule] })) + expectTypeOf< + ValidateStartModules + >().not.toEqualTypeOf() +}) + +test('nested middleware dependencies execute before their consumer', () => { + const nested = createMiddleware({ type: 'function' }) + .middleware([overwrite, reader]) + // @ts-expect-error nested reader observes the overwritten context + .server(({ next }) => next()) + const nestedModule = createStartModule('@review/reader')(() => ({ + functionMiddleware: [nested], + })) + const start = createStart(() => ({ + requestMiddleware: [value], + extends: [nestedModule], + })) + expectTypeOf< + ValidateStartModules + >().not.toEqualTypeOf() +}) + +test('a deduplicated contribution cannot be assumed to restore overwritten context', () => { + const start = createStart(() => ({ + requestMiddleware: [value], + functionMiddleware: [restore], + extends: [overwriteModule, restoreModule, readerModule], + })) + expectTypeOf< + ValidateStartModules + >().not.toEqualTypeOf() + const valid = createStart(() => ({ + requestMiddleware: [value], + functionMiddleware: [reader], + extends: [readerModule], + })) + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() +}) + +test('widened providers cannot establish required context but safe tuple alternatives can', () => { + const providers = [auth] + const uncertain = createStart(() => ({ requestMiddleware: providers })) + expectTypeOf< + ValidateStartModules + >().not.toEqualTypeOf() + const conditional = + Math.random() > 0.5 ? ([auth] as const) : ([auth, value] as const) + const safe = createStart(() => ({ requestMiddleware: conditional })) + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() +}) + +test('a module fragment only takes module options', () => { + // @ts-expect-error defaultSsr belongs to the application + createStartModule('@review/products')(() => ({ defaultSsr: false })) +}) + +test('many installed fragments preserve context and installation proof', () => { + type Repeat< + T, + TCount extends number, + TAcc extends Array = [], + > = TAcc['length'] extends TCount ? TAcc : Repeat + type Modules = Repeat + const modules = Array.from({ length: 100 }, () => readerModule) as Modules + const start = createStart(() => ({ + requestMiddleware: [value], + extends: modules, + })) + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() +}) diff --git a/packages/start-client-core/src/tests/moduleMiddlewareConsumers.test-d.ts b/packages/start-client-core/src/tests/moduleMiddlewareConsumers.test-d.ts new file mode 100644 index 0000000000..80c02876be --- /dev/null +++ b/packages/start-client-core/src/tests/moduleMiddlewareConsumers.test-d.ts @@ -0,0 +1,111 @@ +import { expectTypeOf, test } from 'vitest' +import { createMiddleware } from '../createMiddleware' +import { createServerFn } from '../createServerFn' +import { createStartModule } from '../createStartModule' +import type { CreateMiddlewareFn } from '../createMiddleware' +import type { CreateServerFn } from '../createServerFn' +import type { + StartModuleConfig, + StartModuleRegister, +} from '../createStartModule' + +declare module '../createStartModule' { + interface StartModuleRequirements { + '@review/local-consumer': { requestContext: { value: string } } + } +} + +const moduleMiddleware = createMiddleware as unknown as CreateMiddlewareFn< + StartModuleRegister<'@review/local-consumer'> +> +const moduleServerFn = createServerFn as unknown as CreateServerFn< + StartModuleRegister<'@review/local-consumer'> +> +const overwrite = createMiddleware({ type: 'function' }).server(({ next }) => { + return next({ context: { value: 1 } }) +}) +const restore = createMiddleware({ type: 'function' }).server(({ next }) => { + return next({ context: { value: 'restored' } }) +}) +const reader = moduleMiddleware({ type: 'function' }).server( + ({ context, next }) => { + expectTypeOf(context.value).toEqualTypeOf() + return next() + }, +) + +test('server-function local middleware must preserve context before a module consumer', () => { + moduleServerFn() + .middleware([overwrite, reader]) + .handler( + // @ts-expect-error the reader receives the overwritten value + ({ context }) => context.value, + ) + moduleServerFn() + .middleware([overwrite, reader, restore]) + .handler( + // @ts-expect-error restoring after the reader cannot repair its input + ({ context }) => context.value, + ) +}) + +test('middleware-local dependencies must establish the context of their consumer', () => { + moduleMiddleware({ type: 'function' }) + .middleware([overwrite]) + .server( + // @ts-expect-error this consumer requires the original string context + ({ next }) => next(), + ) + const requestOverwrite = createMiddleware().server(({ next }) => + next({ context: { value: 1 } }), + ) + moduleMiddleware() + .middleware([requestOverwrite]) + .server( + // @ts-expect-error request consumers also need their required context + ({ next }) => next(), + ) +}) + +test('local restoration cannot rely on middleware already executed globally', () => { + const fragment = createStartModule('@review/local-consumer')(() => ({ + functionMiddleware: [restore], + })) + interface Register extends StartModuleRegister<'@review/local-consumer'> { + config: StartModuleConfig + } + const createScopedServerFn = + createServerFn as unknown as CreateServerFn + createScopedServerFn() + .middleware([overwrite, restore, reader]) + .handler( + // @ts-expect-error the previously executed restoration can be deduplicated + ({ context }) => context.value, + ) +}) + +test('intermediate builder steps can restore context before attaching a consumer', () => { + moduleServerFn() + .middleware([overwrite]) + .middleware([restore, reader]) + .handler(({ context }) => { + expectTypeOf(context.value).toEqualTypeOf() + return context.value + }) + moduleMiddleware({ type: 'function' }) + .middleware([overwrite, restore]) + .server(({ context, next }) => { + expectTypeOf(context.value).toEqualTypeOf() + return next() + }) +}) + +test('server-function middleware builders contribute their lists without executing a handler', () => { + const factory = moduleServerFn().middleware([overwrite]) + moduleServerFn() + .middleware([factory, restore, reader]) + .handler(({ context }) => { + expectTypeOf(context.value).toEqualTypeOf() + return context.value + }) +}) diff --git a/packages/start-client-core/src/tests/startModuleConditionalEntry.test-d.ts b/packages/start-client-core/src/tests/startModuleConditionalEntry.test-d.ts new file mode 100644 index 0000000000..00702ade5b --- /dev/null +++ b/packages/start-client-core/src/tests/startModuleConditionalEntry.test-d.ts @@ -0,0 +1,40 @@ +import { expectTypeOf, test } from 'vitest' +import { createMiddleware } from '../createMiddleware' +import { createStart } from '../createStart' +import { createStartModule } from '../createStartModule' +import type { + AssertStartModules, + ValidateStartModules, +} from '../createStartModule' + +const audit = createMiddleware({ type: 'function' }).server(({ next }) => + next(), +) +const auditModule = createStartModule('@review/conditional-audit')(() => ({ + functionMiddleware: [audit], +})) +const unrelatedModule = createStartModule('@review/conditional-unrelated')( + () => ({ functionMiddleware: [audit] }), +) + +test('a union inside a fixed fragment tuple does not prove required installation', () => { + const chosen = Math.random() > 0.5 ? auditModule : unrelatedModule + const start = createStart(() => ({ extends: [chosen] })) + type Result = ValidateStartModules< + typeof start, + readonly [typeof auditModule] + > + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error the generated assertion must reject an optionally installed fragment + type InvalidApp = AssertStartModules +}) + +test('a fixed required fragment can accompany an unrelated union entry', () => { + const chosen = Math.random() > 0.5 ? auditModule : unrelatedModule + const start = createStart(() => ({ extends: [auditModule, chosen] })) + expectTypeOf< + AssertStartModules< + ValidateStartModules + > + >().toEqualTypeOf() +}) diff --git a/packages/start-client-core/src/tests/startModuleConditionalOptions.test-d.ts b/packages/start-client-core/src/tests/startModuleConditionalOptions.test-d.ts new file mode 100644 index 0000000000..9a00e0c836 --- /dev/null +++ b/packages/start-client-core/src/tests/startModuleConditionalOptions.test-d.ts @@ -0,0 +1,331 @@ +import { expectTypeOf, test } from 'vitest' +import { createMiddleware } from '../createMiddleware' +import { createStart } from '../createStart' +import { createStartModule } from '../createStartModule' +import type { + AssertStartModules, + ValidateStartModules, +} from '../createStartModule' + +declare module '../createStartModule' { + interface StartModuleRequirements { + '@review/optional-request-provider': { requestContext: { userId: string } } + '@review/optional-function-provider': { + functionContext: { permission: string } + } + } +} + +const user = createMiddleware().server(({ next }) => + next({ context: { userId: 'user' } }), +) +const permission = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { permission: 'read' } }), +) +const audit = createMiddleware().server(({ next }) => next()) +const functionAudit = createMiddleware({ type: 'function' }).server( + ({ next }) => next(), +) +const required = createStartModule('@review/optional-fragment')(() => ({ + requestMiddleware: [audit], +})) +const firstExtra = createStartModule('@review/optional-first-extra')(() => ({ + requestMiddleware: [audit], +})) +const secondExtra = createStartModule('@review/optional-second-extra')(() => ({ + requestMiddleware: [audit], +})) +const enabled: boolean = Math.random() > 0.5 + +test('an explicitly undefined extends value cannot prove fragment installation', () => { + const conditional = createStart(() => ({ + extends: enabled ? ([required] as const) : undefined, + })) + type Conditional = ValidateStartModules + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error the false branch does not install the executable fragment + type _Conditional = AssertStartModules + const installed = createStart(() => ({ extends: [required] })) + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() +}) + +test('an explicitly undefined request middleware value cannot prove required context', () => { + const conditional = createStart(() => ({ + requestMiddleware: enabled ? ([user] as const) : undefined, + })) + type Conditional = ValidateStartModules< + typeof conditional, + [], + ['@review/optional-request-provider'] + > + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error the false branch has no request context provider + type _Conditional = AssertStartModules + const supplied = createStart(() => ({ requestMiddleware: [user] })) + expectTypeOf< + ValidateStartModules< + typeof supplied, + [], + ['@review/optional-request-provider'] + > + >().toEqualTypeOf() +}) + +test('an explicitly undefined function middleware value cannot prove required context', () => { + const conditional = createStart(() => ({ + functionMiddleware: enabled ? ([permission] as const) : undefined, + })) + type Conditional = ValidateStartModules< + typeof conditional, + [], + ['@review/optional-function-provider'] + > + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error the false branch has no function context provider + type _Conditional = AssertStartModules + const supplied = createStart(() => ({ functionMiddleware: [permission] })) + expectTypeOf< + ValidateStartModules< + typeof supplied, + [], + ['@review/optional-function-provider'] + > + >().toEqualTypeOf() +}) + +test('a factory branch that omits extends cannot prove fragment installation', () => { + const conditional = createStart(() => + enabled ? { extends: [required] as const } : {}, + ) + type Conditional = ValidateStartModules + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error the false branch does not install the executable fragment + type _Conditional = AssertStartModules + const spread = createStart(() => ({ + ...(enabled ? { extends: [required] as const } : {}), + })) + type Spread = ValidateStartModules + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error an optional property is not proof of installation + type _Spread = AssertStartModules +}) + +test('asynchronous factories preserve both required and conditional options', () => { + const conditional = createStart(async () => + enabled ? { extends: [required] as const } : {}, + ) + type Conditional = ValidateStartModules + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error awaiting options does not guarantee their extends property + type _Conditional = AssertStartModules + const optionalProvider = createStart(async () => ({ + ...(enabled ? { requestMiddleware: [user] as const } : {}), + })) + type OptionalProvider = ValidateStartModules< + typeof optionalProvider, + [], + ['@review/optional-request-provider'] + > + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error awaiting options does not guarantee their request provider + type _OptionalProvider = AssertStartModules + const fixed = createStart(async () => ({ + extends: [required], + requestMiddleware: [user], + })) + expectTypeOf< + ValidateStartModules< + typeof fixed, + [typeof required], + ['@review/optional-request-provider'] + > + >().toEqualTypeOf() +}) + +test('explicit list generics do not prove options whose return shape was erased', () => { + const conditional = createStart<[], true, [], [], [typeof required]>(() => + enabled ? { extends: [required] } : {}, + ) + type Conditional = ValidateStartModules + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error the callback may omit the explicitly typed extends list + type _Conditional = AssertStartModules +}) + +test('fixed required siblings and required fragments present in every branch remain valid', () => { + const fixedSibling = createStart(() => ({ + extends: [required, enabled ? firstExtra : secondExtra], + })) + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() + const modules: + | readonly [typeof required, typeof firstExtra] + | readonly [typeof required, typeof secondExtra] = enabled + ? [required, firstExtra] + : [required, secondExtra] + const bothBranches = createStart(() => ({ extends: modules })) + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() +}) + +test('conditionally omitted application request middleware cannot prove required context', () => { + const conditional = createStart(() => + enabled ? { requestMiddleware: [user] as const } : {}, + ) + type Conditional = ValidateStartModules< + typeof conditional, + [], + ['@review/optional-request-provider'] + > + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error the false branch has no request context provider + type _Conditional = AssertStartModules + const spread = createStart(() => ({ + ...(enabled ? { requestMiddleware: [user] as const } : {}), + })) + type Spread = ValidateStartModules< + typeof spread, + [], + ['@review/optional-request-provider'] + > + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error the optional requestMiddleware field may be absent + type _Spread = AssertStartModules + const providers: + | readonly [typeof user] + | readonly [typeof user, typeof audit] = enabled ? [user] : [user, audit] + const fixed = createStart(() => ({ requestMiddleware: providers })) + expectTypeOf< + ValidateStartModules< + typeof fixed, + [], + ['@review/optional-request-provider'] + > + >().toEqualTypeOf() +}) + +test('conditionally omitted application function middleware cannot prove required context', () => { + const conditional = createStart(() => + enabled ? { functionMiddleware: [permission] as const } : {}, + ) + type Conditional = ValidateStartModules< + typeof conditional, + [], + ['@review/optional-function-provider'] + > + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error the false branch has no function context provider + type _Conditional = AssertStartModules + const spread = createStart(() => ({ + ...(enabled ? { functionMiddleware: [permission] as const } : {}), + })) + type Spread = ValidateStartModules< + typeof spread, + [], + ['@review/optional-function-provider'] + > + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error the optional functionMiddleware field may be absent + type _Spread = AssertStartModules + const providers: + | readonly [typeof permission] + | readonly [typeof permission, typeof functionAudit] = enabled + ? [permission] + : [permission, functionAudit] + const fixed = createStart(() => ({ functionMiddleware: providers })) + expectTypeOf< + ValidateStartModules< + typeof fixed, + [], + ['@review/optional-function-provider'] + > + >().toEqualTypeOf() +}) + +test('alternating request and function providers need a common provable context source', () => { + const requestPermission = createMiddleware().server(({ next }) => + next({ context: { permission: 'read' } }), + ) + const alternating = createStart(() => + enabled + ? { requestMiddleware: [requestPermission] as const } + : { functionMiddleware: [permission] as const }, + ) + type Alternating = ValidateStartModules< + typeof alternating, + [], + ['@review/optional-function-provider'] + > + // Both runtime branches provide permission before a server function runs. + // The contract conservatively checks these two optional lists independently; + // it cannot prove the relationship between their presence in this factory. + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error correlated providers do not establish this global contract + type _Alternating = AssertStartModules + const common = createStart(() => ({ requestMiddleware: [requestPermission] })) + expectTypeOf< + ValidateStartModules< + typeof common, + [], + ['@review/optional-function-provider'] + > + >().toEqualTypeOf() +}) + +test('optional fragment contributions cannot prove a later restoration always executes', () => { + const overwrite = createMiddleware().server(({ next }) => + next({ context: { userId: 1 } }), + ) + const restoreUser = createMiddleware().server(({ next }) => + next({ context: { userId: 'restored', restored: true } }), + ) + const destroy = createStartModule('@review/optional-destroy')(() => ({ + requestMiddleware: [overwrite], + })) + const restore = createStartModule('@review/optional-restore')(() => + enabled ? { requestMiddleware: [restoreUser] as const } : {}, + ) + const start = createStart(() => ({ + requestMiddleware: [user], + extends: [destroy, restore], + })) + type Result = ValidateStartModules< + typeof start, + [typeof destroy, typeof restore], + ['@review/optional-request-provider'] + > + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error the optional restoration leaves a numeric context on one runtime path + type _Result = AssertStartModules +}) + +test('optional fragment function middleware cannot prove a later restoration always executes', () => { + const overwrite = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { permission: 1 } }), + ) + const restorePermission = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: { permission: 'restored', restored: true } }), + ) + const destroy = createStartModule('@review/optional-function-destroy')( + () => ({ functionMiddleware: [overwrite] }), + ) + const restore = createStartModule('@review/optional-function-restore')(() => + enabled ? { functionMiddleware: [restorePermission] as const } : {}, + ) + const start = createStart(() => ({ + functionMiddleware: [permission], + extends: [destroy, restore], + })) + type Result = ValidateStartModules< + typeof start, + [typeof destroy, typeof restore], + ['@review/optional-function-provider'] + > + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error the optional restoration leaves a numeric context on one runtime path + type _Result = AssertStartModules +}) diff --git a/packages/start-client-core/src/tests/startModuleContextProjectionEdges.test-d.ts b/packages/start-client-core/src/tests/startModuleContextProjectionEdges.test-d.ts new file mode 100644 index 0000000000..b919a6c0fe --- /dev/null +++ b/packages/start-client-core/src/tests/startModuleContextProjectionEdges.test-d.ts @@ -0,0 +1,316 @@ +import { expectTypeOf, test } from 'vitest' +import { createMiddleware, createStart } from '../index' +import type { AssertStartModules, ValidateStartModules } from '../index' + +declare module '../createStartModule' { + interface StartModuleRequirements { + '@review/string-property-context': { functionContext: { '0': string } } + '@review/number-property-context': { functionContext: { 0: string } } + '@review/numeric-index-context': { + functionContext: Record<`${number}`, string> + } + '@review/number-index-context': { functionContext: Record } + '@review/optional-property-context': { functionContext: { value?: number } } + '@review/required-property-presence': { + functionContext: { value: string | undefined } + } + '@review/independent-optional-fields': { + functionContext: { value: string; other?: string } + } + } +} + +// JavaScript has the same own property for these two spellings. Each provider +// must satisfy either spelling of the requirement, without changing its value. +const numericProperty = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: { 0: 'credential' } }), +) +const stringProperty = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: { '0': 'credential' } }), +) + +test('a numeric property satisfies the same string-keyed requirement', () => { + const start = createStart(() => ({ + functionMiddleware: [numericProperty], + })) + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() +}) + +test('a string property satisfies the same numeric-keyed requirement', () => { + const start = createStart(() => ({ + functionMiddleware: [stringProperty], + })) + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() +}) + +test('equivalent property spellings still require compatible values', () => { + const wrongNumeric = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: { 0: 42 } }), + ) + const wrongString = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: { '0': 42 } }), + ) + const numericStart = createStart(() => ({ + functionMiddleware: [wrongNumeric], + })) + const stringStart = createStart(() => ({ + functionMiddleware: [wrongString], + })) + type WrongNumeric = ValidateStartModules< + typeof numericStart, + [], + ['@review/string-property-context'] + > + type WrongString = ValidateStartModules< + typeof stringStart, + [], + ['@review/number-property-context'] + > + expectTypeOf().not.toEqualTypeOf() + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error the existing property contains a number, not a string + type _WrongNumeric = AssertStartModules + // @ts-expect-error the existing property contains a number, not a string + type _WrongString = AssertStartModules +}) + +test('equivalent property spellings cannot hide an incompatible overwrite', () => { + const wrongString = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: { '0': 42 } }), + ) + const wrongNumeric = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: { 0: 42 } }), + ) + const numericThenString = createStart(() => ({ + functionMiddleware: [numericProperty, wrongString], + })) + const stringThenNumeric = createStart(() => ({ + functionMiddleware: [stringProperty, wrongNumeric], + })) + type NumericThenString = ValidateStartModules< + typeof numericThenString, + [], + ['@review/number-property-context'] + > + type StringThenNumeric = ValidateStartModules< + typeof stringThenNumeric, + [], + ['@review/string-property-context'] + > + expectTypeOf().not.toEqualTypeOf() + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error the later string-spelled property overwrites the numeric one + type _NumericThenString = AssertStartModules + // @ts-expect-error the later numeric property overwrites the string-spelled one + type _StringThenNumeric = AssertStartModules +}) + +test('a numeric template index checks finite numeric property values', () => { + const valid = createStart(() => ({ + functionMiddleware: [numericProperty], + })) + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() + const wrong = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { '0': 42 } }), + ) + const invalid = createStart(() => ({ functionMiddleware: [wrong] })) + expectTypeOf< + ValidateStartModules + >().not.toEqualTypeOf() +}) + +test('numeric template indexes cannot hide an incompatible overwrite', () => { + const context: Record<`${number}`, number> = { '0': 42 } + const indexed = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context }), + ) + const start = createStart(() => ({ + functionMiddleware: [stringProperty, indexed], + })) + type Invalid = ValidateStartModules< + typeof start, + [], + ['@review/string-property-context'] + > + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error the indexed middleware can overwrite '0' with a number + type _Invalid = AssertStartModules +}) + +test('a numeric index cannot hide an incompatible finite-property overwrite', () => { + const context: Record = { 0: 42 } + const indexed = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context }), + ) + const start = createStart(() => ({ + functionMiddleware: [stringProperty, indexed], + })) + type Invalid = ValidateStartModules< + typeof start, + [], + ['@review/string-property-context'] + > + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error the numeric index can overwrite the string-spelled field + type _Invalid = AssertStartModules +}) + +test('a finite overwrite cannot retain an incompatible earlier index guarantee', () => { + const context: Record = { 0: 'first', 1: 'second' } + const indexed = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context }), + ) + const compatible = createStart(() => ({ + functionMiddleware: [indexed, stringProperty], + })) + expectTypeOf< + ValidateStartModules< + typeof compatible, + [], + ['@review/number-index-context'] + > + >().toEqualTypeOf() + const wrong = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { '0': 42 } }), + ) + const incompatible = createStart(() => ({ + functionMiddleware: [indexed, wrong], + })) + type Invalid = ValidateStartModules< + typeof incompatible, + [], + ['@review/number-index-context'] + > + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error one indexed value has been overwritten with a number + type _Invalid = AssertStartModules +}) + +test('a later index signature cannot prove every earlier indexed key was replaced', () => { + const strings: Record = { 0: 'first' } + const otherStrings: Record = { 1: 'second' } + const numbers: Record = { 1: 42 } + const stringIndex = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: strings }), + ) + const numberIndex = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: numbers }), + ) + const otherStringIndex = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: otherStrings }), + ) + const compatible = createStart(() => ({ + functionMiddleware: [stringIndex, otherStringIndex], + })) + expectTypeOf< + ValidateStartModules< + typeof compatible, + [], + ['@review/number-index-context'] + > + >().toEqualTypeOf() + const incompatible = createStart(() => ({ + functionMiddleware: [numberIndex, stringIndex], + })) + type Invalid = ValidateStartModules< + typeof incompatible, + [], + ['@review/number-index-context'] + > + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error stringIndex need not replace numeric key 1 + type _Invalid = AssertStartModules +}) + +test('an optional context field cannot prove an earlier incompatible value was replaced', () => { + const oldValue = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { value: 'old' } }), + ) + const context: { value?: number } = {} + const optionalNumber = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context }), + ) + const start = createStart(() => ({ + functionMiddleware: [oldValue, optionalNumber], + })) + type Invalid = ValidateStartModules< + typeof start, + [], + ['@review/optional-property-context'] + > + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error the optional output may leave the earlier string present + type _Invalid = AssertStartModules + + const requiredNumber = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: { value: 42 } }), + ) + const repaired = createStart(() => ({ + functionMiddleware: [oldValue, optionalNumber, requiredNumber], + })) + expectTypeOf< + ValidateStartModules< + typeof repaired, + [], + ['@review/optional-property-context'] + > + >().toEqualTypeOf() +}) + +test('an optional compatible writer retains an already present context field', () => { + const oldValue = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { value: 'old' } }), + ) + const context: { value?: string } = {} + const optionalString = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context }), + ) + const start = createStart(() => ({ + functionMiddleware: [oldValue, optionalString], + })) + expectTypeOf< + ValidateStartModules< + typeof start, + [], + ['@review/required-property-presence'] + > + >().toEqualTypeOf() + + const optionalOnly = createStart(() => ({ + functionMiddleware: [optionalString], + })) + type Missing = ValidateStartModules< + typeof optionalOnly, + [], + ['@review/required-property-presence'] + > + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error the optional output alone does not establish presence + type _Missing = AssertStartModules +}) + +test('an unrelated optional field cannot weaken an existing required field', () => { + const requiredValue = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: { value: 'required' } }), + ) + const context: { other?: string } = {} + const optionalOther = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context }), + ) + const start = createStart(() => ({ + functionMiddleware: [requiredValue, optionalOther], + })) + expectTypeOf< + ValidateStartModules< + typeof start, + [], + ['@review/independent-optional-fields'] + > + >().toEqualTypeOf() +}) diff --git a/packages/start-client-core/src/tests/startModuleContextScaling.test-d.ts b/packages/start-client-core/src/tests/startModuleContextScaling.test-d.ts new file mode 100644 index 0000000000..fd010ac49a --- /dev/null +++ b/packages/start-client-core/src/tests/startModuleContextScaling.test-d.ts @@ -0,0 +1,211 @@ +import { expectTypeOf, test } from 'vitest' +import { createMiddleware, createStart } from '../index' +import type { ValidateStartModules } from '../index' + +type Credentials = + | { kind: 'user'; user: string } + | { kind: 'token'; token: string } + +declare module '../createStartModule' { + interface StartModuleRequirements { + '@review/scalable-context-walk': { requestContext: { viewer: string } } + '@review/indexed-context-walk': { functionContext: Record } + '@review/correlated-context-walk': { functionContext: Credentials } + } +} + +const viewer = createMiddleware().server(({ next }) => + next({ context: { viewer: 'benchmark' } }), +) +const sharedAudit = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { auditTag: 'host' } }), +) + +// This object differs from sharedAudit at runtime but has the same type. +const independentAudit0 = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: { auditTag: 'fragment' } }), +) +const dependency0 = createMiddleware({ type: 'function' }) + .middleware([sharedAudit, independentAudit0]) + .server(({ next }) => next({ context: { step0: true } })) +const middleware0 = createMiddleware({ type: 'function' }) + .middleware([dependency0, sharedAudit]) + .server(({ context, next }) => { + const tag: string = context.auditTag + const retainsInference: 0 extends 1 & typeof context.auditTag + ? never + : true = true + return next({ context: { lastAuditTag: tag, retainsInference } }) + }) + +// This object differs from sharedAudit at runtime but has the same type. +const independentAudit1 = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: { auditTag: 'fragment' } }), +) +const dependency1 = createMiddleware({ type: 'function' }) + .middleware([sharedAudit, independentAudit1]) + .server(({ next }) => next({ context: { step1: true } })) +const middleware1 = createMiddleware({ type: 'function' }) + .middleware([dependency1, sharedAudit]) + .server(({ context, next }) => { + const tag: string = context.auditTag + const retainsInference: 0 extends 1 & typeof context.auditTag + ? never + : true = true + return next({ context: { lastAuditTag: tag, retainsInference } }) + }) + +// This object differs from sharedAudit at runtime but has the same type. +const independentAudit2 = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: { auditTag: 'fragment' } }), +) +const dependency2 = createMiddleware({ type: 'function' }) + .middleware([sharedAudit, independentAudit2]) + .server(({ next }) => next({ context: { step2: true } })) +const middleware2 = createMiddleware({ type: 'function' }) + .middleware([dependency2, sharedAudit]) + .server(({ context, next }) => { + const tag: string = context.auditTag + const retainsInference: 0 extends 1 & typeof context.auditTag + ? never + : true = true + return next({ context: { lastAuditTag: tag, retainsInference } }) + }) + +// This object differs from sharedAudit at runtime but has the same type. +const independentAudit3 = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: { auditTag: 'fragment' } }), +) +const dependency3 = createMiddleware({ type: 'function' }) + .middleware([sharedAudit, independentAudit3]) + .server(({ next }) => next({ context: { step3: true } })) +const middleware3 = createMiddleware({ type: 'function' }) + .middleware([dependency3, sharedAudit]) + .server(({ context, next }) => { + const tag: string = context.auditTag + const retainsInference: 0 extends 1 & typeof context.auditTag + ? never + : true = true + return next({ context: { lastAuditTag: tag, retainsInference } }) + }) + +// This object differs from sharedAudit at runtime but has the same type. +const independentAudit4 = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: { auditTag: 'fragment' } }), +) +const dependency4 = createMiddleware({ type: 'function' }) + .middleware([sharedAudit, independentAudit4]) + .server(({ next }) => next({ context: { step4: true } })) +const middleware4 = createMiddleware({ type: 'function' }) + .middleware([dependency4, sharedAudit]) + .server(({ context, next }) => { + const tag: string = context.auditTag + const retainsInference: 0 extends 1 & typeof context.auditTag + ? never + : true = true + return next({ context: { lastAuditTag: tag, retainsInference } }) + }) + +// This object differs from sharedAudit at runtime but has the same type. +const independentAudit5 = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: { auditTag: 'fragment' } }), +) +const dependency5 = createMiddleware({ type: 'function' }) + .middleware([sharedAudit, independentAudit5]) + .server(({ next }) => next({ context: { step5: true } })) +const middleware5 = createMiddleware({ type: 'function' }) + .middleware([dependency5, sharedAudit]) + .server(({ context, next }) => { + const tag: string = context.auditTag + const retainsInference: 0 extends 1 & typeof context.auditTag + ? never + : true = true + return next({ context: { lastAuditTag: tag, retainsInference } }) + }) + +// This object differs from sharedAudit at runtime but has the same type. +const independentAudit6 = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: { auditTag: 'fragment' } }), +) +const dependency6 = createMiddleware({ type: 'function' }) + .middleware([sharedAudit, independentAudit6]) + .server(({ next }) => next({ context: { step6: true } })) +const middleware6 = createMiddleware({ type: 'function' }) + .middleware([dependency6, sharedAudit]) + .server(({ context, next }) => { + const tag: string = context.auditTag + const retainsInference: 0 extends 1 & typeof context.auditTag + ? never + : true = true + return next({ context: { lastAuditTag: tag, retainsInference } }) + }) + +// This object differs from sharedAudit at runtime but has the same type. +const independentAudit7 = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: { auditTag: 'fragment' } }), +) +const dependency7 = createMiddleware({ type: 'function' }) + .middleware([sharedAudit, independentAudit7]) + .server(({ next }) => next({ context: { step7: true } })) +const middleware7 = createMiddleware({ type: 'function' }) + .middleware([dependency7, sharedAudit]) + .server(({ context, next }) => { + const tag: string = context.auditTag + const retainsInference: 0 extends 1 & typeof context.auditTag + ? never + : true = true + return next({ context: { lastAuditTag: tag, retainsInference } }) + }) + +test('nested middleware chains do not enumerate unrelated context combinations', () => { + const start = createStart(() => ({ + requestMiddleware: [viewer], + functionMiddleware: [ + sharedAudit, + middleware0, + middleware1, + middleware2, + middleware3, + middleware4, + middleware5, + middleware6, + middleware7, + ], + })) + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() +}) + +test('indexed requirements retain every supplied property', () => { + const incompatible = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: { visible: 'value', unexpected: 42 } }), + ) + const start = createStart(() => ({ functionMiddleware: [incompatible] })) + expectTypeOf< + ValidateStartModules + >().not.toEqualTypeOf() +}) + +test('an index signature does not establish a required named property', () => { + const context: Record = {} + const indexed = createMiddleware().server(({ next }) => next({ context })) + const start = createStart(() => ({ requestMiddleware: [indexed] })) + expectTypeOf< + ValidateStartModules + >().not.toEqualTypeOf() +}) + +test('required context projections preserve correlated union alternatives', () => { + const credentials: Credentials = + Math.random() > 0.5 + ? { kind: 'user', user: 'user' } + : { kind: 'token', token: 'token' } + const provider = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: credentials }), + ) + const start = createStart(() => ({ functionMiddleware: [provider] })) + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() +}) diff --git a/packages/start-client-core/src/tests/startModuleGlobalOwner.test-d.ts b/packages/start-client-core/src/tests/startModuleGlobalOwner.test-d.ts new file mode 100644 index 0000000000..22723e09f3 --- /dev/null +++ b/packages/start-client-core/src/tests/startModuleGlobalOwner.test-d.ts @@ -0,0 +1,106 @@ +import { expectTypeOf, test } from 'vitest' +import { createMiddleware } from '../createMiddleware' +import { createStart } from '../createStart' +import type { CreateMiddlewareFn } from '../createMiddleware' +import type { + AssertStartModules, + StartModuleRegister, + ValidateStartModules, +} from '../createStartModule' + +declare module '../createStartModule' { + interface StartModuleRequirements { + '@review/installed-with-context': { requestContext: { tenantId: string } } + '@review/mixed-use-request': { requestContext: { userId: string } } + '@review/mixed-use-function': { functionContext: { permission: string } } + } +} + +const user = createMiddleware().server(({ next }) => + next({ context: { userId: 'user' } }), +) +const tenant = createMiddleware().server(({ next }) => + next({ context: { tenantId: 'tenant' } }), +) +const permission = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { permission: 'read' } }), +) +const createRequestReader = createMiddleware as unknown as CreateMiddlewareFn< + StartModuleRegister<'@review/mixed-use-request'> +> +const requestReader = createRequestReader().server(({ context, next }) => { + expectTypeOf(context.userId).toEqualTypeOf() + return next() +}) +const createFunctionReader = createMiddleware as unknown as CreateMiddlewareFn< + StartModuleRegister<'@review/mixed-use-function'> +> +const functionReader = createFunctionReader({ type: 'function' }).server( + ({ context, next }) => { + expectTypeOf(context.permission).toEqualTypeOf() + return next() + }, +) + +test('a global middleware consumer is validated when its package routes are not installed', () => { + const missing = createStart(() => ({ requestMiddleware: [requestReader] })) + type Missing = ValidateStartModules< + typeof missing, + [], + ['@review/unrelated-installed'] + > + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error an executed mixed-use package reader needs its request context + type _Missing = AssertStartModules + const valid = createStart(() => ({ + requestMiddleware: [user, requestReader], + })) + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() + const unused = createStart(() => ({})) + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() +}) + +test('a global function consumer is validated independently of installed route package identities', () => { + const missing = createStart(() => ({ functionMiddleware: [functionReader] })) + type Missing = ValidateStartModules< + typeof missing, + [], + ['@review/unrelated-installed'] + > + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error an executed mixed-use package reader needs its function context + type _Missing = AssertStartModules + const valid = createStart(() => ({ + functionMiddleware: [permission, functionReader], + })) + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() +}) + +test('the global walk checks readers before execution even when another installed package already needs validation', () => { + const overwrite = createMiddleware().server(({ next }) => + next({ context: { userId: 42 } }), + ) + const wrong = createStart(() => ({ + requestMiddleware: [tenant, user, overwrite, requestReader], + })) + type Wrong = ValidateStartModules< + typeof wrong, + [], + ['@review/installed-with-context'] + > + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error the request reader runs after its context is overwritten + type _Wrong = AssertStartModules + const valid = createStart(() => ({ + requestMiddleware: [tenant, user, requestReader], + })) + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() +}) diff --git a/packages/start-client-core/src/tests/startModuleImpossibleRequirement.test-d.ts b/packages/start-client-core/src/tests/startModuleImpossibleRequirement.test-d.ts new file mode 100644 index 0000000000..f6d1c5d5eb --- /dev/null +++ b/packages/start-client-core/src/tests/startModuleImpossibleRequirement.test-d.ts @@ -0,0 +1,26 @@ +import { expectTypeOf, test } from 'vitest' +import { createStart } from '../createStart' +import type { + AssertStartModules, + ValidateStartModules, +} from '../createStartModule' + +declare module '../createStartModule' { + interface StartModuleRequirements { + '@review/impossible-requirement': { + requestContext: { role: 'admin' } & { role: 'guest' } + } + } +} + +test('an intersection-derived impossible requirement cannot be treated as absent', () => { + const start = createStart(() => ({})) + type Result = ValidateStartModules< + typeof start, + [], + ['@review/impossible-requirement'] + > + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error no application context can satisfy the impossible requirement + type InvalidApp = AssertStartModules +}) diff --git a/packages/start-client-core/src/tests/startModuleInstallation.test-d.ts b/packages/start-client-core/src/tests/startModuleInstallation.test-d.ts new file mode 100644 index 0000000000..e83cb25cc4 --- /dev/null +++ b/packages/start-client-core/src/tests/startModuleInstallation.test-d.ts @@ -0,0 +1,56 @@ +import { expectTypeOf, test } from 'vitest' +import { createMiddleware } from '../createMiddleware' +import { createStart } from '../createStart' +import { createStartModule } from '../createStartModule' +import type { ValidateStartModules } from '../createStartModule' + +const audit = createMiddleware({ type: 'function' }).server(({ next }) => { + return next() +}) +const unrelated = createMiddleware({ type: 'function' }).server(({ next }) => { + return next() +}) +const auditModule = createStartModule('@review/audit')(() => ({ + functionMiddleware: [audit], +})) + +test('structurally identical middleware does not install a required fragment', () => { + const start = createStart(() => ({ functionMiddleware: [unrelated] })) + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf<"Route module '@review/audit' is not installed: add 'extends: startModules' to createStart()">() +}) + +test('asynchronous options preserve the actual installed fragments', () => { + const missing = createStart(async () => ({ functionMiddleware: [unrelated] })) + const installed = createStart(async () => ({ extends: [auditModule] })) + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf<"Route module '@review/audit' is not installed: add 'extends: startModules' to createStart()">() + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() +}) + +test('an array element type cannot prove a fragment is installed', () => { + const fragments: Array = [] + const start = createStart(() => ({ + extends: fragments, + functionMiddleware: [unrelated], + })) + expectTypeOf< + ValidateStartModules + >().not.toEqualTypeOf() +}) + +test('every conditional fragment list must install the required fragment', () => { + const condition: boolean = Math.random() > 0.5 + const fragments = condition ? ([auditModule] as const) : ([] as const) + const start = createStart(() => ({ + extends: fragments, + functionMiddleware: [unrelated], + })) + expectTypeOf< + ValidateStartModules + >().not.toEqualTypeOf() +}) diff --git a/packages/start-client-core/src/tests/startModuleRequirementFreeArray.test-d.ts b/packages/start-client-core/src/tests/startModuleRequirementFreeArray.test-d.ts new file mode 100644 index 0000000000..693bd0b6c6 --- /dev/null +++ b/packages/start-client-core/src/tests/startModuleRequirementFreeArray.test-d.ts @@ -0,0 +1,34 @@ +import { expectTypeOf, test } from 'vitest' +import { createMiddleware } from '../createMiddleware' +import { createServerFn } from '../createServerFn' +import { createStart } from '../createStart' +import type { CreateServerFn } from '../createServerFn' +import type { + AssertStartModules, + StartModuleRegister, + ValidateStartModules, +} from '../createStartModule' + +const ordinary = createMiddleware().server(({ next }) => + next({ context: { ordinary: 'value' } }), +) +const providers = [ordinary] +const createRequirementFreeServerFn = + createServerFn as unknown as CreateServerFn< + StartModuleRegister<'@review/no-requirements'> + > + +test('requirement-free modules do not demand tuple proof for ordinary arrays', () => { + const start = createStart(() => ({ requestMiddleware: providers })) + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() + expectTypeOf< + AssertStartModules< + ValidateStartModules + > + >().toEqualTypeOf() + createRequirementFreeServerFn() + .middleware(providers) + .handler(() => 'result') +}) diff --git a/packages/start-client-core/src/tests/startModuleUnionRequirement.test-d.ts b/packages/start-client-core/src/tests/startModuleUnionRequirement.test-d.ts new file mode 100644 index 0000000000..52b4ebe675 --- /dev/null +++ b/packages/start-client-core/src/tests/startModuleUnionRequirement.test-d.ts @@ -0,0 +1,178 @@ +import { expectTypeOf, test } from 'vitest' +import { createMiddleware } from '../createMiddleware' +import { createServerFn } from '../createServerFn' +import { createStart } from '../createStart' +import type { CreateMiddlewareFn } from '../createMiddleware' +import type { + AssertStartModules, + StartModuleRegister, + ValidateStartModules, +} from '../createStartModule' + +const userContext = Symbol('user context') +type Authentication = { user: { id: string } } | { apiKey: string } + +declare module '../createStartModule' { + interface StartModuleRequirements { + '@review/union-request': { requestContext: Authentication } + '@review/union-function': { functionContext: Authentication } + '@review/symbol-request': { requestContext: { [userContext]: string } } + } +} + +const user = createMiddleware().server(({ next }) => + next({ context: { user: { id: 'user' } } }), +) +const apiKey = createMiddleware().server(({ next }) => + next({ context: { apiKey: 'key' } }), +) +const functionUser = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { user: { id: 'user' } } }), +) +const functionApiKey = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: { apiKey: 'key' } }), +) + +const createRequestReader = createMiddleware as unknown as CreateMiddlewareFn< + StartModuleRegister<'@review/union-request'> +> +const requestReader = createRequestReader().server(({ context, next }) => { + const credential = 'user' in context ? context.user.id : context.apiKey + expectTypeOf(credential).toEqualTypeOf() + return next() +}) +const createFunctionReader = createMiddleware as unknown as CreateMiddlewareFn< + StartModuleRegister<'@review/union-function'> +> +const functionReader = createFunctionReader({ type: 'function' }).server( + ({ context, next }) => { + const credential = 'user' in context ? context.user.id : context.apiKey + expectTypeOf(credential).toEqualTypeOf() + return next() + }, +) + +test('a union request requirement needs a host provider for one alternative', () => { + const missing = createStart(() => ({})) + type Missing = ValidateStartModules< + typeof missing, + [], + ['@review/union-request'] + > + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error neither authentication alternative is provided + type _Missing = AssertStartModules + const withUser = createStart(() => ({ requestMiddleware: [user] })) + const withApiKey = createStart(() => ({ requestMiddleware: [apiKey] })) + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() +}) + +test('a union function requirement needs a host provider for one alternative', () => { + const missing = createStart(() => ({})) + type Missing = ValidateStartModules< + typeof missing, + [], + ['@review/union-function'] + > + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error neither authentication alternative is provided + type _Missing = AssertStartModules + const withUser = createStart(() => ({ functionMiddleware: [functionUser] })) + const withApiKey = createStart(() => ({ + functionMiddleware: [functionApiKey], + })) + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() +}) + +test('local middleware consumers check union requirements before running', () => { + createMiddleware() + .middleware([requestReader]) + .server( + // @ts-expect-error the imported request consumer has no authentication provider + ({ next }) => next(), + ) + createMiddleware() + .middleware([user, requestReader]) + .server(({ next }) => next()) + createMiddleware() + .middleware([apiKey, requestReader]) + .server(({ next }) => next()) + createServerFn() + .middleware([functionReader]) + .handler( + // @ts-expect-error the imported function consumer has no authentication provider + () => 'result', + ) + createServerFn() + .middleware([functionUser, functionReader]) + .handler(() => 'result') + createServerFn() + .middleware([functionApiKey, functionReader]) + .handler(() => 'result') +}) + +const symbolProvider = createMiddleware().server(({ next }) => + next({ context: { [userContext]: 'user' } }), +) +const wrongSymbolProvider = createMiddleware().server(({ next }) => + next({ context: { [userContext]: 42 } }), +) +const createSymbolReader = createMiddleware as unknown as CreateMiddlewareFn< + StartModuleRegister<'@review/symbol-request'> +> +const symbolReader = createSymbolReader().server(({ context, next }) => { + expectTypeOf(context[userContext]).toEqualTypeOf() + return next() +}) + +test('symbol-keyed required fields cannot disappear from diagnostics and validation', () => { + const missing = createStart(() => ({})) + const wrong = createStart(() => ({ + requestMiddleware: [wrongSymbolProvider], + })) + type Missing = ValidateStartModules< + typeof missing, + [], + ['@review/symbol-request'] + > + type Wrong = ValidateStartModules< + typeof wrong, + [], + ['@review/symbol-request'] + > + expectTypeOf().not.toEqualTypeOf() + expectTypeOf().not.toEqualTypeOf() + // @ts-expect-error the symbol-keyed field is absent + type _Missing = AssertStartModules + // @ts-expect-error the symbol-keyed field has the wrong type + type _Wrong = AssertStartModules + const valid = createStart(() => ({ requestMiddleware: [symbolProvider] })) + expectTypeOf< + ValidateStartModules + >().toEqualTypeOf() + createMiddleware() + .middleware([symbolReader]) + .server( + // @ts-expect-error the symbol-keyed field is absent before this consumer + ({ next }) => next(), + ) + createMiddleware() + .middleware([wrongSymbolProvider, symbolReader]) + .server( + // @ts-expect-error the symbol-keyed field has the wrong type before this consumer + ({ next }) => next(), + ) + createMiddleware() + .middleware([symbolProvider, symbolReader]) + .server(({ next }) => next()) +}) diff --git a/packages/start-client-core/src/tests/startModuleUnscopedConsumer.test-d.ts b/packages/start-client-core/src/tests/startModuleUnscopedConsumer.test-d.ts new file mode 100644 index 0000000000..b27d452ff1 --- /dev/null +++ b/packages/start-client-core/src/tests/startModuleUnscopedConsumer.test-d.ts @@ -0,0 +1,70 @@ +import { expectTypeOf, test } from 'vitest' +import { createMiddleware } from '../createMiddleware' +import { createServerFn } from '../createServerFn' +import type { CreateMiddlewareFn } from '../createMiddleware' +import type { CreateServerFn } from '../createServerFn' +import type { StartModuleRegister } from '../createStartModule' + +declare module '../createStartModule' { + interface StartModuleRequirements { + '@review/cross-module-reader': { requestContext: { value: string } } + } +} + +const createReaderMiddleware = + createMiddleware as unknown as CreateMiddlewareFn< + StartModuleRegister<'@review/cross-module-reader'> + > +const createRequirementFreeServerFn = + createServerFn as unknown as CreateServerFn< + StartModuleRegister<'@review/requirement-free'> + > +const provider = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { value: 'valid' } }), +) +const overwrite = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { value: 1 } }), +) +const reader = createReaderMiddleware({ type: 'function' }).server( + ({ context, next }) => { + expectTypeOf(context.value).toEqualTypeOf() + context.value.toUpperCase() + return next() + }, +) + +test('an unscoped host function checks scoped middleware consumers', () => { + createServerFn() + .middleware([provider, overwrite, reader]) + .handler( + // @ts-expect-error the imported reader consumes a number after the overwrite + () => 'result', + ) +}) + +test('a module without its own requirements checks imported middleware consumers', () => { + createRequirementFreeServerFn() + .middleware([provider, overwrite, reader]) + .handler( + // @ts-expect-error the imported reader consumes a number after the overwrite + () => 'result', + ) +}) + +test('an unscoped middleware checks scoped nested consumers', () => { + createMiddleware({ type: 'function' }) + .middleware([provider, overwrite, reader]) + .server( + // @ts-expect-error the imported reader consumes a number after the overwrite + ({ next }) => next(), + ) +}) + +test('a valid imported middleware remains usable', () => { + createServerFn() + .middleware([provider, reader]) + .handler(() => 'result') + createRequirementFreeServerFn() + .middleware([provider, reader]) + .handler(() => 'result') +}) diff --git a/packages/start-client-core/src/tests/startModuleWidenedGlobalDedupe.test-d.ts b/packages/start-client-core/src/tests/startModuleWidenedGlobalDedupe.test-d.ts new file mode 100644 index 0000000000..f917c5a3d7 --- /dev/null +++ b/packages/start-client-core/src/tests/startModuleWidenedGlobalDedupe.test-d.ts @@ -0,0 +1,43 @@ +import { test } from 'vitest' +import { createMiddleware } from '../createMiddleware' +import { createServerFn } from '../createServerFn' +import { createStart } from '../createStart' +import type { CreateMiddlewareFn } from '../createMiddleware' +import type { CreateServerFn } from '../createServerFn' +import type { StartModuleRegister } from '../createStartModule' + +declare module '../createStartModule' { + interface StartModuleRequirements { + '@review/widened-global-reader': { requestContext: { value: string } } + } +} +const createReaderMiddleware = + createMiddleware as unknown as CreateMiddlewareFn< + StartModuleRegister<'@review/widened-global-reader'> + > +const overwrite = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { value: 1 } }), +) +const restore = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { value: 'restored' } }), +) +const reader = createReaderMiddleware({ type: 'function' }).server( + ({ context, next }) => { + context.value.toUpperCase() + return next() + }, +) + +test('unknown global membership cannot prove a local restoration executes', () => { + const globals = [restore] + const start = createStart(() => ({ functionMiddleware: globals })) + type Register = { config: Awaited> } + const createHostServerFn = + createServerFn as unknown as CreateServerFn + createHostServerFn() + .middleware([overwrite, restore, reader]) + .handler( + // @ts-expect-error restore may already execute globally and skip after local overwrite + () => 'result', + ) +}) diff --git a/packages/start-client-core/tests/createStartModule.test.ts b/packages/start-client-core/tests/createStartModule.test.ts new file mode 100644 index 0000000000..0b423c63ac --- /dev/null +++ b/packages/start-client-core/tests/createStartModule.test.ts @@ -0,0 +1,175 @@ +import { expect, test } from 'vitest' +import { createSerializationAdapter } from '@tanstack/router-core' +import { runWithStartContext } from '@tanstack/start-storage-context' +import { createMiddleware } from '../src/createMiddleware' +import { executeMiddleware, flattenMiddlewares } from '../src/createServerFn' +import { createStart } from '../src/createStart' +import { createStartModule } from '../src/createStartModule' + +const decimal = createSerializationAdapter({ + key: 'decimal', + test: (value): value is { decimal: string } => + typeof value === 'object' && value !== null && 'decimal' in value, + toSerializable: (value) => value.decimal, + fromSerializable: (value) => ({ decimal: value }), +}) +const money = createSerializationAdapter({ + key: 'money', + extends: [decimal], + test: (value): value is { money: string } => + typeof value === 'object' && value !== null && 'money' in value, + toSerializable: (value) => value.money, + fromSerializable: (value) => ({ money: value }), +}) + +const auth = createMiddleware().server(({ next }) => + next({ context: { userId: 'u1' } }), +) +const productsLogging = createMiddleware({ type: 'function' }).server( + ({ next }) => next(), +) +const accountAudit = createMiddleware({ type: 'function' }).server(({ next }) => + next(), +) +const appLogging = createMiddleware({ type: 'function' }).server(({ next }) => + next(), +) + +const products = createStartModule('@acme/products')(() => ({ + serializationAdapters: [decimal], + functionMiddleware: [productsLogging], +})) +const account = createStartModule('@acme/account')(() => ({ + serializationAdapters: [money], + functionMiddleware: [accountAudit, productsLogging], +})) + +test('createStartModule binds the module id', () => { + expect(products.id).toBe('@acme/products') + expect(products.getOptions().functionMiddleware).toEqual([productsLogging]) +}) + +test('createStart installs the contributions of route modules after its own', () => { + const options = createStart(() => ({ + extends: [products, account], + requestMiddleware: [auth], + functionMiddleware: [appLogging], + })).getOptions() as any + + expect(flattenMiddlewares(options.requestMiddleware)).toEqual([auth]) + expect(flattenMiddlewares(options.functionMiddleware)).toEqual([ + appLogging, + productsLogging, + accountAudit, + ]) + expect(options.serializationAdapters).toEqual([decimal, money]) +}) + +test('createStart installs a module that several modules include once', () => { + let calls = 0 + const shared = createStartModule('@acme/shared')(() => { + calls++ + return { functionMiddleware: [productsLogging] } + }) + const options = createStart(() => ({ + extends: [shared, products, shared], + })).getOptions() as any + + expect(calls).toBe(1) + expect(flattenMiddlewares(options.functionMiddleware)).toEqual([ + productsLogging, + ]) +}) + +test('the application can place a module contribution itself', () => { + const options = createStart(() => ({ + extends: [products], + functionMiddleware: [productsLogging, appLogging], + })).getOptions() as any + + expect(flattenMiddlewares(options.functionMiddleware)).toEqual([ + productsLogging, + appLogging, + ]) +}) + +test('an installed contribution placed earlier executes once in the middleware pipeline', async () => { + const calls: Array = [] + const audit = createMiddleware({ type: 'function' }).server(({ next }) => { + calls.push('audit') + return next() + }) + const following = createMiddleware({ type: 'function' }).server( + ({ next }) => { + calls.push('following') + return next() + }, + ) + const fragment = createStartModule('@acme/audit')(() => ({ + functionMiddleware: [audit], + })) + const options = await createStart(() => ({ + extends: [fragment], + functionMiddleware: [audit, following], + })).getOptions() + + await runWithStartContext( + { + getRouter() { + throw new Error('This middleware does not use the router') + }, + request: new Request('http://localhost/'), + startOptions: options, + contextAfterGlobalMiddlewares: {}, + executedRequestMiddlewares: new Set(), + handlerType: 'serverFn', + }, + () => + executeMiddleware([], 'server', { + method: 'POST', + data: undefined, + headers: {}, + context: {}, + sendContext: {}, + serverFnMeta: { id: 'audit' }, + signal: new AbortController().signal, + }), + ) + expect(calls).toEqual(['audit', 'following']) +}) + +test('createStart installs route modules from an asynchronous factory', async () => { + const options = await createStart(async () => ({ + extends: [account], + })).getOptions() + + expect(flattenMiddlewares(options.functionMiddleware as any)).toEqual([ + accountAudit, + productsLogging, + ]) + expect(options.serializationAdapters).toEqual([money, decimal]) +}) + +test('repeated getOptions calls do not accumulate module entries', async () => { + // A fragment that creates its entries on every call, like inline middleware. + const inline = createStartModule('@acme/inline')(() => ({ + functionMiddleware: [ + createMiddleware({ type: 'function' }).server(({ next }) => next()), + ], + })) + const options = { extends: [inline], requestMiddleware: [auth] } + const reused = createStart(() => options) + const cached = Promise.resolve({ ...options }) + const cachedInstance = createStart(() => cached) + + for (let call = 0; call < 3; call++) { + const fromObject = reused.getOptions() as any + const fromPromise = (await cachedInstance.getOptions()) as any + for (const result of [fromObject, fromPromise]) { + expect(result.requestMiddleware).toHaveLength(1) + expect(result.functionMiddleware).toHaveLength(1) + } + } + expect(options.requestMiddleware).toEqual([auth]) + expect(options).not.toHaveProperty('functionMiddleware') +}) diff --git a/packages/start-client-core/vite.config.ts b/packages/start-client-core/vite.config.ts index 71e163a1ed..507bbecf4d 100644 --- a/packages/start-client-core/vite.config.ts +++ b/packages/start-client-core/vite.config.ts @@ -23,6 +23,7 @@ export default defineConfig(({ command }) => srcDir: './src', entry: [ './src/index.tsx', + './src/route-module-internal.ts', './src/client/index.ts', './src/client-rpc/index.ts', './src/hydration/constants.ts', diff --git a/packages/start-plugin-core/package.json b/packages/start-plugin-core/package.json index 727119c44e..0241a6c498 100644 --- a/packages/start-plugin-core/package.json +++ b/packages/start-plugin-core/package.json @@ -82,7 +82,7 @@ "src" ], "engines": { - "node": ">=22.12.0" + "node": ">=22.22.0" }, "dependencies": { "@babel/code-frame": "7.29.7", diff --git a/packages/start-plugin-core/src/import-protection/adapterUtils.ts b/packages/start-plugin-core/src/import-protection/adapterUtils.ts index 4893c504e4..a7aca0de3a 100644 --- a/packages/start-plugin-core/src/import-protection/adapterUtils.ts +++ b/packages/start-plugin-core/src/import-protection/adapterUtils.ts @@ -17,6 +17,11 @@ export interface ImportProtectionEnvRules { export interface ImportProtectionAdapterConfig { root: string srcDirectory: string + /** + * Package roots of installed route modules: their files are application + * source as much as `srcDirectory`. + */ + routeModuleDirectories: Array compiledRules: { client: ImportProtectionEnvRules server: ImportProtectionEnvRules @@ -55,6 +60,7 @@ export function shouldCheckImportProtectionImporter( ImportProtectionAdapterConfig, | 'root' | 'srcDirectory' + | 'routeModuleDirectories' | 'includeMatchers' | 'excludeMatchers' | 'ignoreImporterMatchers' @@ -84,7 +90,11 @@ export function shouldCheckImportProtectionImporter( } else if (config.includeMatchers.length > 0) { result = !!matchesAny(relativePath, config.includeMatchers) } else if (config.srcDirectory) { - result = isInsideDirectory(normalizedImporter, config.srcDirectory) + result = + isInsideDirectory(normalizedImporter, config.srcDirectory) || + config.routeModuleDirectories.some((directory) => + isInsideDirectory(normalizedImporter, directory), + ) } else { result = true } diff --git a/packages/start-plugin-core/src/prerender.ts b/packages/start-plugin-core/src/prerender.ts index 9510a9ab37..39a45886e4 100644 --- a/packages/start-plugin-core/src/prerender.ts +++ b/packages/start-plugin-core/src/prerender.ts @@ -29,12 +29,17 @@ export async function prerender({ let pages = startConfig.pages.length ? startConfig.pages : [{ path: '/' }] if (startConfig.prerender.autoStaticPathsDiscovery ?? true) { - const pagesMap = new Map(pages.map((item) => [item.path, item])) + // Requests use a trailing slash. Use that same URL identity for merging + // parent/index discoveries and preserving explicit per-page overrides. + const pagesMap = new Map( + pages.map((item) => [withTrailingSlash(item.path), item]), + ) const discoveredPages = globalThis.TSS_PRERENDABLE_PATHS || [] for (const page of discoveredPages) { - if (!pagesMap.has(page.path)) { - pagesMap.set(page.path, page) + const key = withTrailingSlash(page.path) + if (!pagesMap.has(key)) { + pagesMap.set(key, page) } } diff --git a/packages/start-plugin-core/src/rsbuild/import-protection.ts b/packages/start-plugin-core/src/rsbuild/import-protection.ts index f9d46505e3..c3aaf31855 100644 --- a/packages/start-plugin-core/src/rsbuild/import-protection.ts +++ b/packages/start-plugin-core/src/rsbuild/import-protection.ts @@ -1,6 +1,7 @@ import { writeFileSync } from 'node:fs' import { dirname, extname, resolve as resolvePath } from 'node:path' import { fileURLToPath } from 'node:url' +import { getRouteModuleDirectories } from '../start-router-plugin/route-module-directories' import { getDefaultImportProtectionRules, @@ -100,7 +101,15 @@ type ImportProtectionRsbuildPluginAPI = { processAssets: RsbuildPluginAPI['processAssets'] } type ImportProtectionGetConfigFn = () => { - startConfig: Pick['startConfig'], 'importProtection'> + startConfig: Pick< + ReturnType['startConfig'], + 'importProtection' + > & { + router?: Pick< + ReturnType['startConfig']['router'], + 'routeModules' + > + } resolvedStartConfig: Pick< ReturnType['resolvedStartConfig'], 'root' | 'srcDirectory' @@ -207,6 +216,8 @@ export interface PluginConfig { root: string command: 'build' | 'serve' srcDirectory: string + /** Package roots of installed route modules (application source too). */ + routeModuleDirectories: Array framework: CompileStartFrameworkOptions effectiveBehavior: ImportProtectionBehavior mockAccess: 'error' | 'warn' | 'off' @@ -1348,6 +1359,7 @@ export function registerImportProtection( root: '', command: api.context.action === 'dev' ? 'serve' : 'build', srcDirectory: '', + routeModuleDirectories: [], framework: opts.framework, effectiveBehavior: 'error', mockAccess: 'error', @@ -1389,6 +1401,10 @@ export function registerImportProtection( config.root = resolvedStartConfig.root config.srcDirectory = resolvedStartConfig.srcDirectory + config.routeModuleDirectories = getRouteModuleDirectories( + resolvedStartConfig.root, + startConfig.router?.routeModules, + ) shared.root = resolvedStartConfig.root const userOpts: ImportProtectionOptions | undefined = diff --git a/packages/start-plugin-core/src/rsbuild/plugin.ts b/packages/start-plugin-core/src/rsbuild/plugin.ts index 5989580d69..97c6f48c1a 100644 --- a/packages/start-plugin-core/src/rsbuild/plugin.ts +++ b/packages/start-plugin-core/src/rsbuild/plugin.ts @@ -89,14 +89,36 @@ export function tanStackStartRsbuild( // RSC plugin instances — created lazily when rspack namespace is available let rscPlugins: RscPluginPair | undefined - // Reference to the dev server for RSC HMR socket writes + // Shared dev server owner for topology reloads and RSC HMR socket writes. let devServerRef: Pick | null = null + let pendingRouteTreeReload = false const serverFnsById: Record = {} let updateServerFnResolver: (() => void) | undefined return { name: 'tanstack-start-rsbuild', setup(api: RsbuildPluginAPI) { + if (api.context.action === 'dev') { + api.onBeforeStartDevServer(({ server }) => { + devServerRef = server + }) + api.onAfterDevCompile(({ isFirstCompile, stats }) => { + if (!pendingRouteTreeReload || stats.hasErrors()) { + return + } + // Wait for all environments to publish their new assets. Route HMR + // preserves the live router, so topology changes need a fresh tree. + pendingRouteTreeReload = false + if (!isFirstCompile) { + devServerRef?.sockWrite('full-reload') + } + }) + api.onCloseDevServer(() => { + devServerRef = null + pendingRouteTreeReload = false + }) + } + const startCompilerEnvironments = [ { name: RSBUILD_ENVIRONMENT_NAMES.client, type: 'client' as const }, { name: RSBUILD_ENVIRONMENT_NAMES.server, type: 'server' as const }, @@ -419,6 +441,12 @@ export function tanStackStartRsbuild( getConfig, corePluginOpts, startPluginOpts, + onClientTreeInvalidated: + api.context.action === 'dev' + ? () => { + pendingRouteTreeReload = true + } + : undefined, }) // --------------------------------------------------------------- @@ -609,13 +637,6 @@ export function tanStackStartRsbuild( enableSwcReactServerComponents(config, 'all') } }) - - // Capture dev server reference for RSC HMR socket writes - if (api.context.action === 'dev') { - api.onBeforeStartDevServer(({ server }) => { - devServerRef = server - }) - } } // --------------------------------------------------------------- diff --git a/packages/start-plugin-core/src/rsbuild/start-compiler-host.ts b/packages/start-plugin-core/src/rsbuild/start-compiler-host.ts index 3cd1725fa0..77ac8e3c25 100644 --- a/packages/start-plugin-core/src/rsbuild/start-compiler-host.ts +++ b/packages/start-plugin-core/src/rsbuild/start-compiler-host.ts @@ -41,6 +41,7 @@ type WarnableRsbuildTransformContext = RsbuildTransformContext & { emitWarning?: (warning: Error) => void } type RsbuildInputFileSystem = NonNullable +type RspackResolver = ReturnType type ServerFnMetadataById = Map type StartCompilerEnvironment = { name: string @@ -141,6 +142,11 @@ export function registerStartCompilerTransforms( // Serialize access to each StartCompiler's mutable per-environment caches. const compilerQueues = new Map>() const inputFileSystems = new Map() + // The compiler follows the `import`s of a module (for example through a + // module that re-exports `createServerFn`). The transform context's + // `resolve` is the loader's base resolver, which applies no dependency + // type, so package exports that only list `import` would not resolve. + const esmResolvers = new Map() const transformContextStorage = new AsyncLocalStorage() const serverFnMetadataByEnvironment = new Map() @@ -344,20 +350,37 @@ export function registerStartCompilerTransforms( ? importer.replace(/[/\\][^/\\]*$/, '') : getRoot() + const resolver = esmResolvers.get(env.name) + if (!resolver) { + throw new Error( + `could not resolve ${source}: missing rspack resolver for ${env.name}`, + ) + } + return await new Promise((resolve, reject) => { - activeCtx.resolve(context, source, (error, resolved) => { - if (error) { - reject(error) - return - } + resolver.resolve( + {}, + context, + source, + { + fileDependencies: { + add: (file: string) => activeCtx.addDependency(file), + }, + }, + (error, resolved) => { + if (error) { + reject(error) + return + } - if (!resolved) { - resolve(null) - return - } + if (!resolved) { + resolve(null) + return + } - resolve(cleanId(resolved)) - }) + resolve(cleanId(resolved)) + }, + ) }) }, }) @@ -411,10 +434,16 @@ export function registerStartCompilerTransforms( if (compiler.inputFileSystem) { inputFileSystems.set(utils.environment.name, compiler.inputFileSystem) } - compiler.hooks.compilation.tap( 'TanStackStartCompilerMetadataLoaderContext', (compilation) => { + // Rspack applies dependency conditions before compilation. Creating + // this resolver in apply would cache the unexpanded conditions. + esmResolvers.set( + utils.environment.name, + compiler.resolverFactory.get('normal', { dependencyType: 'esm' }), + ) + utils.rspack.NormalModule.getCompilationHooks( compilation, ).loader.tap( diff --git a/packages/start-plugin-core/src/rsbuild/start-router-plugin.ts b/packages/start-plugin-core/src/rsbuild/start-router-plugin.ts index 40dfb9e42a..82b1276eb2 100644 --- a/packages/start-plugin-core/src/rsbuild/start-router-plugin.ts +++ b/packages/start-plugin-core/src/rsbuild/start-router-plugin.ts @@ -7,6 +7,8 @@ import { import { routesManifestPlugin } from '../start-router-plugin/generator-plugins/routes-manifest-plugin' import { prerenderRoutesPlugin } from '../start-router-plugin/generator-plugins/prerender-routes-plugin' import { buildRouteTreeFileFooterFromConfig } from '../start-router-plugin/route-tree-footer' +import { createClientRouteTree } from '../start-router-plugin/client-route-tree' +import { cleanId } from '../start-compiler/utils' import { RSBUILD_ENVIRONMENT_NAMES } from './planning' import type { RsbuildPluginAPI } from '@rsbuild/core' import type { GetConfigFn, TanStackStartCoreOptions } from '../types' @@ -26,9 +28,28 @@ export function registerRouterPlugins( getConfig: GetConfigFn corePluginOpts: TanStackStartCoreOptions startPluginOpts: TanStackStartRsbuildInputConfig + onClientTreeInvalidated?: () => void }, ): void { const routerPluginContext = createRouterPluginContext() + const clientTree = createClientRouteTree(opts.onClientTreeInvalidated) + + api.transform( + { + test: (id: string) => + path.normalize(cleanId(id)) === + path.resolve(opts.getConfig().startConfig.router.generatedRouteTree), + environments: [RSBUILD_ENVIRONMENT_NAMES.client], + order: 'pre', + }, + async ({ addDependency }) => { + const result = await clientTree.build() + for (const file of result.dependencies) { + addDependency(file) + } + return result.code + }, + ) api.modifyRspackConfig((config, utils) => { const envName = utils.environment.name @@ -51,6 +72,7 @@ export function registerRouterPlugins( }) }, plugins: [ + clientTree.generatorPlugin, routesManifestPlugin(), ...(opts.startPluginOpts.prerender?.enabled === true ? [prerenderRoutesPlugin()] @@ -60,6 +82,21 @@ export function registerRouterPlugins( routerPluginContext, ) utils.appendPlugins(generatorPlugin) + utils.appendPlugins( + new utils.rspack.NormalModuleReplacementPlugin(/./, (data) => { + // afterResolve provides the physical resource; beforeResolve only has + // the request. Leave package/alias resolution to Rspack itself. + if (!data.createData) { + return + } + const clientId = clientTree.getModuleClientTree( + data.createData.resource, + ) + if (clientId) { + data.createData.resource = clientId + } + }), + ) } if ( diff --git a/packages/start-plugin-core/src/start-router-plugin/client-route-tree.ts b/packages/start-plugin-core/src/start-router-plugin/client-route-tree.ts new file mode 100644 index 0000000000..39e29a45af --- /dev/null +++ b/packages/start-plugin-core/src/start-router-plugin/client-route-tree.ts @@ -0,0 +1,87 @@ +import { pruneServerOnlySubtrees } from '@tanstack/router-generator' +import { normalize } from 'pathe' +import { SERVER_PROP } from './constants' +import type { + Generator, + GeneratorPlugin, + RouteNode, +} from '@tanstack/router-generator' + +function isServerOnlyNode(node: RouteNode | undefined) { + return ( + node?.createFileRouteProps?.has(SERVER_PROP) === true && + node.createFileRouteProps.size === 1 + ) +} + +/** Shared client-tree generation and provider views for both bundlers. */ +export function createClientRouteTree(invalidate: () => void = () => {}) { + let generator: Generator | undefined + let moduleTrees = new Map() + + const generatorPlugin: GeneratorPlugin = { + name: 'start-client-tree-plugin', + init({ generator: instance }) { + generator = instance + }, + afterTransform({ node, prevNode }) { + if (isServerOnlyNode(node) !== isServerOnlyNode(prevNode)) { + invalidate() + } + }, + onRouteTreeChanged() { + moduleTrees = new Map( + generator! + .getRouteModuleClientTrees() + .map(({ filePath, clientFilePath }) => [ + normalize(filePath), + clientFilePath, + ]), + ) + invalidate() + }, + } + + return { + generatorPlugin, + getModuleClientTree(id: string) { + // The suffix belongs to the bundler's module identity. Only the physical + // filename participates in matching the provider's generated tree. + const suffixAt = id.search(/[?#]/) + const filePath = suffixAt === -1 ? id : id.slice(0, suffixAt) + const clientFilePath = moduleTrees.get(normalize(filePath)) + return clientFilePath === undefined + ? undefined + : `${clientFilePath}${suffixAt === -1 ? '' : id.slice(suffixAt)}` + }, + async build() { + if (!generator) { + throw new Error('Generator instance not initialized') + } + const crawlingResult = await generator.getCrawlingResult() + if (!crawlingResult) { + throw new Error('Crawling result not available') + } + const result = generator.buildRouteTree({ + ...crawlingResult, + acc: { + ...crawlingResult.acc, + ...pruneServerOnlySubtrees(crawlingResult), + }, + config: { + disableTypes: true, + enableRouteTreeFormatting: false, + routeTreeFileHeader: [], + routeTreeFileFooter: [], + }, + }) + return { + code: result.routeTreeContent, + dependencies: [ + ...generator.getRoutesByFileMap().keys(), + ...generator.getRouteModuleWatchFiles(), + ], + } + }, + } +} diff --git a/packages/start-plugin-core/src/start-router-plugin/generator-plugins/prerender-routes-plugin.ts b/packages/start-plugin-core/src/start-router-plugin/generator-plugins/prerender-routes-plugin.ts index b614ae4afa..4030023839 100644 --- a/packages/start-plugin-core/src/start-router-plugin/generator-plugins/prerender-routes-plugin.ts +++ b/packages/start-plugin-core/src/start-router-plugin/generator-plugins/prerender-routes-plugin.ts @@ -1,38 +1,20 @@ -import { inferFullPath } from '@tanstack/router-generator' -import type { GeneratorPlugin, RouteNode } from '@tanstack/router-generator' +import type { Generator, GeneratorPlugin } from '@tanstack/router-generator' /** * this plugin gets the prerenderable paths and stores it on globalThis * so that it can be accessed later (e.g. from a vite plugin) */ export function prerenderRoutesPlugin(): GeneratorPlugin { + let generator: Generator return { name: 'prerender-routes-plugin', - onRouteTreeChanged: ({ routeNodes }) => { - globalThis.TSS_PRERENDABLE_PATHS = getPrerenderablePaths(routeNodes) + init({ generator: instance }) { + generator = instance + }, + onRouteTreeChanged: () => { + globalThis.TSS_PRERENDABLE_PATHS = [ + ...new Set(['/', ...generator.getPrerenderableRoutePaths()]), + ].map((path) => ({ path })) }, } } - -function getPrerenderablePaths( - routeNodes: Array, -): Array<{ path: string }> { - const paths = new Set(['/']) - - for (const route of routeNodes) { - if (!route.routePath) continue - // filter routes that are layout - if (route.isNonPath === true) continue - - // filter dynamic routes - // if routePath contains $ it is dynamic - if (route.routePath.includes('$')) continue - - // filter routes that do not have a component, i.e api routes - if (!route.createFileRouteProps?.has('component')) continue - - paths.add(inferFullPath(route)) - } - - return Array.from(paths).map((path) => ({ path })) -} diff --git a/packages/start-plugin-core/src/start-router-plugin/generator-plugins/routes-manifest-plugin.ts b/packages/start-plugin-core/src/start-router-plugin/generator-plugins/routes-manifest-plugin.ts index 34cb7aded1..fa75bdb6f6 100644 --- a/packages/start-plugin-core/src/start-router-plugin/generator-plugins/routes-manifest-plugin.ts +++ b/packages/start-plugin-core/src/start-router-plugin/generator-plugins/routes-manifest-plugin.ts @@ -1,42 +1,81 @@ import { rootRouteId } from '@tanstack/router-core' -import type { GeneratorPlugin } from '@tanstack/router-generator' +import type { + Generator, + GeneratorPlugin, + RouteNode, +} from '@tanstack/router-generator' + +type RoutesManifest = Record< + string, + { + filePath: string + children?: Array + } +> + +/** + * The route id of a child in the route tree: mounted module roots are + * `:`, or `#:` for one of several installations. + */ +function childRouteId(node: RouteNode) { + return node._routeModuleMount + ? `${node._routeModuleMount.installation}:` + : node.routePath +} /** * this plugin builds the routes manifest and stores it on globalThis * so that it can be accessed later (e.g. from a vite plugin) */ export function routesManifestPlugin(): GeneratorPlugin { + let generator: Generator | undefined return { name: 'routes-manifest-plugin', + init: ({ generator: instance }) => { + generator = instance + }, onRouteTreeChanged: ({ routeTree, rootRouteNode, routeNodes }) => { - const allChildren = routeTree.map((d) => d.routePath) - const routes: Record< - string, - { - filePath: string - children: Array - } - > = { + const allChildren = routeTree.map(childRouteId) + const routes: RoutesManifest = { [rootRouteId]: { filePath: rootRouteNode.fullPath, - children: allChildren, + children: allChildren as Array, }, ...Object.fromEntries( - routeNodes.map((d) => { - const filePathId = d.routePath + routeNodes + .filter((d) => !d._routeModuleMount) + .map((d) => { + const filePathId = d.routePath - return [ - filePathId, - { - filePath: d.fullPath, - children: d.children?.map((childRoute) => childRoute.routePath), - }, - ] - }), + return [ + filePathId, + { + filePath: d.fullPath, + children: d.children?.map( + (childRoute) => childRouteId(childRoute) as string, + ), + }, + ] + }), ), } + // Routes of mounted route modules, with their qualified ids. + for (const route of generator?.getMountedRouteModuleRoutes() ?? []) { + if (route.filePath) { + const entry = (routes[route.id] ??= { filePath: route.filePath }) + entry.filePath = route.filePath + } + const parent = routes[route.parent] + if (parent) { + const children = (parent.children ??= []) + if (!children.includes(route.id)) { + children.push(route.id) + } + } + } + globalThis.TSS_ROUTES_MANIFEST = routes }, } diff --git a/packages/start-plugin-core/src/start-router-plugin/route-module-directories.ts b/packages/start-plugin-core/src/start-router-plugin/route-module-directories.ts new file mode 100644 index 0000000000..244ffc3ab2 --- /dev/null +++ b/packages/start-plugin-core/src/start-router-plugin/route-module-directories.ts @@ -0,0 +1,25 @@ +import { + getInstalledRouteModuleDirectories, + resolveRouteModuleContext, +} from '@tanstack/router-generator' +import type { RouteModulesOption } from '@tanstack/router-generator' + +/** + * Package roots of the route modules an application installs. Start treats + * their files as application source (import protection, entries). + * + * Composition errors are reported by the route generation; here a broken or + * missing module simply contributes no directory. + */ +export function getRouteModuleDirectories( + root: string, + routeModules: RouteModulesOption | undefined, +): Array { + try { + return getInstalledRouteModuleDirectories( + resolveRouteModuleContext({ root, routeModules }), + ) + } catch { + return [] + } +} diff --git a/packages/start-plugin-core/src/vite/import-protection-plugin/plugin.ts b/packages/start-plugin-core/src/vite/import-protection-plugin/plugin.ts index dcbec56655..9954b0d208 100644 --- a/packages/start-plugin-core/src/vite/import-protection-plugin/plugin.ts +++ b/packages/start-plugin-core/src/vite/import-protection-plugin/plugin.ts @@ -1,6 +1,7 @@ import { writeFileSync } from 'node:fs' import { normalizePath } from 'vite' import { dirname, relative } from 'pathe' +import { getRouteModuleDirectories } from '../../start-router-plugin/route-module-directories' import { escapeRegExp, resolveViteId } from '../../utils' import { SERVER_FN_LOOKUP, VITE_ENVIRONMENT_NAMES } from '../../constants' @@ -280,6 +281,7 @@ export function importProtectionPlugin( command: 'build', bundledDev: false, srcDirectory: '', + routeModuleDirectories: [], framework: opts.framework, effectiveBehavior: 'error', mockAccess: 'error', @@ -1209,7 +1211,9 @@ export function importProtectionPlugin( edgeSurvivalApplied || (pv.info.type === 'file' && !!pv.info.resolved && - isInsideDirectory(pv.info.resolved, config.srcDirectory)) + [config.srcDirectory, ...config.routeModuleDirectories].some( + (directory) => isInsideDirectory(pv.info.resolved!, directory), + )) if (shouldEmit) { emittedAny = @@ -1423,6 +1427,10 @@ export function importProtectionPlugin( const { startConfig, resolvedStartConfig } = opts.getConfig() config.srcDirectory = resolvedStartConfig.srcDirectory + config.routeModuleDirectories = getRouteModuleDirectories( + viteConfig.root, + startConfig.router.routeModules, + ) const userOpts: ImportProtectionOptions | undefined = startConfig.importProtection @@ -1616,7 +1624,12 @@ export function importProtectionPlugin( const routesDirectory = normalizePath( `${config.srcDirectory}/routes`, ) - if (isInsideDirectory(normalizedImporter, routesDirectory)) { + if ( + isInsideDirectory(normalizedImporter, routesDirectory) || + config.routeModuleDirectories.some((directory) => + isInsideDirectory(normalizedImporter, directory), + ) + ) { env.graph.addEntry(normalizedImporter) } } diff --git a/packages/start-plugin-core/src/vite/import-protection-plugin/types.ts b/packages/start-plugin-core/src/vite/import-protection-plugin/types.ts index 21691783ea..3b6207a478 100644 --- a/packages/start-plugin-core/src/vite/import-protection-plugin/types.ts +++ b/packages/start-plugin-core/src/vite/import-protection-plugin/types.ts @@ -21,6 +21,8 @@ export interface PluginConfig { command: 'build' | 'serve' bundledDev: boolean srcDirectory: string + /** Package roots of installed route modules (application source too). */ + routeModuleDirectories: Array framework: CompileStartFrameworkOptions effectiveBehavior: ImportProtectionBehavior mockAccess: 'error' | 'warn' | 'off' diff --git a/packages/start-plugin-core/src/vite/start-router-plugin/plugin.ts b/packages/start-plugin-core/src/vite/start-router-plugin/plugin.ts index e4f06893a7..99693c3822 100644 --- a/packages/start-plugin-core/src/vite/start-router-plugin/plugin.ts +++ b/packages/start-plugin-core/src/vite/start-router-plugin/plugin.ts @@ -1,3 +1,4 @@ +import { existsSync } from 'node:fs' import { createRouterPluginContext } from '@tanstack/router-plugin/context' import { tanStackRouterCodeSplitter, @@ -9,28 +10,12 @@ import { VITE_ENVIRONMENT_NAMES } from '../../constants' import { routesManifestPlugin } from '../../start-router-plugin/generator-plugins/routes-manifest-plugin' import { prerenderRoutesPlugin } from '../../start-router-plugin/generator-plugins/prerender-routes-plugin' import { buildRouteTreeFileFooterFromConfig } from '../../start-router-plugin/route-tree-footer' -import { pruneServerOnlySubtrees } from '../../start-router-plugin/pruneServerOnlySubtrees' -import { SERVER_PROP } from '../../start-router-plugin/constants' +import { createClientRouteTree } from '../../start-router-plugin/client-route-tree' import type { GetConfigFn } from '../../types' import type { TanStackStartVitePluginCoreOptions } from '../types' -import type { - Generator, - GeneratorPlugin, - RouteNode, -} from '@tanstack/router-generator' import type { DevEnvironment, Plugin, PluginOption } from 'vite' import type { TanStackStartInputConfig } from '../../schema' -function isServerOnlyNode(node: RouteNode | undefined) { - if (!node?.createFileRouteProps) { - return false - } - return ( - node.createFileRouteProps.has(SERVER_PROP) && - node.createFileRouteProps.size === 1 - ) -} - export function tanStackStartRouter( startPluginOpts: TanStackStartInputConfig, getConfig: GetConfigFn, @@ -58,19 +43,7 @@ export function tanStackStartRouter( clientEnvironment.hot.send({ type: 'full-reload', path: '*' }) } - let generatorInstance: Generator | null = null - - const clientTreeGeneratorPlugin: GeneratorPlugin = { - name: 'start-client-tree-plugin', - init({ generator }) { - generatorInstance = generator - }, - afterTransform({ node, prevNode }) { - if (isServerOnlyNode(node) !== isServerOnlyNode(prevNode)) { - invalidate() - } - }, - } + const clientTree = createClientRouteTree(invalidate) let routeTreeFileFooter: Array | null = null @@ -109,36 +82,35 @@ export function tanStackStartRouter( } }, + async resolveId(source, importer, options) { + if (!source.startsWith('.') && !path.isAbsolute(source)) { + return null + } + const resolved = await this.resolve(source, importer, { + ...options, + skipSelf: true, + }) + if (!resolved) { + return null + } + const clientId = clientTree.getModuleClientTree(resolved.id) + return clientId ? { ...resolved, id: clientId } : null + }, + load: { filter: { // this will be set in the config hook above since it relies on `config` hook being called first }, async handler() { - if (!generatorInstance) { - throw new Error('Generator instance not initialized') + const result = await clientTree.build() + for (const file of result.dependencies) { + // The generator watches missing discovery candidates. Vite also + // resolves load-hook watch files as module dependencies. + if (existsSync(file)) { + this.addWatchFile(file) + } } - const crawlingResult = await generatorInstance.getCrawlingResult() - if (!crawlingResult) { - throw new Error('Crawling result not available') - } - const prunedAcc = pruneServerOnlySubtrees(crawlingResult) - const acc = { - ...crawlingResult.acc, - ...prunedAcc, - } - const buildResult = generatorInstance.buildRouteTree({ - ...crawlingResult, - acc, - config: { - // importRoutesUsingAbsolutePaths: true, - // addExtensions: true, - disableTypes: true, - enableRouteTreeFormatting: false, - routeTreeFileHeader: [], - routeTreeFileFooter: [], - }, - }) - return { code: buildResult.routeTreeContent, map: null } + return { code: result.code, map: null } }, }, } @@ -146,7 +118,7 @@ export function tanStackStartRouter( clientTreePlugin, tanstackRouterGenerator(() => { const routerConfig = getConfig().startConfig.router - const plugins = [clientTreeGeneratorPlugin, routesManifestPlugin()] + const plugins = [clientTree.generatorPlugin, routesManifestPlugin()] if (startPluginOpts.prerender?.enabled === true) { plugins.push(prerenderRoutesPlugin()) } diff --git a/packages/start-plugin-core/tests/route-module-start-build.test.ts b/packages/start-plugin-core/tests/route-module-start-build.test.ts new file mode 100644 index 0000000000..812c2afc06 --- /dev/null +++ b/packages/start-plugin-core/tests/route-module-start-build.test.ts @@ -0,0 +1,744 @@ +import { execFileSync } from 'node:child_process' +import { createRequire } from 'node:module' +import { promises as fs, realpathSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { pathToFileURL } from 'node:url' +import { afterEach, expect, it } from 'vitest' +import { + Generator, + getConfig, + pruneServerOnlySubtrees, +} from '@tanstack/router-generator' +import { parseStartConfig } from '../src/schema' +import { prerender } from '../src/prerender' +import { prerenderRoutesPlugin } from '../src/start-router-plugin/generator-plugins/prerender-routes-plugin' +import { routesManifestPlugin } from '../src/start-router-plugin/generator-plugins/routes-manifest-plugin' + +type Framework = 'react' | 'solid' | 'vue' +const frameworks = ['react', 'solid', 'vue'] as const +const bundlers = ['vite', 'rsbuild'] as const +let workspace: string | undefined +afterEach(async () => { + delete globalThis.TSS_PRERENDABLE_PATHS + Reflect.deleteProperty(globalThis, 'TSS_ROUTES_MANIFEST') + if (workspace) { + await fs.rm(workspace, { recursive: true, force: true }) + } +}) + +async function fixtures(framework: Framework) { + const routerPackage = `@tanstack/${framework}-router` + const startPackage = `@tanstack/${framework}-start` + const frameworkPackage = framework === 'solid' ? 'solid-js' : framework + workspace = realpathSync( + await fs.mkdtemp(path.join(os.tmpdir(), 'start-module-build-')), + ) + const feature = path.join(workspace, 'feature') + const app = path.join(workspace, 'app') + const repository = path.resolve(import.meta.dirname, '../../..') + for (const root of [feature, app]) { + await fs.mkdir(path.join(root, 'src/routes'), { recursive: true }) + await fs.mkdir(path.join(root, 'node_modules/@tanstack'), { + recursive: true, + }) + await fs.symlink( + path.join(repository, `packages/${framework}-router`), + path.join(root, 'node_modules', routerPackage), + ) + await fs.symlink( + path.join(repository, `packages/${framework}-start`), + path.join(root, 'node_modules', startPackage), + ) + await fs.symlink( + path.join( + repository, + `packages/${framework}-router/node_modules`, + frameworkPackage, + ), + path.join(root, 'node_modules', frameworkPackage), + ) + } + await fs.writeFile( + path.join(feature, 'package.json'), + JSON.stringify({ + name: '@review/feature', + type: 'module', + dependencies: { + [routerPackage]: '*', + [startPackage]: '*', + [frameworkPackage]: '*', + }, + exports: { + './package.json': './package.json', + './route-module': './src/routeModule.gen.ts', + }, + tanstack: { router: { module: {} } }, + }), + ) + await fs.writeFile( + path.join(app, 'package.json'), + JSON.stringify({ + name: '@review/app', + type: 'module', + dependencies: { + '@review/feature': '*', + [routerPackage]: '*', + [startPackage]: '*', + [frameworkPackage]: '*', + }, + }), + ) + await fs.mkdir(path.join(app, 'node_modules/@review'), { recursive: true }) + await fs.symlink(feature, path.join(app, 'node_modules/@review/feature')) + await fs.writeFile( + path.join(feature, 'src/routes/__root.tsx'), + `import { createModuleRoot } from '../routeScope.gen' +export const Route = createModuleRoot()({}) +`, + ) + await fs.writeFile( + path.join(feature, 'src/routes/about.tsx'), + `import { createFileRoute } from '../routeScope.gen' +export const Route = createFileRoute('@review/feature:/about')({ component: () => 'module page' }) +`, + ) + await fs.writeFile( + path.join(feature, 'src/routes/api.tsx'), + `import { createFileRoute } from '../routeScope.gen' +export const Route = createFileRoute('@review/feature:/api')({ server: { handlers: { GET: () => new Response('module api') } } }) +`, + ) + await fs.writeFile( + path.join(app, 'src/routes/__root.tsx'), + `import { createRootRoute } from '${routerPackage}' +export const Route = createRootRoute() +`, + ) + await fs.writeFile( + path.join(app, 'src/routes/about.tsx'), + `import { createFileRoute } from '${routerPackage}' +export const Route = createFileRoute('/about')({ component: () => 'app page' }) +`, + ) + await fs.writeFile( + path.join(app, 'src/routes/api.tsx'), + `import { createFileRoute } from '${routerPackage}' +export const Route = createFileRoute('/api')({ server: { handlers: { GET: () => new Response('app api') } } }) +`, + ) + await fs.writeFile( + path.join(app, 'src/router.ts'), + `import { createRouter, createMemoryHistory } from '${routerPackage}' +import { routeTree } from './routeTree.gen' +export function getRouter() { + return createRouter({ routeTree, history: createMemoryHistory() }) +} +`, + ) + for (const [root, moduleId] of [ + [feature, '@review/feature'], + [app, ''], + ] as const) { + const factory = moduleId ? '../routeScope.gen' : routerPackage + for (const [name, routePath, options] of [ + ['index', '/', "component: () => 'index'"], + ['parent', '/parent', "component: () => 'parent'"], + ['parent.index', '/parent/', "component: () => 'parent index'"], + ['parent.child', '/parent/child', "component: () => 'child'"], + ['_layout', '/_layout', "component: () => 'layout'"], + ['_layout.page', '/_layout/page', "component: () => 'pathless child'"], + ['$id', '/$id', "component: () => 'dynamic'"], + [ + 'mixed', + '/mixed', + "component: () => 'mixed', server: { handlers: { GET: () => new Response('server-only-sentinel') } }", + ], + [ + 'branch', + '/branch', + "server: { handlers: { GET: () => new Response('server-only-sentinel') } }", + ], + [ + 'branch.page', + '/branch/page', + "component: () => 'child needs its parent'", + ], + [ + 'branch.api', + '/branch/api', + "server: { handlers: { GET: () => new Response('server-only-sentinel') } }", + ], + [ + 'only', + '/only', + "server: { handlers: { GET: () => new Response('server-only-sentinel') } }", + ], + [ + 'only.child', + '/only/child', + "server: { handlers: { GET: () => new Response('server-only-sentinel') } }", + ], + ]) { + await fs.writeFile( + path.join(root, `src/routes/${name}.tsx`), + `import { createFileRoute } from '${factory}' +export const Route = createFileRoute('${moduleId ? `${moduleId}:` : ''}${routePath}')({ ${options} }) +`, + ) + } + } + const moduleConfig = getConfig( + { + disableLogging: true, + target: framework, + routesDirectory: './src/routes', + generatedRouteTree: './src/routeTree.gen.ts', + tmpDir: path.join(workspace, '.tmp'), + }, + feature, + ) + const providerGenerator = new Generator({ + root: feature, + config: moduleConfig, + }) + await providerGenerator.run() + return { app, feature, providerGenerator } +} + +it.each(frameworks)( + '%s discovers and renders static mounted module pages without crawling links', + async (framework) => { + const { app } = await fixtures(framework) + const config = getConfig( + { + disableLogging: true, + target: framework, + routesDirectory: './src/routes', + generatedRouteTree: './src/routeTree.gen.ts', + routeModules: { + includes: [{ module: '@review/feature', at: '/feature' }], + }, + tmpDir: path.join(workspace!, '.tmp'), + plugins: [prerenderRoutesPlugin(), routesManifestPlugin()], + }, + app, + ) + await new Generator({ root: app, config }).run() + expect(globalThis.TSS_ROUTES_MANIFEST).toHaveProperty( + '@review/feature:/about', + ) + const startConfig = parseStartConfig( + { + prerender: { enabled: true, crawlLinks: false }, + router: { + routeModules: { + includes: [{ module: '@review/feature', at: '/feature' }], + }, + }, + }, + { framework }, + app, + ) + const requested: Array = [] + await prerender({ + startConfig, + handler: { + getClientOutputDirectory: () => path.join(workspace!, 'html'), + request: async (url) => { + requested.push(url) + return new Response('page', { + headers: { 'content-type': 'text/html' }, + }) + }, + }, + }) + expect(requested.map((pathname) => pathname.replace(/\/$/, ''))).toContain( + '/feature/about', + ) + await expect( + fs.readFile( + path.join(workspace!, 'html/feature/about/index.html'), + 'utf8', + ), + ).resolves.toContain('page') + const paths = requested + .map((pathname) => pathname.replace(/\/$/, '')) + .sort() + expect(paths).toEqual( + [ + '', + '/about', + '/branch/page', + '/feature', + '/feature/about', + '/feature/branch/page', + '/feature/mixed', + '/feature/page', + '/feature/parent', + '/feature/parent/child', + '/mixed', + '/page', + '/parent', + '/parent/child', + ].sort(), + ) + }, +) + +it.each( + frameworks.flatMap((framework) => + bundlers.map((bundler) => ({ framework, bundler })), + ), +)( + '$framework/$bundler prunes application and module endpoints from the client', + async ({ framework, bundler }) => { + const { app } = await fixtures(framework) + const repository = path.resolve(import.meta.dirname, '../../..') + const outputRoot = path.join(app, 'dist') + const outDir = path.join(outputRoot, 'client') + await fs.writeFile( + path.join(app, 'src/client.ts'), + `import { getRouter } from './router' +globalThis.__routeModuleBuildRouter = getRouter() +`, + ) + // Use each public Start plugin, including its compiler, environment + // resolution and default server entry. The custom client entry exposes the + // actual browser router without starting hydration in this probe. + const buildScript = path.join(app, 'build.mjs') + if (bundler === 'vite') { + await fs.symlink( + path.join(repository, 'packages/start-plugin-core/node_modules/vite'), + path.join(app, 'node_modules/vite'), + ) + const frameworkPlugins = { + react: ['@vitejs/plugin-react'], + solid: ['vite-plugin-solid'], + vue: ['@vitejs/plugin-vue', '@vitejs/plugin-vue-jsx'], + }[framework] + for (const plugin of frameworkPlugins) { + const destination = path.join(app, 'node_modules', plugin) + await fs.mkdir(path.dirname(destination), { recursive: true }) + await fs.symlink( + path.join( + repository, + `e2e/${framework}-start/server-routes/node_modules`, + plugin, + ), + destination, + ) + } + await fs.writeFile( + buildScript, + `import { createBuilder } from 'vite' +import { tanstackStart } from '@tanstack/${framework}-start/plugin/vite' +${frameworkPlugins.map((plugin, index) => `import frameworkPlugin${index} from '${plugin}'`).join('\n')} + +const builder = await createBuilder({ + configFile: false, + root: process.cwd(), + logLevel: 'warn', + plugins: [ + tanstackStart({ + router: { + routeModules: { includes: [{ module: '@review/feature', at: '/feature' }] }, + tmpDir: ${JSON.stringify(path.join(workspace!, '.tmp'))}, + }, + }), + ${frameworkPlugins.map((_, index) => `frameworkPlugin${index}(${framework === 'solid' ? '{ ssr: true }' : ''})`).join(',\n ')}, + ], + build: { outDir: ${JSON.stringify(outputRoot)}, minify: false }, + environments: { + client: { build: { rolldownOptions: { output: { entryFileNames: 'assets/[name].js' } } } }, + ssr: { build: { rolldownOptions: { output: { entryFileNames: 'index.js' } } } }, + }, +}) +await builder.buildApp() +`, + ) + } else { + await fs.mkdir(path.join(app, 'node_modules/@rsbuild'), { + recursive: true, + }) + await fs.symlink( + path.join( + repository, + 'packages/start-plugin-core/node_modules/@rsbuild/core', + ), + path.join(app, 'node_modules/@rsbuild/core'), + ) + await fs.writeFile( + buildScript, + `import { createRsbuild } from '@rsbuild/core' +import { tanstackStart } from '@tanstack/${framework}-start/plugin/rsbuild' + +const rsbuild = await createRsbuild({ + cwd: process.cwd(), + config: { + plugins: [tanstackStart({ + router: { + routeModules: { includes: [{ module: '@review/feature', at: '/feature' }] }, + tmpDir: ${JSON.stringify(path.join(workspace!, '.tmp'))}, + }, + })], + output: { + distPath: { root: ${JSON.stringify(outputRoot)} }, + filename: { js: '[name].js' }, + filenameHash: false, + minify: false, + }, + environments: { ssr: { output: { module: true } } }, + }, +}) +await rsbuild.build() +`, + ) + } + execFileSync(process.execPath, [buildScript], { + cwd: app, + encoding: 'utf8', + maxBuffer: 16 * 1024 * 1024, + }) + + const serverResult = JSON.parse( + execFileSync( + process.execPath, + [ + '--input-type=module', + '-e', + `const { default: server } = await import(${JSON.stringify(pathToFileURL(path.join(outputRoot, 'server/index.js')).href)}); +const paths = ['/api', '/feature/api', '/mixed', '/feature/mixed', '/only/child', '/feature/only/child']; +const responses = await Promise.all(paths.map(async path => { + const response = await server.fetch(new Request('http://localhost' + path)); + return [path, { status: response.status, body: await response.text() }]; +})); +console.log(JSON.stringify(Object.fromEntries(responses))); +`, + ], + { cwd: app, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 }, + ), + ) + expect(serverResult['/api']).toEqual({ status: 200, body: 'app api' }) + expect(serverResult['/feature/api']).toEqual({ + status: 200, + body: 'module api', + }) + for (const route of [ + '/mixed', + '/feature/mixed', + '/only/child', + '/feature/only/child', + ]) { + expect(serverResult[route]).toEqual({ + status: 200, + body: 'server-only-sentinel', + }) + } + const jsdom = createRequire( + path.join(repository, 'packages/react-router/package.json'), + ).resolve('jsdom') + const result = JSON.parse( + execFileSync( + process.execPath, + [ + '--input-type=module', + '-e', + ` + import { JSDOM } from ${JSON.stringify(pathToFileURL(jsdom).href)}; + const dom = new JSDOM('', {url: 'http://localhost/'}); + globalThis.window = dom.window; + globalThis.self = dom.window; + globalThis.document = dom.window.document; + await import(${JSON.stringify(pathToFileURL(path.join(outDir, bundler === 'rsbuild' ? 'assets/js/index.js' : 'assets/index.js')).href)}); + const router = globalThis.__routeModuleBuildRouter; + const summarize = (url) => router.matchRoutes(url).map(match => ({routeId: match.routeId, globalNotFound: match.globalNotFound})); + console.log(JSON.stringify({ + routes: Object.keys(router.routesById), + moduleHasServer: !!router.routesById['@review/feature:/api']?.options.server, + appMatches: summarize('/api'), + moduleMatches: summarize('/feature/api'), + matches: Object.fromEntries(['/about', '/mixed', '/branch/page', '/only', '/only/child', '/feature/about', '/feature/mixed', '/feature/branch/page', '/feature/only', '/feature/only/child'].map(url => [url, summarize(url).at(-1)?.routeId])), + mixedHasServer: !!router.routesById['@review/feature:/mixed']?.options.server, + })); + dom.window.close(); + `, + ], + { encoding: 'utf8' }, + ), + ) + expect(result.appMatches.at(-1)?.routeId).not.toBe('/api') + expect(result.moduleMatches.at(-1)?.routeId).not.toBe( + '@review/feature:/api', + ) + expect(result.matches).toMatchObject({ + '/about': '/about', + '/mixed': '/mixed', + '/branch/page': '/branch/page', + '/feature/about': '@review/feature:/about', + '/feature/mixed': '@review/feature:/mixed', + '/feature/branch/page': '@review/feature:/branch/page', + }) + for (const [url, id] of [ + ['/only', '/only'], + ['/only/child', '/only/child'], + ['/feature/only', '@review/feature:/only'], + ['/feature/only/child', '@review/feature:/only/child'], + ] as const) { + expect(result.matches[url]).not.toBe(id) + } + expect(result.mixedHasServer).toBe(false) + const files = await fs.readdir(outDir, { recursive: true }) + for (const file of files.filter((file) => file.endsWith('.js'))) { + expect(await fs.readFile(path.join(outDir, file), 'utf8')).not.toContain( + 'server-only-sentinel', + ) + } + }, + 60000, +) + +it('refreshes module page eligibility after a provider option edit without a path change', async () => { + const { app, feature, providerGenerator } = await fixtures('react') + const config = getConfig( + { + disableLogging: true, + routeModules: { + includes: [{ module: '@review/feature', at: '/feature' }], + }, + plugins: [prerenderRoutesPlugin()], + }, + app, + ) + const consumerGenerator = new Generator({ root: app, config }) + await consumerGenerator.run() + expect(globalThis.TSS_PRERENDABLE_PATHS).toContainEqual({ + path: '/feature/about', + }) + + const routeFile = path.join(feature, 'src/routes/about.tsx') + await fs.writeFile( + routeFile, + `import { createFileRoute } from '../routeScope.gen' +export const Route = createFileRoute('@review/feature:/about')({ server: { handlers: { GET: () => new Response('endpoint') } } }) +`, + ) + await providerGenerator.run({ type: 'update', path: routeFile }) + await consumerGenerator.run({ + type: 'update', + path: path.join(feature, '.tanstack/route-module.json'), + }) + const requested: Array = [] + await prerender({ + startConfig: parseStartConfig( + { prerender: { enabled: true, crawlLinks: false } }, + { framework: 'react' }, + app, + ), + handler: { + getClientOutputDirectory: () => path.join(workspace!, 'updated-pages'), + request: async (url) => { + requested.push(url) + return new Response('updated', { + headers: { 'content-type': 'text/html' }, + }) + }, + }, + }) + expect(requested).not.toContain('/feature/about/') + expect(requested).toContain('/feature/mixed/') +}) + +it('respects explicit page overrides, filters, basepath and disabled discovery for module pages', async () => { + const { app } = await fixtures('react') + await new Generator({ + root: app, + config: getConfig( + { + disableLogging: true, + routeModules: { + includes: [{ module: '@review/feature', at: '/feature' }], + }, + plugins: [prerenderRoutesPlugin()], + }, + app, + ), + }).run() + const requested: Array = [] + const output = path.join(workspace!, 'controlled-pages') + const run = async (autoStaticPathsDiscovery: boolean) => { + requested.length = 0 + await prerender({ + startConfig: parseStartConfig( + { + router: { basepath: '/base' }, + prerender: { + enabled: true, + crawlLinks: false, + autoStaticPathsDiscovery, + filter: (page) => page.path !== '/feature/parent', + }, + pages: [ + { path: '/feature/about/', prerender: { enabled: false } }, + { path: '/feature/mixed', prerender: { outputPath: '/selected' } }, + ], + }, + { framework: 'react' }, + app, + ), + handler: { + getClientOutputDirectory: () => output, + request: async (url) => { + requested.push(url) + return new Response('selected', { + headers: { 'content-type': 'text/html' }, + }) + }, + }, + }) + } + await run(true) + expect(requested).toContain('/base/feature/mixed/') + expect(requested).not.toContain('/base/feature/about/') + expect(requested).not.toContain('/base/feature/parent/') + await expect( + fs.readFile(path.join(output, 'selected/index.html'), 'utf8'), + ).resolves.toContain('selected') + await run(false) + expect(requested).toEqual(['/base/feature/mixed/']) +}) + +it('discovers nested and named installations while excluding dynamic host URLs', async () => { + const { app } = await fixtures('react') + const wrapper = path.join(workspace!, 'wrapper') + await fs.mkdir(path.join(wrapper, 'src/routes'), { recursive: true }) + await fs.symlink( + path.join(app, 'node_modules'), + path.join(wrapper, 'node_modules'), + 'dir', + ) + await fs.symlink( + wrapper, + path.join(app, 'node_modules/@review/wrapper'), + 'dir', + ) + const appPackagePath = path.join(app, 'package.json') + const appPackage = JSON.parse(await fs.readFile(appPackagePath, 'utf8')) + appPackage.dependencies['@review/wrapper'] = '*' + await fs.writeFile(appPackagePath, JSON.stringify(appPackage)) + await fs.writeFile( + path.join(wrapper, 'package.json'), + JSON.stringify({ + name: '@review/wrapper', + type: 'module', + dependencies: { + '@review/feature': '*', + '@tanstack/react-router': '*', + '@tanstack/react-start': '*', + }, + exports: { + './route-module': './src/routeModule.gen.ts', + './package.json': './package.json', + }, + tanstack: { + router: { + module: { includes: [{ module: '@review/feature', at: '/nested' }] }, + }, + }, + }), + ) + await fs.writeFile( + path.join(wrapper, 'src/routes/__root.tsx'), + `import { createModuleRoot } from '../routeScope.gen' +export const Route = createModuleRoot()({}) +`, + ) + await new Generator({ + root: wrapper, + config: getConfig({ disableLogging: true }, wrapper), + }).run() + await new Generator({ + root: app, + config: getConfig( + { + disableLogging: true, + plugins: [prerenderRoutesPlugin()], + routeModules: { + includes: [{ module: '@review/wrapper', at: '/outer' }], + }, + }, + app, + ), + }).run() + expect(globalThis.TSS_PRERENDABLE_PATHS).toContainEqual({ + path: '/outer/nested/about', + }) + + await fs.writeFile( + path.join(app, 'src/routes/orgs.$orgId.tsx'), + `import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/orgs/$orgId')({ component: () => 'organization' }) +`, + ) + await new Generator({ + root: app, + config: getConfig( + { + disableLogging: true, + plugins: [prerenderRoutesPlugin()], + routeModules: { + includes: [ + { module: '@review/feature', at: '/first', as: 'first' }, + { module: '@review/feature', at: '/second', as: 'second' }, + { + module: '@review/feature', + parent: '/orgs/$orgId', + at: '/third', + as: 'third', + }, + ], + }, + }, + app, + ), + }).run() + const requested: Array = [] + await prerender({ + startConfig: parseStartConfig( + { prerender: { enabled: true, crawlLinks: false } }, + { framework: 'react' }, + app, + ), + handler: { + getClientOutputDirectory: () => path.join(workspace!, 'installations'), + request: async (url) => { + requested.push(url) + return new Response('installed', { + headers: { 'content-type': 'text/html' }, + }) + }, + }, + }) + expect(requested).toContain('/first/about/') + expect(requested).toContain('/second/about/') + expect(requested.some((url) => url.includes('$'))).toBe(false) + expect(new Set(requested).size).toBe(requested.length) +}) + +it('can rebuild full and pruned trees repeatedly from the same generated provider', async () => { + const { providerGenerator } = await fixtures('react') + const crawl = await providerGenerator.getCrawlingResult() + expect(crawl).toBeDefined() + const original = providerGenerator.buildRouteTree(crawl!).routeTreeContent + const client = () => + providerGenerator.buildRouteTree({ + ...crawl!, + acc: { ...crawl!.acc, ...pruneServerOnlySubtrees(crawl!) }, + config: { disableTypes: true }, + }).routeTreeContent + const first = client() + expect(client()).toBe(first) + expect(providerGenerator.buildRouteTree(crawl!).routeTreeContent).toBe( + original, + ) +}) diff --git a/packages/vue-router/package.json b/packages/vue-router/package.json index 93ae8fdeed..0c050abfbc 100644 --- a/packages/vue-router/package.json +++ b/packages/vue-router/package.json @@ -59,7 +59,13 @@ "default": "./dist/esm/ssr/client.js" } }, - "./package.json": "./package.json" + "./package.json": "./package.json", + "./_internal/route-module": { + "import": { + "types": "./dist/esm/route-module-internal.d.ts", + "default": "./dist/esm/route-module-internal.js" + } + } }, "sideEffects": false, "files": [ diff --git a/packages/vue-router/src/Match.tsx b/packages/vue-router/src/Match.tsx index 0c3ff40f1d..cd48cff6a0 100644 --- a/packages/vue-router/src/Match.tsx +++ b/packages/vue-router/src/Match.tsx @@ -1,3 +1,4 @@ +import { resolveRouteId } from '@tanstack/router-core/_internal/route-module' import * as Vue from 'vue' import { isNotFound, rootRouteId } from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' @@ -92,7 +93,10 @@ export const Match = Vue.defineComponent({ fallback: (error: any) => { error.routeId ??= routeId - if (error.routeId !== routeId) { + if ( + (resolveRouteId?.(router, error.routeId, routeId) ?? + error.routeId) !== routeId + ) { throw error } diff --git a/packages/vue-router/src/Matches.tsx b/packages/vue-router/src/Matches.tsx index a22ec82e82..22150ddb11 100644 --- a/packages/vue-router/src/Matches.tsx +++ b/packages/vue-router/src/Matches.tsx @@ -16,7 +16,9 @@ import type { MakeRouteMatchUnion, MaskOptions, MatchRouteOptions, + Register, RegisteredRouter, + RegisteredRouterOf, ResolveRoute, ToSubOptionsProps, } from '@tanstack/router-core' @@ -24,7 +26,7 @@ import type { // Define a type for the error component function type ErrorRouteComponentType = (props: ErrorComponentProps) => Vue.VNode -declare module '@tanstack/router-core' { +declare module '@tanstack/router-core/extensions' { export interface RouteMatchExtensions { meta?: Array links?: Array @@ -135,6 +137,22 @@ export type UseMatchRouteOptions< MaskOptions & MatchRouteOptions +/** + * The signature of `useMatchRoute`, typed against the router of `TDefaultRegister` unless a + * router type is passed explicitly. Route modules export a `useMatchRoute` of + * this type. + */ +export type UseMatchRouteFn = < + TRouter extends AnyRouter = RegisteredRouterOf, +>() => < + const TFrom extends string = string, + const TTo extends string | undefined = undefined, + const TMaskFrom extends string = TFrom, + const TMaskTo extends string = '', +>( + opts: UseMatchRouteOptions, +) => Vue.Ref['types']['allParams']> + export function useMatchRoute() { const router = useRouter() @@ -188,24 +206,14 @@ export type MakeMatchRouteOptions< } // Create a type for the MatchRoute component that includes the generics -export interface MatchRouteComponentType { +export interface MatchRouteComponentType { < - TRouter extends AnyRouter = RegisteredRouter, + TRouter extends AnyRouter = RegisteredRouterOf, TFrom extends string = string, TTo extends string | undefined = undefined, >( props: MakeMatchRouteOptions, ): Vue.VNode - new (): { - $props: { - from?: string - to?: string - fuzzy?: boolean - caseSensitive?: boolean - includeSearch?: boolean - pending?: boolean - } - } } export const MatchRoute = Vue.defineComponent({ @@ -236,6 +244,15 @@ export const MatchRoute = Vue.defineComponent({ type: Boolean, required: false, }, + // Internal route-module scope, set by the `MatchRoute` of a route module. + _module: { + type: String, + required: false, + }, + _nearestRoute: { + type: String, + required: false, + }, }, setup(props, { slots }) { const params = useMatchRoute()(props) @@ -269,6 +286,17 @@ export type UseMatchesResult< TSelected, > = unknown extends TSelected ? Array> : TSelected +/** + * The signature of `useMatches`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useMatches` of this type. + */ +export type UseMatchesFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TSelected = unknown, +>( + opts?: UseMatchesBaseOptions, +) => Vue.Ref> + export function useMatches< TRouter extends AnyRouter = RegisteredRouter, TSelected = unknown, @@ -283,6 +311,17 @@ export function useMatches< }) } +/** + * The signature of `useParentMatches`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useParentMatches` of this type. + */ +export type UseParentMatchesFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TSelected = unknown, +>( + opts?: UseMatchesBaseOptions, +) => Vue.Ref> + export function useParentMatches< TRouter extends AnyRouter = RegisteredRouter, TSelected = unknown, @@ -302,6 +341,17 @@ export function useParentMatches< } as any) } +/** + * The signature of `useChildMatches`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useChildMatches` of this type. + */ +export type UseChildMatchesFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TSelected = unknown, +>( + opts?: UseMatchesBaseOptions, +) => Vue.Ref> + export function useChildMatches< TRouter extends AnyRouter = RegisteredRouter, TSelected = unknown, diff --git a/packages/vue-router/src/fileRoute.ts b/packages/vue-router/src/fileRoute.ts index 69334b79ee..13f347ee7c 100644 --- a/packages/vue-router/src/fileRoute.ts +++ b/packages/vue-router/src/fileRoute.ts @@ -53,6 +53,81 @@ export function createFileRoute< } } +/** + * The route factory returned by `createFileRoute(path)`. `TDefaultRegister` + * is the scope of the created route: the application's `Register`, or the + * scope register of a route module. + */ +export type FileRouteFactory< + TFilePath extends string, + TParentRoute extends AnyRoute, + TId extends RouteConstraints['TId'], + TPath extends RouteConstraints['TPath'], + TFullPath extends RouteConstraints['TFullPath'], + TDefaultRegister = Register, +> = < + TRegister = TDefaultRegister, + TSearchValidator = undefined, + TParams = ResolveParams, + TRouteContextFn = AnyContext, + TBeforeLoadFn = AnyContext, + TLoaderDeps extends Record = {}, + TLoaderFn = undefined, + TChildren = unknown, + TSSR = unknown, + TMiddlewares = unknown, + THandlers = undefined, +>( + options?: FileBaseRouteOptions< + TRegister, + TParentRoute, + TId, + TPath, + TSearchValidator, + TParams, + TLoaderDeps, + TLoaderFn, + AnyContext, + TRouteContextFn, + TBeforeLoadFn, + AnyContext, + TSSR, + TMiddlewares, + THandlers + > & + UpdatableRouteOptions< + TParentRoute, + TId, + TFullPath, + TParams, + TSearchValidator, + TLoaderFn, + TLoaderDeps, + AnyContext, + TRouteContextFn, + TBeforeLoadFn + >, +) => Route< + TRegister, + TParentRoute, + TPath, + TFullPath, + TFilePath, + TId, + TSearchValidator, + TParams, + AnyContext, + TRouteContextFn, + TBeforeLoadFn, + TLoaderDeps, + TLoaderFn, + TChildren, + unknown, + TSSR, + TMiddlewares, + THandlers +> + /** @deprecated It's no longer recommended to use the `FileRoute` class directly. Instead, use `createFileRoute('/path/to/file')(options)` to create a file route. @@ -74,68 +149,13 @@ export class FileRoute< this.silent = _opts?.silent } - createRoute = < - TRegister = Register, - TSearchValidator = undefined, - TParams = ResolveParams, - TRouteContextFn = AnyContext, - TBeforeLoadFn = AnyContext, - TLoaderDeps extends Record = {}, - TLoaderFn = undefined, - TChildren = unknown, - TSSR = unknown, - TMiddlewares = unknown, - THandlers = undefined, - >( - options?: FileBaseRouteOptions< - TRegister, - TParentRoute, - TId, - TPath, - TSearchValidator, - TParams, - TLoaderDeps, - TLoaderFn, - AnyContext, - TRouteContextFn, - TBeforeLoadFn, - AnyContext, - TSSR, - TMiddlewares, - THandlers - > & - UpdatableRouteOptions< - TParentRoute, - TId, - TFullPath, - TParams, - TSearchValidator, - TLoaderFn, - TLoaderDeps, - AnyContext, - TRouteContextFn, - TBeforeLoadFn - >, - ): Route< - TRegister, - TParentRoute, - TPath, - TFullPath, + createRoute: FileRouteFactory< TFilePath, + TParentRoute, TId, - TSearchValidator, - TParams, - AnyContext, - TRouteContextFn, - TBeforeLoadFn, - TLoaderDeps, - TLoaderFn, - TChildren, - unknown, - TSSR, - TMiddlewares, - THandlers - > => { + TPath, + TFullPath + > = (options) => { if (process.env.NODE_ENV !== 'production') { if (!this.silent) { console.warn( @@ -182,7 +202,7 @@ export function FileRouteLoader< return (loaderFn) => loaderFn as any } -declare module '@tanstack/router-core' { +declare module '@tanstack/router-core/extensions' { export interface LazyRoute { useMatch: UseMatchRoute useRouteContext: UseRouteContextRoute diff --git a/packages/vue-router/src/index.tsx b/packages/vue-router/src/index.tsx index f63a763e25..1a7e548040 100644 --- a/packages/vue-router/src/index.tsx +++ b/packages/vue-router/src/index.tsx @@ -180,6 +180,8 @@ export type { ResolvedRedirect, MakeRouteMatch, MakeRouteMatchUnion, + KnownRouteMatchUnion, + ForeignRouteMatch, RouteMatch, AnyRouteMatch, RouteContextFn, @@ -265,9 +267,54 @@ export type { ErrorRouteComponent, NotFoundRouteComponent, } from './route' +// `createFileRoute` returns router-core's `Route`, and `Route` above is this +// package's class: declarations name the type of file routes through this +// export, so they need no import of `@tanstack/router-core`. +export type { Route as RouteCore } from '@tanstack/router-core' export { createRouter, Router } from './router' +export type { + FileRoutesByPathEntry, + FileRouteScope, + RouteScope, +} from './routeModule' +export type { FileRouteFactory } from './fileRoute' +export type { + HostedRouter, + InstallationRoutesById, + MountedRoutesById, + ModuleRootRoute, + ModuleRootRouteOptions, + MountRouteModuleOptions, + RedirectFn, + RegisteredRouterOf, + ScopeRouter, + ScopedRouter, + ScopedRouterView, + ValidateRouteModuleMount, + ValidateRouteModuleMountPath, +} from '@tanstack/router-core' +export type { GetRouteApiFn } from './route' +export type { CreateLinkFn, LinkOptionsFn } from './link' +export type { NavigateComponentFn, UseNavigateFn } from './useNavigate' +export type { + MatchRouteComponentType, + UseChildMatchesFn, + UseMatchRouteFn, + UseMatchesFn, + UseParentMatchesFn, +} from './Matches' +export type { UseRouterFn } from './useRouter' +export type { UseMatchFn } from './useMatch' +export type { UseLoaderDataFn } from './useLoaderData' +export type { UseLoaderDepsFn } from './useLoaderDeps' +export type { UseSearchFn } from './useSearch' +export type { UseParamsFn } from './useParams' +export type { UseRouteContextFn } from './useRouteContext' +export type { UseLocationFn } from './useLocation' +export type { UseRouterStateFn } from './useRouterState' + export { lazyFn, SearchParamError } from '@tanstack/router-core' export { RouterProvider, RouterContextProvider } from './RouterProvider' diff --git a/packages/vue-router/src/link.tsx b/packages/vue-router/src/link.tsx index 34666743e3..8efd6cb949 100644 --- a/packages/vue-router/src/link.tsx +++ b/packages/vue-router/src/link.tsx @@ -10,17 +10,20 @@ import { import { isServer } from '@tanstack/router-core/isServer' import { useRouter } from './useRouter' -import { linkLocationContext } from './matchContext' +import { linkLocationContext, routeIdContext } from './matchContext' import { useIntersectionObserver } from './utils' - import type { AnyRouter, Constrain, LinkOptions, ParsedLocation, + Register, RegisteredRouter, + RegisteredRouterOf, RoutePaths, + ScopedRouteOptions, } from '@tanstack/router-core' + import type { AnchorHTMLAttributes, ReservedProps } from '@vue/runtime-dom' import type { ValidateLinkOptions, @@ -87,6 +90,16 @@ type AnyLinkPropsOptions = UseLinkPropsOptions & { } type LinkEventOptions = AnyLinkPropsOptions & Partial +export type UseLinkPropsFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TFrom extends string = string, + TTo extends string = '', + TMaskFrom extends string = TFrom, + TMaskTo extends string = '', +>( + options: UseLinkPropsOptions, +) => Vue.Ref + export function useLinkProps< TRouter extends AnyRouter = RegisteredRouter, TFrom extends RoutePaths | string = string, @@ -95,20 +108,21 @@ export function useLinkProps< TMaskTo extends string = '', >( options: UseLinkPropsOptions, -): LinkHTMLAttributes { +): Vue.Ref { return useLinkPropsImpl(() => options as AnyLinkPropsOptions) } -function useLinkPropsImpl( +/** @internal Shared by the scoped hook, which supplies live scoped options. */ +export function useLinkPropsImpl( getOptions: () => AnyLinkPropsOptions, -): LinkHTMLAttributes { +): Vue.Ref { const router = useRouter() let renderFetchedHref: string | undefined // Ensure router is defined before proceeding if (!router) { console.warn('useRouter must be used inside a component!') - return {} + return Vue.shallowRef({}) } // During SSR we render exactly once and do not need reactivity. @@ -118,10 +132,17 @@ function useLinkPropsImpl( if (getUrlScheme(`${options.to}`)) { return Vue.shallowRef( getExternalLinkProps(options, router), - ) as unknown as LinkHTMLAttributes + ) as Vue.Ref } - const next = router.buildLocation(options as any) + const next = router.buildLocation( + (options._module === undefined + ? options + : { + ...options, + _nearestRoute: Vue.inject(routeIdContext, undefined), + }) as any, + ) const href = getHref(options, router, next) const isActive = @@ -150,7 +171,7 @@ function useLinkPropsImpl( return Vue.shallowRef( result as LinkHTMLAttributes, - ) as unknown as LinkHTMLAttributes + ) as Vue.Ref } const ref = Vue.ref(null) @@ -172,6 +193,9 @@ function useLinkPropsImpl( // place, so a reactive option value (checked one level deep, not nested) // gets a fresh object per location instead, re-read at each navigation. A // mask holds destination options of its own, so its values are checked too. + // The nearest route resolves module destinations to the installation the + // Link renders under; other destinations ignore it. + const routeId = Vue.inject(routeIdContext, undefined) const dest = Vue.computed((prev?: Record) => { const options = getOptions() as Record const dest: Record = {} @@ -187,6 +211,7 @@ function useLinkPropsImpl( } same &&= prev![key] === value } + dest._nearestRoute = routeId return same ? prev! : dest }) @@ -424,7 +449,7 @@ function useLinkPropsImpl( }) // Return the computed ref itself - callers should access .value - return computedProps as unknown as LinkHTMLAttributes + return computedProps } // [href, active] of an internal Link. @@ -447,6 +472,9 @@ const NAVIGATION_KEYS = [ 'unsafeRelative', 'from', 'href', + // Internal route-module scope (see `scopeLocationOptions` in router-core). + '_module', + '_fromRoute', ] as const function resolveStyleProps(options: AnyLinkPropsOptions, isActive: boolean) { @@ -811,8 +839,9 @@ export type CreateLinkProps = LinkProps< export type LinkComponent< in out TComp, in out TDefaultFrom extends string = string, + in out TDefaultRegister = Register, > = < - TRouter extends AnyRouter = RegisteredRouter, + TRouter extends AnyRouter = RegisteredRouterOf, const TFrom extends string = TDefaultFrom, const TTo extends string | undefined = undefined, const TMaskFrom extends string = TFrom, @@ -823,10 +852,11 @@ export type LinkComponent< export interface LinkComponentRoute< in out TDefaultFrom extends string = string, + in out TDefaultRegister = Register, > { defaultFrom: TDefaultFrom; < - TRouter extends AnyRouter = RegisteredRouter, + TRouter extends AnyRouter = RegisteredRouterOf, const TTo extends string | undefined = undefined, const TMaskTo extends string = '', >( @@ -841,6 +871,14 @@ export interface LinkComponentRoute< ): Vue.VNode } +/** + * The signature of `createLink`, creating links typed against the router of `TDefaultRegister`. + * Route modules export a `createLink` of this type. + */ +export type CreateLinkFn = ( + Comp: Constrain Vue.VNode>, +) => LinkComponent + export function createLink( Comp: Constrain Vue.VNode>, ): LinkComponent { @@ -916,7 +954,7 @@ const LinkImpl = Vue.defineComponent({ (isServer ?? useRouter()?.isServer) ? () => ({ ...props, ...attrs }) : useLinkPropsSnapshot(props, attrs), - ) as LinkHTMLAttributes | Vue.ComputedRef + ) return () => { const Component = props._asChild || 'a' @@ -968,12 +1006,12 @@ export type LinkOptionsFnOptions< ? ValidateLinkOptionsArray : ValidateLinkOptions -export type LinkOptionsFn = < +export type LinkOptionsFn = < const TOptions, - TRouter extends AnyRouter = RegisteredRouter, + TRouter extends AnyRouter = RegisteredRouterOf, >( options: LinkOptionsFnOptions, -) => TOptions +) => ScopedRouteOptions export const linkOptions: LinkOptionsFn<'a'> = (options) => { return options as any diff --git a/packages/vue-router/src/route-module-internal.ts b/packages/vue-router/src/route-module-internal.ts new file mode 100644 index 0000000000..3ac86d6306 --- /dev/null +++ b/packages/vue-router/src/route-module-internal.ts @@ -0,0 +1,6 @@ +// Internal generated/framework wiring; use generated scopes to author modules. +export * from './routeModule' +export { + mountRouteModule, + getRouteModuleId, +} from '@tanstack/router-core/_internal/route-module' diff --git a/packages/vue-router/src/route.ts b/packages/vue-router/src/route.ts index 7c931ecdf9..1b783b990b 100644 --- a/packages/vue-router/src/route.ts +++ b/packages/vue-router/src/route.ts @@ -4,6 +4,7 @@ import { BaseRouteApi, notFound, } from '@tanstack/router-core' +import { getRouteNavigationScope } from '@tanstack/router-core/_internal/route-module' import * as Vue from 'vue' import { Link } from './link' import { useLoaderData } from './useLoaderData' @@ -24,6 +25,7 @@ import type { NotFoundRouteProps, Register, RegisteredRouter, + RegisteredRouterOf, ResolveFullPath, ResolveId, ResolveParams, @@ -57,7 +59,7 @@ export type VueSFC = { render?: Function } -declare module '@tanstack/router-core' { +declare module '@tanstack/router-core/extensions' { export interface UpdatableRouteOptionsExtensions { component?: RouteComponent | VueSFC errorComponent?: false | null | undefined | ErrorRouteComponent | VueSFC @@ -68,18 +70,31 @@ declare module '@tanstack/router-core' { export interface RouteExtensions< in out TId extends string, in out TFullPath extends string, + in out TRegister, > { - useMatch: UseMatchRoute - useRouteContext: UseRouteContextRoute - useSearch: UseSearchRoute - useParams: UseParamsRoute - useLoaderDeps: UseLoaderDepsRoute - useLoaderData: UseLoaderDataRoute - useNavigate: () => UseNavigateResult - Link: LinkComponentRoute + useMatch: UseMatchRoute + useRouteContext: UseRouteContextRoute + useSearch: UseSearchRoute + useParams: UseParamsRoute + useLoaderDeps: UseLoaderDepsRoute + useLoaderData: UseLoaderDataRoute + useNavigate: () => UseNavigateResult + Link: LinkComponentRoute } } +/** + * The signature of `getRouteApi`, typed against the router of `TDefaultRegister` unless a + * router type is passed explicitly. Route modules export a `getRouteApi` of + * this type. + */ +export type GetRouteApiFn = < + const TId, + TRouter extends AnyRouter = RegisteredRouterOf, +>( + id: ConstrainLiteral>, +) => RouteApi + export function getRouteApi< const TId, TRouter extends AnyRouter = RegisteredRouter, @@ -98,53 +113,65 @@ export class RouteApi< super({ id }) } - useMatch: UseMatchRoute = (opts) => { + useMatch: UseMatchRoute = (opts) => { return useMatch({ ...opts, from: this.id } as any) as any } - useRouteContext: UseRouteContextRoute = (opts) => { + useRouteContext: UseRouteContextRoute = (opts) => { return useRouteContext({ ...(opts as any), from: this.id }) } - useSearch: UseSearchRoute = (opts) => { + useSearch: UseSearchRoute = (opts) => { return useSearch({ ...opts, from: this.id } as any) } - useParams: UseParamsRoute = (opts) => { + useParams: UseParamsRoute = (opts) => { return useParams({ ...opts, from: this.id } as any) } - useLoaderDeps: UseLoaderDepsRoute = (opts) => { + useLoaderDeps: UseLoaderDepsRoute = (opts) => { return useLoaderDeps({ ...opts, from: this.id, strict: false } as any) } - useLoaderData: UseLoaderDataRoute = (opts) => { + useLoaderData: UseLoaderDataRoute = (opts) => { return useLoaderData({ ...opts, from: this.id, strict: false } as any) } useNavigate = (): UseNavigateResult< - RouteTypesById['fullPath'] + RouteTypesById['fullPath'], + { router: TRouter } > => { const router = useRouter() - return useNavigate({ from: router.routesById[this.id as string].fullPath }) + return useNavigate( + getRouteNavigationScope( + this.id as string, + router.routesById[this.id as string]?.fullPath, + ) as any, + ) as any } notFound = (opts?: NotFoundError) => { return notFound({ routeId: this.id as string, ...opts }) } - Link: LinkComponentRoute['fullPath']> = (( - props, - ctx?: Vue.SetupContext, - ) => { + Link: LinkComponentRoute< + RouteTypesById['fullPath'], + { router: TRouter } + > = ((props, ctx?: Vue.SetupContext) => { const router = useRouter() - const fullPath = router.routesById[this.id as string].fullPath + const fullPath = router.routesById[this.id as string]?.fullPath return Vue.h( Link as any, - { from: fullPath as never, ...(props as any) }, + { + ...(getRouteNavigationScope(this.id as string, fullPath) as any), + ...(props as any), + }, ctx?.slots, ) - }) as LinkComponentRoute['fullPath']> + }) as LinkComponentRoute< + RouteTypesById['fullPath'], + { router: TRouter } + > } export class Route< @@ -242,41 +269,49 @@ export class Route< super(options) } - useMatch: UseMatchRoute = (opts) => { + useMatch: UseMatchRoute = (opts) => { return useMatch({ ...opts, from: this.id } as any) as any } - useRouteContext: UseRouteContextRoute = (opts?) => { + useRouteContext: UseRouteContextRoute = (opts?) => { return useRouteContext({ ...(opts as any), from: this.id }) } - useSearch: UseSearchRoute = (opts) => { + useSearch: UseSearchRoute = (opts) => { return useSearch({ ...opts, from: this.id } as any) } - useParams: UseParamsRoute = (opts) => { + useParams: UseParamsRoute = (opts) => { return useParams({ ...opts, from: this.id } as any) } - useLoaderDeps: UseLoaderDepsRoute = (opts) => { + useLoaderDeps: UseLoaderDepsRoute = (opts) => { return useLoaderDeps({ ...opts, from: this.id } as any) } - useLoaderData: UseLoaderDataRoute = (opts) => { + useLoaderData: UseLoaderDataRoute = (opts) => { return useLoaderData({ ...opts, from: this.id } as any) } - useNavigate = (): UseNavigateResult => { - return useNavigate({ from: this.fullPath }) + useNavigate = (): UseNavigateResult => { + return useNavigate( + getRouteNavigationScope(this.id, this.fullPath) as any, + ) as any } - Link: LinkComponentRoute = ((props, ctx?: Vue.SetupContext) => { + Link: LinkComponentRoute = (( + props, + ctx?: Vue.SetupContext, + ) => { return Vue.h( Link as any, - { from: this.fullPath as never, ...(props as any) }, + { + ...(getRouteNavigationScope(this.id, this.fullPath) as any), + ...(props as any), + }, ctx?.slots, ) - }) as LinkComponentRoute + }) as LinkComponentRoute } export function createRoute< @@ -475,37 +510,40 @@ export class RootRoute< super(options) } - useMatch: UseMatchRoute = (opts) => { + useMatch: UseMatchRoute = (opts) => { return useMatch({ ...opts, from: this.id } as any) as any } - useRouteContext: UseRouteContextRoute = (opts) => { + useRouteContext: UseRouteContextRoute = (opts) => { return useRouteContext({ ...(opts as any), from: this.id }) } - useSearch: UseSearchRoute = (opts) => { + useSearch: UseSearchRoute = (opts) => { return useSearch({ ...opts, from: this.id } as any) } - useParams: UseParamsRoute = (opts) => { + useParams: UseParamsRoute = (opts) => { return useParams({ ...opts, from: this.id } as any) } - useLoaderDeps: UseLoaderDepsRoute = (opts) => { + useLoaderDeps: UseLoaderDepsRoute = (opts) => { return useLoaderDeps({ ...opts, from: this.id } as any) } - useLoaderData: UseLoaderDataRoute = (opts) => { + useLoaderData: UseLoaderDataRoute = (opts) => { return useLoaderData({ ...opts, from: this.id } as any) } - useNavigate = (): UseNavigateResult<'/'> => { - return useNavigate({ from: this.fullPath }) + useNavigate = (): UseNavigateResult<'/', TRegister> => { + return useNavigate({ from: this.fullPath }) as any } - Link: LinkComponentRoute<'/'> = ((props, ctx?: Vue.SetupContext) => { + Link: LinkComponentRoute<'/', TRegister> = (( + props, + ctx?: Vue.SetupContext, + ) => { return Vue.h(Link, { from: this.fullPath as never, ...props }, ctx?.slots) - }) as LinkComponentRoute<'/'> + }) as LinkComponentRoute<'/', TRegister> } export function createRouteMask< diff --git a/packages/vue-router/src/routeModule.ts b/packages/vue-router/src/routeModule.ts new file mode 100644 index 0000000000..f29bd3b246 --- /dev/null +++ b/packages/vue-router/src/routeModule.ts @@ -0,0 +1,441 @@ +import * as Vue from 'vue' +import { notFound } from '@tanstack/router-core' +import { + bindRouteScopeOptions, + createScopedRedirect, + getInstallationRouteIdMapper, + getScopedRouterView, +} from '@tanstack/router-core/_internal/route-module' +import { Route, getRouteApi } from './route' +import { Link, useLinkPropsImpl } from './link' +import { useBlocker } from './useBlocker' +import { Navigate, useNavigate } from './useNavigate' +import { + MatchRoute, + useChildMatches, + useMatchRoute, + useMatches, + useParentMatches, +} from './Matches' +import { useRouter } from './useRouter' +import { routeIdContext } from './matchContext' +import { useMatch } from './useMatch' +import { useLoaderData } from './useLoaderData' +import { useLoaderDeps } from './useLoaderDeps' +import { useSearch } from './useSearch' +import { useParams } from './useParams' +import { useRouteContext } from './useRouteContext' +import { useLocation } from './useLocation' +import { useRouterState } from './useRouterState' +import type { UseBlockerFn } from './useBlocker' +import type { + AnyContext, + AnyRoute, + AnyRouter, + ModuleRootRoute, + ModuleRootRouteOptions, + NotFoundError, + RedirectFn, + RouteIds, + ScopedRouterView, +} from '@tanstack/router-core' +import type { FileRouteFactory } from './fileRoute' +import type { GetRouteApiFn } from './route' +import type { + CreateLinkFn, + LinkComponent, + LinkOptionsFn, + UseLinkPropsFn, +} from './link' +import type { NavigateComponentFn, UseNavigateFn } from './useNavigate' +import type { + MatchRouteComponentType, + UseChildMatchesFn, + UseMatchRouteFn, + UseMatchesFn, + UseParentMatchesFn, +} from './Matches' +import type { UseMatchFn } from './useMatch' +import type { UseLoaderDataFn } from './useLoaderData' +import type { UseLoaderDepsFn } from './useLoaderDeps' +import type { UseSearchFn } from './useSearch' +import type { UseParamsFn } from './useParams' +import type { UseRouteContextFn } from './useRouteContext' +import type { UseLocationFn } from './useLocation' +import type { UseRouterStateFn } from './useRouterState' + +/** An entry of a generated module-local `FileRoutesByPath` interface. */ +export interface FileRoutesByPathEntry { + id: string + path: string + fullPath: string + parentRoute: AnyRoute +} + +// Entries reference the route files, whose types depend on these factories: +// read one property at a time and never constrain or check whole entries. +type FileRouteEntry = + TFileRoutesByPath[TFilePath & keyof TFileRoutesByPath] +type FileRouteParent = + FileRouteEntry extends { + parentRoute: infer TParentRoute extends AnyRoute + } + ? TParentRoute + : never +type FileRouteId = + FileRouteEntry extends { + id: infer TId extends string + } + ? TId + : never +type FileRoutePath = + FileRouteEntry extends { + path: infer TPath extends string + } + ? TPath + : never +type FileRouteFullPath = + FileRouteEntry extends { + fullPath: infer TFullPath extends string + } + ? TFullPath + : never + +/** + * Route factories of a route module, typed against the module's generated + * `FileRoutesByPath` and its scope register instead of the application's + * global registrations. + */ +export interface FileRouteScope< + TFileRoutesByPath, + TRegister, + TModuleId extends string, +> { + /** `createFileRoute`, typed against the module's own route files. */ + createFileRoute: ( + path?: TFilePath, + ) => FileRouteFactory< + FileRouteId, + FileRouteParent, + FileRouteId, + FileRoutePath, + FileRouteFullPath, + TRegister + > + /** + * Creates the module root. `TRouterContext` is the router context the module + * requires from the route it is mounted under. + */ + createModuleRoot: () => < + TRouteContextFn = AnyContext, + TBeforeLoadFn = AnyContext, + TSearchValidator = undefined, + TLoaderDeps extends Record = {}, + TLoaderFn = undefined, + TSSR = unknown, + const TServerMiddlewares = unknown, + THandlers = undefined, + >( + options?: ModuleRootRouteOptions< + TModuleId, + TRegister, + TSearchValidator, + TRouterContext, + TRouteContextFn, + TBeforeLoadFn, + TLoaderDeps, + TLoaderFn, + TSSR, + TServerMiddlewares, + THandlers + >, + ) => ModuleRootRoute< + TModuleId, + TRegister, + TSearchValidator, + TRouterContext, + TRouteContextFn, + TBeforeLoadFn, + TLoaderDeps, + TLoaderFn, + unknown, + unknown, + TSSR, + TServerMiddlewares, + THandlers + > +} + +/** Binds only the module-root factory used by generated route scopes. */ +export function bindCreateModuleRoot( + moduleId: TModuleId, +): FileRouteScope['createModuleRoot'] { + return () => (options) => + new Route({ ...(options as any), _module: moduleId }) as any +} + +/** + * The routing APIs of a route scope, typed against `TRouter`. + * + * Path-based APIs (`Link`, `useNavigate`, `redirect`, ...) address routes by + * the module-local paths of the module: they work wherever the module is + * mounted. Id-based APIs (`useMatch`, `getRouteApi`, ...) take qualified route + * ids such as `@acme/products:/$productId`. + */ +export interface RouteScope { + Link: LinkComponent<'a', string, { router: TRouter }> + createLink: CreateLinkFn<{ router: TRouter }> + linkOptions: LinkOptionsFn<'a', { router: TRouter }> + Navigate: NavigateComponentFn<{ router: TRouter }> + useNavigate: UseNavigateFn<{ router: TRouter }> + useLinkProps: UseLinkPropsFn<{ router: TRouter }> + useBlocker: UseBlockerFn<{ router: TRouter }> + notFound: ( + options?: Omit & { + routeId?: RouteIds + }, + ) => NotFoundError + redirect: RedirectFn<{ router: TRouter }> + MatchRoute: MatchRouteComponentType<{ router: TRouter }> + useMatchRoute: UseMatchRouteFn<{ router: TRouter }> + /** + * The router, viewed from the module: its `navigate`, `buildLocation`, + * `preloadRoute` and `matchRoute` take module-local paths. + */ + useRouter: (opts?: { warn?: boolean }) => ScopedRouterView + getRouteApi: GetRouteApiFn<{ router: TRouter }> + useMatch: UseMatchFn<{ router: TRouter }> + useMatches: UseMatchesFn<{ router: TRouter }> + useParentMatches: UseParentMatchesFn<{ router: TRouter }> + useChildMatches: UseChildMatchesFn<{ router: TRouter }> + useLoaderData: UseLoaderDataFn<{ router: TRouter }> + useLoaderDeps: UseLoaderDepsFn<{ router: TRouter }> + useSearch: UseSearchFn<{ router: TRouter }> + useParams: UseParamsFn<{ router: TRouter }> + useRouteContext: UseRouteContextFn<{ router: TRouter }> + useLocation: UseLocationFn<{ router: TRouter }> + useRouterState: UseRouterStateFn<{ router: TRouter }> +} + +// Each generated ESM export binds only its own API. These functions allocate +// closures/components; they never access a router or register runtime state. +function bindOptions(moduleId: string): (options: any) => any { + const router = useRouter() + const routeId = Vue.inject(routeIdContext, undefined) + return (options: any) => + bindRouteScopeOptions(moduleId, options ?? {}, router, routeId) +} + +function bindIdHook(moduleId: string, hook: (options: any) => any) { + const toInstallation = getInstallationRouteIdMapper(moduleId) + return toInstallation + ? (options?: { from?: string }) => + hook({ ...options, from: toInstallation(options?.from) }) + : hook +} + +function scopedComponent( + moduleId: string, + name: string, + component: any, + extra?: object, +) { + return Vue.defineComponent({ + name, + inheritAttrs: false, + setup(_, { attrs, slots }) { + const bind = bindOptions(moduleId) + return () => Vue.h(component, { ...bind(attrs), ...extra }, slots) + }, + }) +} + +export function bindRouteScopeLink( + moduleId: string, +): RouteScope['Link'] { + return scopedComponent(moduleId, 'Link', Link) as any +} + +export function bindRouteScopeCreateLink( + moduleId: string, +): RouteScope['createLink'] { + return ((Comp: unknown) => + scopedComponent(moduleId, 'Link', Link, { _asChild: Comp })) as any +} + +export function bindRouteScopeNavigate( + moduleId: string, +): RouteScope['Navigate'] { + return scopedComponent(moduleId, 'Navigate', Navigate) as any +} + +export function bindRouteScopeMatchRoute( + moduleId: string, +): RouteScope['MatchRoute'] { + return Vue.defineComponent({ + name: 'MatchRoute', + inheritAttrs: false, + setup(_, { attrs, slots }) { + const bind = bindOptions(moduleId) + const routeId = Vue.inject(routeIdContext, undefined) + return () => + Vue.h( + MatchRoute as any, + { ...bind(attrs), _nearestRoute: routeId }, + slots, + ) + }, + }) as any +} + +export function bindRouteScopeUseLinkProps( + moduleId: string, +): RouteScope['useLinkProps'] { + return ((options: any) => { + const bind = bindOptions(moduleId) + return useLinkPropsImpl(() => bind(options)) + }) as any +} + +export function bindRouteScopeLinkOptions( + moduleId: string, +): RouteScope['linkOptions'] { + return ((options: any) => + Array.isArray(options) + ? options.map((option) => bindRouteScopeOptions(moduleId, option)) + : bindRouteScopeOptions(moduleId, options)) as any +} + +export function bindRouteScopeUseNavigate( + moduleId: string, +): RouteScope['useNavigate'] { + return ((options?: any) => { + const bind = bindOptions(moduleId) + const navigate = useNavigate(bind(options)) + return (next: any) => navigate(bind(next)) + }) as any +} + +export function bindRouteScopeRedirect( + moduleId: string, +): RouteScope['redirect'] { + return createScopedRedirect(moduleId) +} + +export function bindRouteScopeUseMatchRoute( + moduleId: string, +): RouteScope['useMatchRoute'] { + return (() => { + const bind = bindOptions(moduleId) + const matchRoute = useMatchRoute() + const routeId = Vue.inject(routeIdContext, undefined) + return (options: any) => + matchRoute({ ...bind(options), _nearestRoute: routeId }) + }) as any +} + +export function bindRouteScopeUseRouter( + moduleId: string, +): RouteScope['useRouter'] { + return ((options?: { warn?: boolean }) => + getScopedRouterView( + useRouter(options), + moduleId, + Vue.inject(routeIdContext, undefined), + )) as any +} + +export function bindRouteScopeGetRouteApi( + moduleId: string, +): RouteScope['getRouteApi'] { + const toInstallation = getInstallationRouteIdMapper(moduleId) + return ( + toInstallation + ? (id: string) => getRouteApi(toInstallation(id) as never) + : getRouteApi + ) as any +} + +export function bindRouteScopeUseMatch( + moduleId: string, +): RouteScope['useMatch'] { + return bindIdHook(moduleId, useMatch) as any +} + +export function bindRouteScopeUseLoaderData( + moduleId: string, +): RouteScope['useLoaderData'] { + return bindIdHook(moduleId, useLoaderData) as any +} + +export function bindRouteScopeUseLoaderDeps( + moduleId: string, +): RouteScope['useLoaderDeps'] { + return bindIdHook(moduleId, useLoaderDeps) as any +} + +export function bindRouteScopeUseSearch( + moduleId: string, +): RouteScope['useSearch'] { + return bindIdHook(moduleId, useSearch) as any +} + +export function bindRouteScopeUseParams( + moduleId: string, +): RouteScope['useParams'] { + return bindIdHook(moduleId, useParams) as any +} + +export function bindRouteScopeUseRouteContext( + moduleId: string, +): RouteScope['useRouteContext'] { + return bindIdHook(moduleId, useRouteContext) as any +} + +export function bindRouteScopeUseMatches( + _moduleId: string, +): RouteScope['useMatches'] { + return useMatches as any +} + +export function bindRouteScopeUseParentMatches( + _moduleId: string, +): RouteScope['useParentMatches'] { + return useParentMatches as any +} + +export function bindRouteScopeUseChildMatches( + _moduleId: string, +): RouteScope['useChildMatches'] { + return useChildMatches as any +} + +export function bindRouteScopeUseLocation( + _moduleId: string, +): RouteScope['useLocation'] { + return useLocation as any +} + +export function bindRouteScopeUseRouterState( + _moduleId: string, +): RouteScope['useRouterState'] { + return useRouterState as any +} + +export function bindRouteScopeUseBlocker( + _moduleId: string, +): RouteScope['useBlocker'] { + return useBlocker as any +} + +export function bindRouteScopeNotFound( + moduleId: string, +): RouteScope['notFound'] { + const toInstallation = getInstallationRouteIdMapper(moduleId) + return ((options?: any) => + notFound( + toInstallation && options?.routeId + ? { ...options, routeId: toInstallation(options.routeId) } + : options, + )) as any +} diff --git a/packages/vue-router/src/router.ts b/packages/vue-router/src/router.ts index b1f56cf929..48bf6f5ecd 100644 --- a/packages/vue-router/src/router.ts +++ b/packages/vue-router/src/router.ts @@ -15,7 +15,7 @@ import type { } from './route' import type { VNode } from 'vue' -declare module '@tanstack/router-core' { +declare module '@tanstack/router-core/extensions' { export interface RouterOptionsExtensions { /** * The default `component` a route should use if no component is provided. diff --git a/packages/vue-router/src/routerStores.ts b/packages/vue-router/src/routerStores.ts index a7aafa0287..171e4124bc 100644 --- a/packages/vue-router/src/routerStores.ts +++ b/packages/vue-router/src/routerStores.ts @@ -2,7 +2,7 @@ import { batch, createAtom } from '@tanstack/vue-store' import type { GetStoreConfig } from '@tanstack/router-core' import type { Readable } from '@tanstack/vue-store' -declare module '@tanstack/router-core' { +declare module '@tanstack/router-core/extensions' { export interface RouterReadableStore extends Readable {} } diff --git a/packages/vue-router/src/useBlocker.tsx b/packages/vue-router/src/useBlocker.tsx index 17eef20f7a..02f9345646 100644 --- a/packages/vue-router/src/useBlocker.tsx +++ b/packages/vue-router/src/useBlocker.tsx @@ -1,3 +1,4 @@ +import { isServer } from '@tanstack/router-core/isServer' import * as Vue from 'vue' import { useRouter } from './useRouter' import type { @@ -10,6 +11,8 @@ import type { AnyRouter, ParseRoute, RegisteredRouter, + RegisteredRouterOf, + RouteScopeMarker, } from '@tanstack/router-core' type ShouldBlockFnLocation< @@ -29,14 +32,21 @@ type AnyShouldBlockFnLocation = ShouldBlockFnLocation type MakeShouldBlockFnLocationUnion< TRouter extends AnyRouter = RegisteredRouter, TRoute extends AnyRoute = ParseRoute, -> = TRoute extends any +> = TRouter['routeTree'] extends RouteScopeMarker ? ShouldBlockFnLocation< - TRoute['id'], - TRoute['fullPath'], - TRoute['types']['allParams'], - TRoute['types']['fullSearchSchema'] + string, + string, + Record, + Record > - : never + : TRoute extends any + ? ShouldBlockFnLocation< + TRoute['id'], + TRoute['fullPath'], + TRoute['types']['allParams'], + TRoute['types']['fullSearchSchema'] + > + : never type BlockerResolver = | { @@ -128,6 +138,14 @@ function _resolveBlockerOpts( } } +/** The generated module hook observes navigation across the entire application. */ +export type UseBlockerFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TWithResolver extends boolean = false, +>( + opts: UseBlockerOpts, +) => TWithResolver extends true ? Vue.Ref> : void + export function useBlocker< TRouter extends AnyRouter = RegisteredRouter, TWithResolver extends boolean = false, @@ -164,14 +182,19 @@ export function useBlocker( const router = useRouter() const { history } = router - const resolver = Vue.ref({ + const idle: BlockerResolver = { status: 'idle', current: undefined, next: undefined, action: undefined, proceed: undefined, reset: undefined, - }) + } + if (isServer ?? router.isServer) { + return withResolver ? Vue.toRef(() => idle) : undefined + } + + const resolver = Vue.ref(idle) Vue.watchEffect((onCleanup) => { const blockerFnComposed = async (blockerFnArgs: BlockerFnArgs) => { diff --git a/packages/vue-router/src/useLoaderData.tsx b/packages/vue-router/src/useLoaderData.tsx index c4cbcb2f93..fc3bf3f442 100644 --- a/packages/vue-router/src/useLoaderData.tsx +++ b/packages/vue-router/src/useLoaderData.tsx @@ -2,7 +2,9 @@ import { useMatch } from './useMatch' import type * as Vue from 'vue' import type { AnyRouter, + Register, RegisteredRouter, + RegisteredRouterOf, ResolveUseLoaderData, StrictOrFrom, UseLoaderDataResult, @@ -25,13 +27,26 @@ export type UseLoaderDataOptions< > = StrictOrFrom & UseLoaderDataBaseOptions -export type UseLoaderDataRoute = < - TRouter extends AnyRouter = RegisteredRouter, +export type UseLoaderDataRoute = < + TRouter extends AnyRouter = RegisteredRouterOf, TSelected = unknown, >( opts?: UseLoaderDataBaseOptions, ) => Vue.Ref> +/** + * The signature of `useLoaderData`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useLoaderData` of this type. + */ +export type UseLoaderDataFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TFrom extends string | undefined = undefined, + TStrict extends boolean = true, + TSelected = unknown, +>( + opts: UseLoaderDataOptions, +) => Vue.Ref> + export function useLoaderData< TRouter extends AnyRouter = RegisteredRouter, const TFrom extends string | undefined = undefined, diff --git a/packages/vue-router/src/useLoaderDeps.tsx b/packages/vue-router/src/useLoaderDeps.tsx index ecf9f54f4e..e168e9ae77 100644 --- a/packages/vue-router/src/useLoaderDeps.tsx +++ b/packages/vue-router/src/useLoaderDeps.tsx @@ -2,7 +2,9 @@ import { useMatch } from './useMatch' import type * as Vue from 'vue' import type { AnyRouter, + Register, RegisteredRouter, + RegisteredRouterOf, ResolveUseLoaderDeps, StrictOrFrom, UseLoaderDepsResult, @@ -23,13 +25,25 @@ export type UseLoaderDepsOptions< > = StrictOrFrom & UseLoaderDepsBaseOptions -export type UseLoaderDepsRoute = < - TRouter extends AnyRouter = RegisteredRouter, +export type UseLoaderDepsRoute = < + TRouter extends AnyRouter = RegisteredRouterOf, TSelected = unknown, >( opts?: UseLoaderDepsBaseOptions, ) => Vue.Ref> +/** + * The signature of `useLoaderDeps`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useLoaderDeps` of this type. + */ +export type UseLoaderDepsFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TFrom extends string | undefined = undefined, + TSelected = unknown, +>( + opts: UseLoaderDepsOptions, +) => Vue.Ref> + export function useLoaderDeps< TRouter extends AnyRouter = RegisteredRouter, const TFrom extends string | undefined = undefined, diff --git a/packages/vue-router/src/useLocation.tsx b/packages/vue-router/src/useLocation.tsx index 144ca8ced9..809205bbf8 100644 --- a/packages/vue-router/src/useLocation.tsx +++ b/packages/vue-router/src/useLocation.tsx @@ -2,7 +2,9 @@ import { useSelector } from '@tanstack/vue-store' import { useRouter } from './useRouter' import type { AnyRouter, + Register, RegisteredRouter, + RegisteredRouterOf, RouterState, } from '@tanstack/router-core' import type * as Vue from 'vue' @@ -18,6 +20,17 @@ export type UseLocationResult< ? RouterState['location'] : TSelected +/** + * The signature of `useLocation`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useLocation` of this type. + */ +export type UseLocationFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TSelected = unknown, +>( + opts?: UseLocationBaseOptions, +) => Vue.Ref> + export function useLocation< TRouter extends AnyRouter = RegisteredRouter, TSelected = unknown, diff --git a/packages/vue-router/src/useMatch.tsx b/packages/vue-router/src/useMatch.tsx index 5bffc5fdcf..8846086e3a 100644 --- a/packages/vue-router/src/useMatch.tsx +++ b/packages/vue-router/src/useMatch.tsx @@ -1,5 +1,6 @@ import * as Vue from 'vue' import { invariant } from '@tanstack/router-core' +import { resolveRouteId } from '@tanstack/router-core/_internal/route-module' import { isServer } from '@tanstack/router-core/isServer' import { useSelector } from '@tanstack/vue-store' import { routeIdContext } from './matchContext' @@ -8,7 +9,10 @@ import type { AnyRouter, MakeRouteMatch, MakeRouteMatchUnion, + Register, RegisteredRouter, + RegisteredRouterOf, + RouteScopeMarker, StrictOrFrom, ThrowConstraint, ThrowOrOptional, @@ -22,13 +26,17 @@ export interface UseMatchBaseOptions< TSelected, > { select?: ( - match: MakeRouteMatch, + match: TRouter['routeTree'] extends RouteScopeMarker + ? TStrict extends true + ? MakeRouteMatch + : MakeRouteMatchUnion + : MakeRouteMatch, ) => TSelected shouldThrow?: TThrow } -export type UseMatchRoute = < - TRouter extends AnyRouter = RegisteredRouter, +export type UseMatchRoute = < + TRouter extends AnyRouter = RegisteredRouterOf, TSelected = unknown, TThrow extends boolean = true, >( @@ -57,6 +65,28 @@ export type UseMatchResult< : MakeRouteMatchUnion : TSelected +/** + * The signature of `useMatch`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useMatch` of this type. + */ +export type UseMatchFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TFrom extends string | undefined = undefined, + TStrict extends boolean = true, + TThrow extends boolean = true, + TSelected = unknown, +>( + opts: UseMatchOptions< + TRouter, + TFrom, + TStrict, + ThrowConstraint, + TSelected + >, +) => Vue.Ref< + ThrowOrOptional, TThrow> +> + export function useMatch< TRouter extends AnyRouter = RegisteredRouter, const TFrom extends string | undefined = undefined, @@ -79,11 +109,16 @@ export function useMatch< // During SSR we render exactly once and do not need reactivity. // Avoid store subscriptions and pending/transition bookkeeping on the server. if (isServer ?? router.isServer) { - const nearestRouteId = opts.from ? undefined : Vue.inject(routeIdContext) - const matchStore = - (opts.from ?? nearestRouteId) - ? router.stores.getMatchStore(opts.from ?? nearestRouteId!) - : undefined + const nearestRouteId = Vue.inject(routeIdContext, undefined) + // `from` can be the module-local id of a module installed several times: + // it resolves through the nearest match. + const routeId = + resolveRouteId && opts.from + ? resolveRouteId(router, opts.from, nearestRouteId) + : (opts.from ?? nearestRouteId) + const matchStore = routeId + ? router.stores.getMatchStore(routeId) + : undefined const match = matchStore?.get() if ((opts.shouldThrow ?? true) && !match) { @@ -105,7 +140,13 @@ export function useMatch< > } - return Vue.ref(opts.select ? opts.select(match) : match) as Vue.Ref< + return Vue.ref( + opts.select + ? opts.select( + match as unknown as Parameters>[0], + ) + : match, + ) as Vue.Ref< ThrowOrOptional< UseMatchResult, TThrow @@ -116,26 +157,24 @@ export function useMatch< // Set up reactive match value based on lookup strategy. let match: Readonly> const nearestRouteId = Vue.inject(routeIdContext) + // `from` can be the module-local id of a module installed several times: + // it resolves through the nearest match. + const routeId = + resolveRouteId && opts.from + ? resolveRouteId(router, opts.from, nearestRouteId) + : (opts.from ?? nearestRouteId) - if (opts.from) { - // routeId case: subscribe to the stable per-route presentation atom. - const matchStore = router.stores.getMatchStore(opts.from) - match = useSelector(matchStore) + if (routeId) { + // Subscribe to the stable per-route presentation atom. The nearest + // routeId is provided by the nearest Match component and doesn't change + // for the component's lifetime, so the store is stable. + match = useSelector(router.stores.getMatchStore(routeId)) } else { - // Nearest-match case: use the routeId from context for stable lookup. - // The routeId is provided by the nearest Match component and doesn't - // change for the component's lifetime, so the store is stable. - if (nearestRouteId) { - match = useSelector(router.stores.getMatchStore(nearestRouteId)) - } else { - // No route context — will fall through to error handling below - match = Vue.ref(undefined) as Readonly> - } + // No route context — will fall through to error handling below + match = Vue.ref(undefined) as Readonly> } - const ownsMatch = - nearestRouteId !== undefined && - (opts.from ?? nearestRouteId) === nearestRouteId + const ownsMatch = nearestRouteId !== undefined && routeId === nearestRouteId let lastOwnedMatch: any const result = Vue.computed(() => { if (match.value !== undefined && ownsMatch) { diff --git a/packages/vue-router/src/useNavigate.tsx b/packages/vue-router/src/useNavigate.tsx index bc3162260a..7ac2df2060 100644 --- a/packages/vue-router/src/useNavigate.tsx +++ b/packages/vue-router/src/useNavigate.tsx @@ -1,40 +1,84 @@ import * as Vue from 'vue' +import { isServer } from '@tanstack/router-core/isServer' +import { routeIdContext } from './matchContext' import { useRouter } from './useRouter' import type { AnyRouter, + CompatibleRouteScope, FromPathOption, NavigateOptions, + Register, RegisteredRouter, + RegisteredRouterOf, + RouteModuleScope, UseNavigateResult, } from '@tanstack/router-core' +/** + * The signature of `useNavigate`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useNavigate` of this type. + */ +export type UseNavigateFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TDefaultFrom extends string = string, +>(_defaultOpts?: { + from?: FromPathOption + _module?: RouteModuleScope> +}) => UseNavigateResult + export function useNavigate< TRouter extends AnyRouter = RegisteredRouter, TDefaultFrom extends string = string, >(_defaultOpts?: { from?: FromPathOption -}): UseNavigateResult { +}): UseNavigateResult { const { navigate } = useRouter() + // Route-module APIs also pass the internal `_module`/`_fromRoute` scope, + // which resolves to the installation of the nearest match. + const defaults = _defaultOpts as + | { from?: string; _module?: RouteModuleScope; _fromRoute?: string } + | undefined + const routeId = Vue.inject(routeIdContext, undefined) return ((options: NavigateOptions) => { - return navigate({ from: _defaultOpts?.from, ...options }) - }) as UseNavigateResult + return navigate({ + from: defaults?.from, + _module: defaults?._module, + _fromRoute: defaults?._fromRoute, + _nearestRoute: routeId, + ...options, + }) + }) as UseNavigateResult } -export function Navigate< - TRouter extends AnyRouter = RegisteredRouter, +/** + * The signature of `Navigate`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `Navigate` of this type. + */ +export type NavigateComponentFn = < + TRouter extends AnyRouter = RegisteredRouterOf, const TFrom extends string = string, const TTo extends string | undefined = undefined, const TMaskFrom extends string = TFrom, const TMaskTo extends string = '', ->(props: NavigateOptions): null { - const { navigate } = useRouter() +>( + props: NavigateOptions, +) => null - Vue.onMounted(() => { - navigate({ - ...props, - }) - }) - - return null -} +export const Navigate = Vue.defineComponent({ + name: 'Navigate', + inheritAttrs: false, + setup(_, { attrs }) { + const router = useRouter() + if (isServer ?? router.isServer) { + return () => null + } + const navigate = useNavigate() + const update = () => { + void navigate({ ...attrs }) + } + Vue.onMounted(update) + Vue.onUpdated(update) + return () => null + }, +}) as unknown as NavigateComponentFn diff --git a/packages/vue-router/src/useParams.tsx b/packages/vue-router/src/useParams.tsx index 6891c08adc..703d91e902 100644 --- a/packages/vue-router/src/useParams.tsx +++ b/packages/vue-router/src/useParams.tsx @@ -2,7 +2,9 @@ import { useMatch } from './useMatch' import type * as Vue from 'vue' import type { AnyRouter, + Register, RegisteredRouter, + RegisteredRouterOf, ResolveUseParams, StrictOrFrom, ThrowConstraint, @@ -30,8 +32,8 @@ export type UseParamsOptions< > = StrictOrFrom & UseParamsBaseOptions -export type UseParamsRoute = < - TRouter extends AnyRouter = RegisteredRouter, +export type UseParamsRoute = < + TRouter extends AnyRouter = RegisteredRouterOf, TSelected = unknown, TThrow extends boolean = true, >( @@ -46,6 +48,28 @@ export type UseParamsRoute = < ThrowOrOptional, TThrow> > +/** + * The signature of `useParams`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useParams` of this type. + */ +export type UseParamsFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TFrom extends string | undefined = undefined, + TStrict extends boolean = true, + TThrow extends boolean = true, + TSelected = unknown, +>( + opts: UseParamsOptions< + TRouter, + TFrom, + TStrict, + ThrowConstraint, + TSelected + >, +) => Vue.Ref< + ThrowOrOptional, TThrow> +> + export function useParams< TRouter extends AnyRouter = RegisteredRouter, const TFrom extends string | undefined = undefined, diff --git a/packages/vue-router/src/useRouteContext.ts b/packages/vue-router/src/useRouteContext.ts index 839e311925..86e09e3bf2 100644 --- a/packages/vue-router/src/useRouteContext.ts +++ b/packages/vue-router/src/useRouteContext.ts @@ -2,19 +2,34 @@ import { useMatch } from './useMatch' import type * as Vue from 'vue' import type { AnyRouter, + Register, RegisteredRouter, + RegisteredRouterOf, UseRouteContextBaseOptions, UseRouteContextOptions, UseRouteContextResult, } from '@tanstack/router-core' -export type UseRouteContextRoute = < - TRouter extends AnyRouter = RegisteredRouter, +export type UseRouteContextRoute = < + TRouter extends AnyRouter = RegisteredRouterOf, TSelected = unknown, >( opts?: UseRouteContextBaseOptions, ) => Vue.Ref> +/** + * The signature of `useRouteContext`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useRouteContext` of this type. + */ +export type UseRouteContextFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TFrom extends string | undefined = undefined, + TStrict extends boolean = true, + TSelected = unknown, +>( + opts: UseRouteContextOptions, +) => Vue.Ref> + export function useRouteContext< TRouter extends AnyRouter = RegisteredRouter, const TFrom extends string | undefined = undefined, diff --git a/packages/vue-router/src/useRouter.tsx b/packages/vue-router/src/useRouter.tsx index 21afef03df..6bcbddd8c5 100644 --- a/packages/vue-router/src/useRouter.tsx +++ b/packages/vue-router/src/useRouter.tsx @@ -1,6 +1,21 @@ import * as Vue from 'vue' import { routerContext } from './routerContext' -import type { AnyRouter, RegisteredRouter } from '@tanstack/router-core' +import type { + AnyRouter, + Register, + RegisteredRouter, + RegisteredRouterOf, +} from '@tanstack/router-core' + +/** + * The signature of `useRouter`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useRouter` of this type. + */ +export type UseRouterFn = < + TRouter extends AnyRouter = RegisteredRouterOf, +>(opts?: { + warn?: boolean +}) => TRouter export function useRouter(opts?: { warn?: boolean diff --git a/packages/vue-router/src/useRouterState.tsx b/packages/vue-router/src/useRouterState.tsx index 489b05ae91..e7d64bd4a2 100644 --- a/packages/vue-router/src/useRouterState.tsx +++ b/packages/vue-router/src/useRouterState.tsx @@ -4,7 +4,9 @@ import { useSelector } from '@tanstack/vue-store' import { useRouter } from './useRouter' import type { AnyRouter, + Register, RegisteredRouter, + RegisteredRouterOf, RouterState, } from '@tanstack/router-core' @@ -18,6 +20,17 @@ export type UseRouterStateResult< TSelected, > = unknown extends TSelected ? RouterState : TSelected +/** + * The signature of `useRouterState`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useRouterState` of this type. + */ +export type UseRouterStateFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + TSelected = unknown, +>( + opts?: UseRouterStateOptions, +) => Vue.Ref> + export function useRouterState< TRouter extends AnyRouter = RegisteredRouter, TSelected = unknown, @@ -42,7 +55,7 @@ export function useRouterState< // The expression must stay inlined in the `if` so bundlers fold the // browser-build constant `isServer = false` and drop this server block. if (isServer ?? router.isServer) { - const state = router.stores.__store.get() as RouterState< + const state = router.stores.__store.get() as unknown as RouterState< TRouter['routeTree'] > return Vue.ref(opts?.select ? opts.select(state) : state) as Vue.Ref< @@ -52,7 +65,7 @@ export function useRouterState< return useSelector(router.stores.__store, (state) => { if (opts?.select) { - return opts.select(state) + return opts.select(state as unknown as RouterState) } return state diff --git a/packages/vue-router/src/useSearch.tsx b/packages/vue-router/src/useSearch.tsx index 43f61d743f..107b7602b5 100644 --- a/packages/vue-router/src/useSearch.tsx +++ b/packages/vue-router/src/useSearch.tsx @@ -2,7 +2,9 @@ import { useMatch } from './useMatch' import type * as Vue from 'vue' import type { AnyRouter, + Register, RegisteredRouter, + RegisteredRouterOf, ResolveUseSearch, StrictOrFrom, ThrowConstraint, @@ -30,8 +32,8 @@ export type UseSearchOptions< > = StrictOrFrom & UseSearchBaseOptions -export type UseSearchRoute = < - TRouter extends AnyRouter = RegisteredRouter, +export type UseSearchRoute = < + TRouter extends AnyRouter = RegisteredRouterOf, TSelected = unknown, TThrow extends boolean = true, >( @@ -46,6 +48,28 @@ export type UseSearchRoute = < ThrowOrOptional, TThrow> > +/** + * The signature of `useSearch`, typed against the router of `TDefaultRegister` unless a router + * type is passed explicitly. Route modules export a `useSearch` of this type. + */ +export type UseSearchFn = < + TRouter extends AnyRouter = RegisteredRouterOf, + const TFrom extends string | undefined = undefined, + TStrict extends boolean = true, + TThrow extends boolean = true, + TSelected = unknown, +>( + opts: UseSearchOptions< + TRouter, + TFrom, + TStrict, + ThrowConstraint, + TSelected + >, +) => Vue.Ref< + ThrowOrOptional, TThrow> +> + export function useSearch< TRouter extends AnyRouter = RegisteredRouter, const TFrom extends string | undefined = undefined, diff --git a/packages/vue-router/tests/blocker-server.test.tsx b/packages/vue-router/tests/blocker-server.test.tsx new file mode 100644 index 0000000000..35d4f13f75 --- /dev/null +++ b/packages/vue-router/tests/blocker-server.test.tsx @@ -0,0 +1,38 @@ +import * as Vue from 'vue' +import { afterEach, expect, test, vi } from 'vitest' +import { cleanup, render, screen } from '@testing-library/vue' +import { + RouterContextProvider, + createMemoryHistory, + createRootRoute, + createRouter, + useBlocker, +} from '../src' + +afterEach(cleanup) + +test('a server router does not register navigation blockers', async () => { + const history = createMemoryHistory({ initialEntries: ['/'] }) + const block = vi.spyOn(history, 'block') + const router = createRouter({ + routeTree: createRootRoute(), + history, + isServer: true, + }) + const Observer = Vue.defineComponent({ + setup() { + const state = useBlocker({ + shouldBlockFn: () => true, + withResolver: true, + }) + return () => {state.value.status} + }, + }) + render( + + + , + ) + await screen.findByText('idle') + expect(block).not.toHaveBeenCalled() +}) diff --git a/packages/vue-router/tests/navigate-options-parity.test.tsx b/packages/vue-router/tests/navigate-options-parity.test.tsx new file mode 100644 index 0000000000..fb978a104f --- /dev/null +++ b/packages/vue-router/tests/navigate-options-parity.test.tsx @@ -0,0 +1,107 @@ +import * as Vue from 'vue' +import { renderToString } from 'vue/server-renderer' +import { afterEach, expect, test, vi } from 'vitest' +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/vue' +import { + Navigate, + Outlet, + RouterContextProvider, + RouterProvider, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '../src' + +afterEach(cleanup) + +test('Navigate leaves the request location unchanged during server rendering', async () => { + const root = createRootRoute() + const next = createRoute({ getParentRoute: () => root, path: '/next' }) + const router = createRouter({ + routeTree: root.addChildren([next]), + history: createMemoryHistory({ initialEntries: ['/'] }), + isServer: true, + }) + const navigate = vi.spyOn(router, 'navigate') + const html = await renderToString( + + + Request content + , + ) + expect(html).toContain('Request content') + expect(navigate).not.toHaveBeenCalled() + expect(router.state.location.href).toBe('/') +}) + +test('Navigate responds to option changes while mounted', async () => { + const component = Vue.defineComponent({ + setup() { + const id = Vue.ref('one') + const q = Vue.ref('first') + const replace = Vue.ref(true) + const setId = (value: string) => { + id.value = value + } + const setQ = (value: string) => { + q.value = value + } + const setReplace = (value: boolean) => { + replace.value = value + } + return () => ( + <> + + + + + + ) + }, + }) + const root = createRootRoute({ component }) + const item = createRoute({ getParentRoute: () => root, path: '/items/$id' }) + const history = createMemoryHistory({ initialEntries: ['/'] }) + const router = createRouter({ routeTree: root.addChildren([item]), history }) + render() + await waitFor(() => + expect(router.state.location.href).toBe('/items/one?q=first'), + ) + const initialLength = history.length + await fireEvent.click(screen.getByText('Change params')) + await waitFor(() => + expect(router.state.location.href).toBe('/items/two?q=first'), + ) + expect(history.length).toBe(initialLength + 1) + await fireEvent.click(screen.getByText('Change search')) + await waitFor(() => + expect(router.state.location.href).toBe('/items/two?q=second'), + ) + expect(history.length).toBe(initialLength + 1) +}) diff --git a/packages/vue-router/vite.config.ts b/packages/vue-router/vite.config.ts index 13928e0a1a..8500f1d734 100644 --- a/packages/vue-router/vite.config.ts +++ b/packages/vue-router/vite.config.ts @@ -34,6 +34,7 @@ export default mergeConfig( tsconfigPath: './tsconfig.build.json', entry: [ './src/index.tsx', + './src/route-module-internal.ts', './src/index.dev.tsx', './src/ssr/client.ts', './src/ssr/server.ts', diff --git a/packages/vue-start/package.json b/packages/vue-start/package.json index 8d734e2eb8..25b316d977 100644 --- a/packages/vue-start/package.json +++ b/packages/vue-start/package.json @@ -98,7 +98,13 @@ "default": "./dist/esm/client-only.js" } }, - "./package.json": "./package.json" + "./package.json": "./package.json", + "./_internal/route-module": { + "import": { + "types": "./dist/esm/route-module-internal.d.ts", + "default": "./dist/esm/route-module-internal.js" + } + } }, "sideEffects": false, "files": [ @@ -109,7 +115,7 @@ "!skills/_artifacts" ], "engines": { - "node": ">=22.12.0" + "node": ">=22.22.0" }, "dependencies": { "@tanstack/start-client-core": "workspace:*", diff --git a/packages/vue-start/src/index.ts b/packages/vue-start/src/index.ts index 21b3b5b003..6602558c38 100644 --- a/packages/vue-start/src/index.ts +++ b/packages/vue-start/src/index.ts @@ -1,5 +1,6 @@ export { useServerFn } from './useServerFn' export * from '@tanstack/start-client-core' +export type { StartModuleRequirements } from '@tanstack/start-client-core' // Explicit re-exports shadow `export *` above so these public-API names are // registered on the namespace at link time (via Vite SSR's `defineExport` // at fileStartIndex), surviving the cold-start SSR cycle through user diff --git a/packages/vue-start/src/route-module-internal.ts b/packages/vue-start/src/route-module-internal.ts new file mode 100644 index 0000000000..8642a07276 --- /dev/null +++ b/packages/vue-start/src/route-module-internal.ts @@ -0,0 +1 @@ +export { createStartModule } from '@tanstack/start-client-core/_internal/route-module' diff --git a/packages/vue-start/vite.config.ts b/packages/vue-start/vite.config.ts index dc421ef7ff..2edbb7d7b2 100644 --- a/packages/vue-start/vite.config.ts +++ b/packages/vue-start/vite.config.ts @@ -28,6 +28,7 @@ export default mergeConfig( exclude: ['./src/default-entry'], entry: [ './src/index.ts', + './src/route-module-internal.ts', './src/client.tsx', './src/client-rpc.ts', './src/ssr-rpc.ts', diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b20d885861..72b59ded82 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -40,8 +40,8 @@ catalogs: specifier: ^5.0.4 version: 5.0.4 chokidar: - specifier: ^5.0.0 - version: 5.0.0 + specifier: ^6.0.0 + version: 6.0.0 combinate: specifier: ^1.1.11 version: 1.1.11 @@ -1450,6 +1450,211 @@ importers: specifier: ^8.3.4 version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + e2e/react-router/route-modules: + devDependencies: + '@playwright/test': + specifier: ^1.63.0 + version: 1.63.0 + '@tanstack/router-e2e-utils': + specifier: workspace:^ + version: link:../../e2e-utils + '@tanstack/router-generator': + specifier: workspace:* + version: link:../../../packages/router-generator + '@types/node': + specifier: 25.0.9 + version: 25.0.9 + vite-plugin-solid: + specifier: ^2.11.11 + version: 2.11.11(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + vitest: + specifier: 'catalog:' + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + + e2e/react-router/route-modules/packages/account: + dependencies: + '@route-modules/products': + specifier: workspace:* + version: link:../products + '@tanstack/react-router': + specifier: workspace:* + version: link:../../../../../packages/react-router + react: + specifier: ^19.2.3 + version: 19.2.3 + devDependencies: + '@tanstack/router-cli': + specifier: workspace:* + version: link:../../../../../packages/router-cli + '@tanstack/router-core': + specifier: workspace:* + version: link:../../../../../packages/router-core + '@types/react': + specifier: ^19.2.8 + version: 19.2.9 + + e2e/react-router/route-modules/packages/billing: + dependencies: + '@route-modules/settings': + specifier: workspace:* + version: link:../settings + '@route-modules/team': + specifier: workspace:* + version: link:../team + '@tanstack/react-router': + specifier: workspace:* + version: link:../../../../../packages/react-router + react: + specifier: ^19.2.3 + version: 19.2.3 + devDependencies: + '@tanstack/router-cli': + specifier: workspace:* + version: link:../../../../../packages/router-cli + '@tanstack/router-core': + specifier: workspace:* + version: link:../../../../../packages/router-core + '@types/react': + specifier: ^19.2.8 + version: 19.2.9 + + e2e/react-router/route-modules/packages/products: + dependencies: + '@tanstack/react-router': + specifier: workspace:* + version: link:../../../../../packages/react-router + react: + specifier: ^19.2.3 + version: 19.2.3 + zod: + specifier: ^4.4.3 + version: 4.5.4 + devDependencies: + '@tanstack/router-cli': + specifier: workspace:* + version: link:../../../../../packages/router-cli + '@tanstack/router-core': + specifier: workspace:* + version: link:../../../../../packages/router-core + '@types/react': + specifier: ^19.2.8 + version: 19.2.9 + + e2e/react-router/route-modules/packages/settings: + dependencies: + '@tanstack/react-router': + specifier: workspace:* + version: link:../../../../../packages/react-router + react: + specifier: ^19.2.3 + version: 19.2.3 + devDependencies: + '@tanstack/router-cli': + specifier: workspace:* + version: link:../../../../../packages/router-cli + '@tanstack/router-core': + specifier: workspace:* + version: link:../../../../../packages/router-core + '@types/react': + specifier: ^19.2.8 + version: 19.2.9 + + e2e/react-router/route-modules/packages/storefront: + dependencies: + '@route-modules/products': + specifier: workspace:* + version: link:../products + '@tanstack/react-router': + specifier: workspace:* + version: link:../../../../../packages/react-router + react: + specifier: ^19.2.3 + version: 19.2.3 + devDependencies: + '@tanstack/router-cli': + specifier: workspace:* + version: link:../../../../../packages/router-cli + '@tanstack/router-core': + specifier: workspace:* + version: link:../../../../../packages/router-core + '@types/react': + specifier: ^19.2.8 + version: 19.2.9 + + e2e/react-router/route-modules/packages/team: + dependencies: + '@tanstack/react-router': + specifier: workspace:* + version: link:../../../../../packages/react-router + react: + specifier: ^19.2.3 + version: 19.2.3 + devDependencies: + '@tanstack/router-cli': + specifier: workspace:* + version: link:../../../../../packages/router-cli + '@tanstack/router-core': + specifier: workspace:* + version: link:../../../../../packages/router-core + '@types/react': + specifier: ^19.2.8 + version: 19.2.9 + + e2e/react-router/route-modules/packages/web: + dependencies: + '@route-modules/account': + specifier: workspace:* + version: link:../account + '@route-modules/billing': + specifier: workspace:* + version: link:../billing + '@route-modules/products': + specifier: workspace:* + version: link:../products + '@route-modules/settings': + specifier: workspace:* + version: link:../settings + '@route-modules/storefront': + specifier: workspace:* + version: link:../storefront + '@route-modules/team': + specifier: workspace:* + version: link:../team + '@tanstack/react-router': + specifier: workspace:* + version: link:../../../../../packages/react-router + '@tanstack/react-router-devtools': + specifier: workspace:^ + version: link:../../../../../packages/react-router-devtools + react: + specifier: ^19.2.3 + version: 19.2.3 + react-dom: + specifier: ^19.2.3 + version: 19.2.3(react@19.2.3) + devDependencies: + '@tanstack/router-cli': + specifier: workspace:* + version: link:../../../../../packages/router-cli + '@tanstack/router-plugin': + specifier: workspace:* + version: link:../../../../../packages/router-plugin + '@types/react': + specifier: ^19.2.8 + version: 19.2.9 + '@types/react-dom': + specifier: ^19.2.3 + version: 19.2.3(@types/react@19.2.9) + '@vitejs/plugin-react': + specifier: ^6.0.1 + version: 6.0.1(@rolldown/plugin-babel@0.2.3(@babel/core@7.29.7(supports-color@10.2.2))(rolldown@1.2.13)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)))(babel-plugin-react-compiler@1.0.0)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + vite: + specifier: ^8.3.4 + version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + vitest: + specifier: 'catalog:' + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + e2e/react-router/rspack-basic-file-based: dependencies: '@tanstack/react-router': @@ -3032,6 +3237,182 @@ importers: specifier: ^8.3.4 version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + e2e/react-start/route-modules: + devDependencies: + '@playwright/test': + specifier: ^1.63.0 + version: 1.63.0 + '@start-route-modules/web': + specifier: workspace:* + version: link:packages/web + '@tanstack/router-e2e-utils': + specifier: workspace:^ + version: link:../../e2e-utils + '@tanstack/router-generator': + specifier: workspace:* + version: link:../../../packages/router-generator + '@types/node': + specifier: 25.0.9 + version: 25.0.9 + vitest: + specifier: 'catalog:' + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + + e2e/react-start/route-modules/packages/catalog: + dependencies: + '@tanstack/react-router': + specifier: workspace:* + version: link:../../../../../packages/react-router + '@tanstack/react-start': + specifier: workspace:* + version: link:../../../../../packages/react-start + react: + specifier: ^19.2.3 + version: 19.2.3 + devDependencies: + '@tanstack/router-cli': + specifier: workspace:* + version: link:../../../../../packages/router-cli + '@tanstack/router-core': + specifier: workspace:* + version: link:../../../../../packages/router-core + '@tanstack/start-client-core': + specifier: workspace:* + version: link:../../../../../packages/start-client-core + '@types/react': + specifier: ^19.2.8 + version: 19.2.9 + + e2e/react-start/route-modules/packages/notes: + dependencies: + '@tanstack/react-router': + specifier: workspace:* + version: link:../../../../../packages/react-router + react: + specifier: ^19.2.3 + version: 19.2.3 + devDependencies: + '@tanstack/router-cli': + specifier: workspace:* + version: link:../../../../../packages/router-cli + '@tanstack/router-core': + specifier: workspace:* + version: link:../../../../../packages/router-core + '@types/react': + specifier: ^19.2.8 + version: 19.2.9 + + e2e/react-start/route-modules/packages/settings: + dependencies: + '@tanstack/react-router': + specifier: workspace:* + version: link:../../../../../packages/react-router + '@tanstack/react-start': + specifier: workspace:* + version: link:../../../../../packages/react-start + react: + specifier: ^19.2.3 + version: 19.2.3 + devDependencies: + '@tanstack/router-cli': + specifier: workspace:* + version: link:../../../../../packages/router-cli + '@tanstack/router-core': + specifier: workspace:* + version: link:../../../../../packages/router-core + '@tanstack/start-client-core': + specifier: workspace:* + version: link:../../../../../packages/start-client-core + '@types/react': + specifier: ^19.2.8 + version: 19.2.9 + + e2e/react-start/route-modules/packages/team: + dependencies: + '@start-route-modules/settings': + specifier: workspace:* + version: link:../settings + '@tanstack/react-router': + specifier: workspace:* + version: link:../../../../../packages/react-router + '@tanstack/react-start': + specifier: workspace:* + version: link:../../../../../packages/react-start + react: + specifier: ^19.2.3 + version: 19.2.3 + devDependencies: + '@tanstack/router-cli': + specifier: workspace:* + version: link:../../../../../packages/router-cli + '@tanstack/router-core': + specifier: workspace:* + version: link:../../../../../packages/router-core + '@tanstack/start-client-core': + specifier: workspace:* + version: link:../../../../../packages/start-client-core + '@types/react': + specifier: ^19.2.8 + version: 19.2.9 + + e2e/react-start/route-modules/packages/web: + dependencies: + '@start-route-modules/catalog': + specifier: workspace:* + version: link:../catalog + '@start-route-modules/notes': + specifier: workspace:* + version: link:../notes + '@start-route-modules/settings': + specifier: workspace:* + version: link:../settings + '@start-route-modules/team': + specifier: workspace:* + version: link:../team + '@tanstack/react-router': + specifier: workspace:* + version: link:../../../../../packages/react-router + '@tanstack/react-router-devtools': + specifier: workspace:^ + version: link:../../../../../packages/react-router-devtools + '@tanstack/react-start': + specifier: workspace:* + version: link:../../../../../packages/react-start + react: + specifier: ^19.2.3 + version: 19.2.3 + react-dom: + specifier: ^19.2.3 + version: 19.2.3(react@19.2.3) + devDependencies: + '@rsbuild/core': + specifier: ^2.1.0 + version: 2.2.5 + '@rsbuild/plugin-react': + specifier: ^2.0.0 + version: 2.0.0(@rsbuild/core@2.2.5)(@rspack/core@2.2.7(@swc/helpers@0.5.23)) + '@types/node': + specifier: 25.0.9 + version: 25.0.9 + '@types/react': + specifier: ^19.2.8 + version: 19.2.9 + '@types/react-dom': + specifier: ^19.2.3 + version: 19.2.3(@types/react@19.2.9) + '@typescript/native': + specifier: npm:typescript@^7.0.2 + version: typescript@7.0.2 + '@vitejs/plugin-react': + specifier: ^6.0.1 + version: 6.0.1(@rolldown/plugin-babel@0.2.3(@babel/core@7.29.7(supports-color@10.2.2))(rolldown@1.2.13)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)))(babel-plugin-react-compiler@1.0.0)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + srvx: + specifier: ^1.0.0 + version: 1.0.5 + vite: + specifier: ^8.3.4 + version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + e2e/react-start/rsbuild: dependencies: '@tanstack/react-router': @@ -4688,6 +5069,65 @@ importers: specifier: ^2.11.11 version: 2.11.11(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + e2e/solid-router/route-modules: + dependencies: + '@route-modules/solid-settings': + specifier: workspace:* + version: link:packages/settings + '@tanstack/solid-router': + specifier: workspace:^ + version: link:../../../packages/solid-router + solid-js: + specifier: 1.9.12 + version: 1.9.12 + devDependencies: + '@playwright/test': + specifier: ^1.63.0 + version: 1.63.0 + '@tanstack/router-cli': + specifier: workspace:* + version: link:../../../packages/router-cli + '@tanstack/router-core': + specifier: workspace:* + version: link:../../../packages/router-core + '@tanstack/router-e2e-utils': + specifier: workspace:^ + version: link:../../e2e-utils + '@tanstack/router-generator': + specifier: workspace:* + version: link:../../../packages/router-generator + '@tanstack/router-plugin': + specifier: workspace:* + version: link:../../../packages/router-plugin + '@types/node': + specifier: 25.0.9 + version: 25.0.9 + vite: + specifier: ^8.3.4 + version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + vite-plugin-solid: + specifier: ^2.11.11 + version: 2.11.11(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + vitest: + specifier: 'catalog:' + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + + e2e/solid-router/route-modules/packages/settings: + dependencies: + '@tanstack/solid-router': + specifier: workspace:^ + version: link:../../../../../packages/solid-router + solid-js: + specifier: 1.9.12 + version: 1.9.12 + devDependencies: + '@tanstack/router-cli': + specifier: workspace:* + version: link:../../../../../packages/router-cli + '@tanstack/router-core': + specifier: workspace:* + version: link:../../../../../packages/router-core + e2e/solid-router/rspack-basic-file-based: dependencies: '@tanstack/solid-router': @@ -6677,6 +7117,65 @@ importers: specifier: ^8.3.4 version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + e2e/vue-router/route-modules: + dependencies: + '@route-modules/vue-settings': + specifier: workspace:* + version: link:packages/settings + '@tanstack/vue-router': + specifier: workspace:* + version: link:../../../packages/vue-router + vue: + specifier: ^3.5.16 + version: 3.5.25(typescript@6.0.2) + devDependencies: + '@playwright/test': + specifier: ^1.63.0 + version: 1.63.0 + '@tanstack/router-cli': + specifier: workspace:* + version: link:../../../packages/router-cli + '@tanstack/router-core': + specifier: workspace:* + version: link:../../../packages/router-core + '@tanstack/router-e2e-utils': + specifier: workspace:^ + version: link:../../e2e-utils + '@tanstack/router-generator': + specifier: workspace:* + version: link:../../../packages/router-generator + '@tanstack/router-plugin': + specifier: workspace:* + version: link:../../../packages/router-plugin + '@types/node': + specifier: 25.0.9 + version: 25.0.9 + '@vitejs/plugin-vue-jsx': + specifier: ^5.1.5 + version: 5.1.5(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vue@3.5.25(typescript@6.0.2)) + vite: + specifier: ^8.3.4 + version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + vitest: + specifier: 'catalog:' + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + + e2e/vue-router/route-modules/packages/settings: + dependencies: + '@tanstack/vue-router': + specifier: workspace:* + version: link:../../../../../packages/vue-router + vue: + specifier: ^3.5.16 + version: 3.5.25(typescript@6.0.2) + devDependencies: + '@tanstack/router-cli': + specifier: workspace:* + version: link:../../../../../packages/router-cli + '@tanstack/router-core': + specifier: workspace:* + version: link:../../../../../packages/router-core + e2e/vue-router/rspack-basic-file-based: dependencies: '@tanstack/vue-router': @@ -10846,6 +11345,61 @@ importers: specifier: ^8.3.4 version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + examples/react/start-large-route-modules: + dependencies: + '@tanstack/react-router': + specifier: workspace:* + version: link:../../../packages/react-router + '@tanstack/react-start': + specifier: workspace:* + version: link:../../../packages/react-start + react: + specifier: ^19.2.3 + version: 19.2.3 + react-dom: + specifier: ^19.2.3 + version: 19.2.3(react@19.2.3) + devDependencies: + '@rsbuild/core': + specifier: ^2.1.0 + version: 2.2.5 + '@rsbuild/plugin-react': + specifier: ^2.0.0 + version: 2.0.0(@rsbuild/core@2.2.5)(@rspack/core@2.2.7(@swc/helpers@0.5.23)) + '@tanstack/router-core': + specifier: workspace:* + version: link:../../../packages/router-core + '@tanstack/router-generator': + specifier: workspace:* + version: link:../../../packages/router-generator + '@tanstack/start-client-core': + specifier: workspace:* + version: link:../../../packages/start-client-core + '@types/node': + specifier: 25.0.9 + version: 25.0.9 + '@types/react': + specifier: ^19.2.8 + version: 19.2.9 + '@types/react-dom': + specifier: ^19.2.3 + version: 19.2.3(@types/react@19.2.9) + '@typescript/native': + specifier: npm:typescript@^7.0.2 + version: typescript@7.0.2 + '@vitejs/plugin-react': + specifier: ^6.0.1 + version: 6.0.1(@rolldown/plugin-babel@0.2.3(@babel/core@7.29.7(supports-color@10.2.2))(rolldown@1.2.13)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)))(babel-plugin-react-compiler@1.0.0)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + srvx: + specifier: ^1.0.0 + version: 1.0.5 + typescript: + specifier: npm:@typescript/typescript6@^6.0.2 + version: '@typescript/typescript6@6.0.2' + vite: + specifier: ^8.3.4 + version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + examples/react/start-material-ui: dependencies: '@emotion/cache': @@ -14495,7 +15049,7 @@ importers: version: 7.1.0 chokidar: specifier: 'catalog:' - version: 5.0.0 + version: 6.0.0 devDependencies: '@arethetypeswrong/cli': specifier: 'catalog:' @@ -14746,7 +15300,7 @@ importers: version: link:../router-utils chokidar: specifier: 'catalog:' - version: 5.0.0 + version: 6.0.0 unplugin: specifier: ^3.3.0 version: 3.3.0(@rspack/core@2.2.7(@swc/helpers@0.5.23))(esbuild@0.28.2)(rolldown@1.2.13)(rollup@4.63.1)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(webpack@5.110.3) @@ -23485,6 +24039,10 @@ packages: resolution: {integrity: sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==} engines: {node: '>= 20.19.0'} + chokidar@6.0.0: + resolution: {integrity: sha512-Ec2Z7wpcKBiMpR7DxteoqS/sq5G5d2A4fpxzPv6+fD7xNNdrTghn7L11YwV5EN1B3i72Erc3XVT5FkWIDx90+A==} + engines: {node: '>= 22.22'} + chownr@3.0.0: resolution: {integrity: sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==} engines: {node: '>=18'} @@ -27360,6 +27918,10 @@ packages: resolution: {integrity: sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ==} engines: {node: '>= 20.19.0'} + readdirp@5.1.1: + resolution: {integrity: sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==} + engines: {node: '>= 20.19.0'} + real-require@0.2.0: resolution: {integrity: sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==} engines: {node: '>= 12.13.0'} @@ -35894,7 +36456,7 @@ snapshots: '@typescript-eslint/utils': 8.57.1(@typescript/typescript6@6.0.2)(eslint@9.22.0(jiti@2.7.0)(supports-color@7.2.0))(supports-color@10.2.2) '@typescript-eslint/visitor-keys': 8.57.1 eslint: 9.22.0(jiti@2.7.0)(supports-color@7.2.0) - ignore: 7.0.5 + ignore: 7.0.12 natural-compare: 1.4.0 ts-api-utils: 2.4.0(@typescript/typescript6@6.0.2) typescript: '@typescript/typescript6@6.0.2' @@ -36561,6 +37123,18 @@ snapshots: transitivePeerDependencies: - supports-color + '@vitejs/plugin-vue-jsx@5.1.5(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vue@3.5.25(typescript@6.0.2))': + dependencies: + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/plugin-syntax-typescript': 7.28.6(@babel/core@7.29.7(supports-color@10.2.2)) + '@babel/plugin-transform-typescript': 7.28.6(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@rolldown/pluginutils': 1.0.0-rc.9 + '@vue/babel-plugin-jsx': 2.0.1(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + vite: 8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + vue: 3.5.25(typescript@6.0.2) + transitivePeerDependencies: + - supports-color + '@vitejs/plugin-vue-jsx@5.1.5(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vue@3.5.25(@typescript/typescript6@6.0.2))': dependencies: '@babel/core': 7.29.7(supports-color@10.2.2) @@ -36693,6 +37267,16 @@ snapshots: msw: 2.15.0(@types/node@25.0.9)(typescript@5.9.2) vite: 8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + '@vitest/mocker@5.0.4(msw@2.15.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))': + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + '@vitest/spy': 5.0.4 + estree-walker: 3.0.3 + magic-string: 1.4.3 + optionalDependencies: + msw: 2.15.0(@types/node@25.0.9)(typescript@6.0.2) + vite: 8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + '@vitest/pretty-format@4.1.4': dependencies: tinyrainbow: 3.2.0 @@ -36973,6 +37557,12 @@ snapshots: '@vue/shared': 3.5.25 vue: 3.5.25(typescript@5.9.3) + '@vue/server-renderer@3.5.25(vue@3.5.25(typescript@6.0.2))': + dependencies: + '@vue/compiler-ssr': 3.5.25 + '@vue/shared': 3.5.25 + vue: 3.5.25(typescript@6.0.2) + '@vue/server-renderer@3.5.25(vue@3.5.25(typescript@7.0.2))': dependencies: '@vue/compiler-ssr': 3.5.25 @@ -37831,6 +38421,10 @@ snapshots: dependencies: readdirp: 5.0.0 + chokidar@6.0.0: + dependencies: + readdirp: 5.1.1 + chownr@3.0.0: {} chrome-trace-event@1.0.4: {} @@ -41096,6 +41690,32 @@ snapshots: - '@types/node' optional: true + msw@2.15.0(@types/node@25.0.9)(typescript@6.0.2): + dependencies: + '@inquirer/confirm': 6.3.2(@types/node@25.0.9) + '@mswjs/interceptors': 0.41.9 + '@open-draft/deferred-promise': 3.0.0 + '@types/statuses': 2.0.6 + cookie: 1.1.1 + graphql: 16.14.2 + headers-polyfill: 5.0.1 + is-node-process: 1.2.0 + outvariant: 1.4.3 + path-to-regexp: 6.3.0 + picocolors: 1.1.1 + rettime: 0.11.11 + statuses: 2.0.2 + strict-event-emitter: 0.5.1 + tough-cookie: 6.0.1 + type-fest: 5.9.0 + until-async: 3.0.2 + yargs: 17.7.2 + optionalDependencies: + typescript: 6.0.2 + transitivePeerDependencies: + - '@types/node' + optional: true + msw@2.7.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2): dependencies: '@bundled-es-modules/cookie': 2.0.1 @@ -42303,6 +42923,8 @@ snapshots: readdirp@5.0.0: {} + readdirp@5.1.1: {} + real-require@0.2.0: {} rechoir@0.8.0: @@ -43892,6 +44514,21 @@ snapshots: transitivePeerDependencies: - supports-color + vite-plugin-solid@2.11.11(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): + dependencies: + '@babel/core': 7.29.7(supports-color@10.2.2) + '@types/babel__core': 7.20.5 + babel-preset-solid: 1.9.10(@babel/core@7.29.7(supports-color@10.2.2))(solid-js@1.9.12) + merge-anything: 5.1.7 + solid-js: 1.9.12 + solid-refresh: 0.6.3(solid-js@1.9.12)(supports-color@10.2.2) + vite: 8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + vitefu: 1.1.1(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + optionalDependencies: + '@testing-library/jest-dom': 6.6.3 + transitivePeerDependencies: + - supports-color + vite-plugin-solid@2.11.11(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): dependencies: '@babel/core': 7.29.7(supports-color@10.2.2) @@ -44016,6 +44653,10 @@ snapshots: tsx: 4.20.3 yaml: 2.9.0 + vitefu@1.1.1(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): + optionalDependencies: + vite: 8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + vitefu@1.1.1(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): optionalDependencies: vite: 8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) @@ -44203,6 +44844,30 @@ snapshots: transitivePeerDependencies: - msw + vitest@5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@29.1.1(@noble/hashes@2.0.1))(msw@2.15.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): + dependencies: + '@types/chai': 5.2.2 + '@vitest/mocker': 5.0.4(msw@2.15.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + chai: 6.3.0 + es-module-lexer: 2.3.2 + expect-type: 1.4.0 + magic-string: 1.4.3 + obug: 3.0.0 + picomatch: 4.0.7 + std-env: 4.3.0 + tinybench: 6.2.2 + tinyexec: 1.3.1 + tinyglobby: 0.2.17 + vite: 8.3.4(@types/node@25.0.9)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + why-is-node-running: 3.2.1 + optionalDependencies: + '@opentelemetry/api': 1.9.1 + '@types/node': 25.0.9 + '@vitest/ui': 5.0.4(vitest@5.0.4) + jsdom: 29.1.1(@noble/hashes@2.0.1) + transitivePeerDependencies: + - msw + vscode-uri@3.0.8: {} vue-component-type-helpers@2.2.12: {} @@ -44304,6 +44969,16 @@ snapshots: optionalDependencies: typescript: 5.9.3 + vue@3.5.25(typescript@6.0.2): + dependencies: + '@vue/compiler-dom': 3.5.25 + '@vue/compiler-sfc': 3.5.25 + '@vue/runtime-dom': 3.5.25 + '@vue/server-renderer': 3.5.25(vue@3.5.25(typescript@6.0.2)) + '@vue/shared': 3.5.25 + optionalDependencies: + typescript: 6.0.2 + vue@3.5.25(typescript@7.0.2): dependencies: '@vue/compiler-dom': 3.5.25 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 8f33a49d50..4a80ff6e40 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -6,7 +6,7 @@ blockExoticSubdeps: true trustPolicy: 'no-downgrade' trustPolicyExclude: - - 'chokidar@4.0.3' # known to be safe, installed by sass, prisma, netlify... no planned releases in v4, packages is on v5 now + - 'chokidar@4.0.3' # known to be safe, installed by sass, prisma, netlify... no planned releases in v4, package is on v6 now - 'semver@6.3.1' # installed by babel, ecosystem has been on v7 for 7 years now, but babel is horribly out of date, 6.3.1 is the latest v6 and was released 3 years ago - 'undici@6.21.2' # installed by cheerio@1.0.0 -> html-link-extractor@1.0.5 -> markdown-link-extractor@4.0.3, is only 1 year old, v6, v7 and v8 are maintained in parallel - '@platformatic/flame@1.7.0' # trusted publishing failed due to a missing sigstore module in npm, then an established maintainer published it manually @@ -24,9 +24,13 @@ packages: - 'examples/react/router-monorepo-simple-lazy/packages/*' - 'e2e/e2e-utils' - 'e2e/react-router/*' + - 'e2e/react-router/route-modules/packages/*' - 'e2e/solid-router/*' + - 'e2e/solid-router/route-modules/packages/*' - 'e2e/vue-router/*' + - 'e2e/vue-router/route-modules/packages/*' - 'e2e/react-start/*' + - 'e2e/react-start/route-modules/packages/*' - 'e2e/solid-start/*' - 'e2e/vue-start/*' - 'e2e/eslint-plugin-start' @@ -49,7 +53,7 @@ catalog: '@types/react-dom': ^19.2.3 eslint: ^9.22.0 eslint-plugin-react-hooks: ^5.1.0 - chokidar: ^5.0.0 + chokidar: ^6.0.0 combinate: ^1.1.11 isbot: ^5.1.22 jsdom: ^25.0.1 diff --git a/scripts/benchmarks/route-modules/measure.mjs b/scripts/benchmarks/route-modules/measure.mjs new file mode 100644 index 0000000000..15f915dc53 --- /dev/null +++ b/scripts/benchmarks/route-modules/measure.mjs @@ -0,0 +1,586 @@ +// Measures route modules against a single application with the same routes +// (CONCEPT.md §8): generation, declaration emit and type-check cost, the +// consumer program size, and incremental behaviour after an implementation +// change and after a contract change. +// +// Usage: node scripts/benchmarks/route-modules/measure.mjs [modules] [groups] +// Each module has `groups * 3 + 1` routes (static, search, param, index). +import crypto from 'node:crypto' +import { spawnSync } from 'node:child_process' +import { + existsSync, + mkdirSync, + readFileSync, + readdirSync, + realpathSync, + rmSync, + statSync, + symlinkSync, + writeFileSync, +} from 'node:fs' +import { createRequire } from 'node:module' +import os from 'node:os' +import path from 'node:path' +import { fileURLToPath, pathToFileURL } from 'node:url' +import { performance } from 'node:perf_hooks' + +const moduleCount = Number(process.argv[2] ?? 10) +const groups = Number(process.argv[3] ?? 10) + +const repoRoot = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../../..', +) +const tsc = path.join(repoRoot, 'node_modules', '.bin', 'tsc') +// The router fixture resolves the generator and the runtime packages. +const fixture = path.join(repoRoot, 'e2e/react-router/route-modules') +const fixturePackage = path.join(fixture, 'packages/products') +const generatorEntry = createRequire( + path.join(fixture, 'package.json'), +).resolve('@tanstack/router-generator') +const { Generator, getConfig } = await import( + pathToFileURL(generatorEntry).href +) +const external = [ + '@tanstack/react-router', + '@tanstack/router-core', + 'react', + '@types/react', +] + +const workspace = realpathSync( + (() => { + const dir = path.join( + os.tmpdir(), + `route-modules-measure-${crypto.randomBytes(4).toString('hex')}`, + ) + mkdirSync(dir, { recursive: true }) + return dir + })(), +) + +const tsconfig = { + compilerOptions: { + strict: true, + jsx: 'react-jsx', + target: 'ESNext', + module: 'ESNext', + moduleResolution: 'Bundler', + lib: ['DOM', 'DOM.Iterable', 'ES2022'], + skipLibCheck: true, + noEmit: true, + types: [], + }, + include: ['src'], +} +const routeTypesTsconfig = { + extends: './tsconfig.json', + compilerOptions: { + noEmit: false, + declaration: true, + emitDeclarationOnly: true, + noEmitOnError: true, + declarationMap: true, + rootDir: '.', + outDir: '.tanstack/types', + }, + include: ['src'], +} + +function write(file, content) { + mkdirSync(path.dirname(file), { recursive: true }) + writeFileSync( + file, + typeof content === 'string' ? content : JSON.stringify(content, null, 2), + ) +} + +function writePackage(root, packageJson, dependencies) { + write(path.join(root, 'package.json'), packageJson) + write(path.join(root, 'tsconfig.json'), tsconfig) + for (const dependency of external) { + const link = path.join(root, 'node_modules', dependency) + mkdirSync(path.dirname(link), { recursive: true }) + symlinkSync( + realpathSync(path.join(fixturePackage, 'node_modules', dependency)), + link, + 'dir', + ) + } + for (const [name, target] of dependencies) { + const link = path.join(root, 'node_modules', name) + mkdirSync(path.dirname(link), { recursive: true }) + symlinkSync(target, link, 'dir') + } +} + +const searchValidator = `(search: Record) => ({ + page: Number(search.page ?? 0), + q: String(search.q ?? ''), + })` + +/** + * The routes of one feature. `api` names the routing APIs: module routes use + * the scope and module-local paths, application routes use the framework and + * prefixed paths. `other` addresses the previous feature. + */ +function featureRoutes({ id, prefix, scopeImport, otherLink }) { + const files = {} + const route = (file, routePath, body, extraImports = '') => { + const depth = file.split('/').length - 1 + const scope = scopeImport(depth) + files[file] = `${scope}${extraImports} +export const Route = createFileRoute('${id(routePath)}')(${body}) +` + } + route( + 'index.tsx', + '/', + `{ + component: () => First item, +}`, + ) + for (let i = 0; i < groups; i++) { + const next = (i + 1) % groups + route( + `item${i}.tsx`, + `/item${i}`, + `{ + component: () => ( + + ), +})`.replace(/\)$/, ''), + ) + route( + `search${i}.tsx`, + `/search${i}`, + `{ + validateSearch: ${searchValidator}, + loader: () => ({ results: [{ id: 'r${i}', score: ${i} }] }), + component: () => { + const { page, q } = Route.useSearch() + const { results } = Route.useLoaderData() + return ( + + {q}:{page} + + ) + }, +}`, + ) + route( + `params${i}/$id.tsx`, + `/params${i}/$id`, + `{ + loader: ({ params }) => ({ id: params.id, label: 'item ' + params.id }), + component: () => { + const { label } = Route.useLoaderData() + return ( + + Back + + ) + }, +}`, + ) + } + return files +} + +function moduleName(k) { + return `@bench/m${k}` +} + +/** A single application with every feature under `/f`. */ +function writeSingleApp(root) { + writePackage(root, { name: '@bench/single', type: 'module' }, []) + write( + path.join(root, 'src/routes/__root.tsx'), + `import { Outlet, createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute({ component: () => }) +`, + ) + write( + path.join(root, 'src/routes/index.tsx'), + `import { Link, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: () => ( + + ), +}) +`, + ) + for (let k = 0; k < moduleCount; k++) { + const files = featureRoutes({ + id: (routePath) => `/f${k}${routePath === '/' ? '/' : routePath}`, + prefix: `/f${k}`, + scopeImport: () => + `import { Link, createFileRoute } from '@tanstack/react-router'\n`, + otherLink: (i) => + k > 0 + ? `Other` + : '', + }) + for (const [file, content] of Object.entries(files)) { + write(path.join(root, 'src/routes', `f${k}`, file), content) + } + } +} + +/** The same features as route modules; module `k` uses module `k - 1`. */ +function writeModules() { + const roots = [] + for (let k = 0; k < moduleCount; k++) { + const root = path.join(workspace, 'modular', `m${k}`) + roots.push(root) + const dependencies = k > 0 ? [[moduleName(k - 1), roots[k - 1]]] : [] + writePackage( + root, + { + name: moduleName(k), + type: 'module', + tanstack: { + router: { module: { uses: dependencies.map(([name]) => name) } }, + }, + exports: { + './route-types': { + types: './.tanstack/types/src/routeContract.gen.d.ts', + }, + './route-module': { + types: './.tanstack/types/src/routeModule.gen.d.ts', + default: './src/routeModule.gen.ts', + }, + './package.json': './package.json', + }, + dependencies: Object.fromEntries( + [...external, ...dependencies.map(([name]) => name)].map((name) => [ + name, + '*', + ]), + ), + }, + dependencies, + ) + write(path.join(root, 'tsconfig.route-types.json'), routeTypesTsconfig) + write( + path.join(root, 'src/routes/__root.tsx'), + `import { Outlet } from '@tanstack/react-router' +import { createModuleRoot } from '../routeScope.gen' + +export const Route = createModuleRoot()({ component: () => }) +`, + ) + const files = featureRoutes({ + id: (routePath) => `${moduleName(k)}:${routePath}`, + prefix: '', + scopeImport: (depth) => { + const scope = `${'../'.repeat(depth + 1)}routeScope.gen` + return k > 0 + ? `import { createFileRoute, m${k - 1} } from '${scope}'\n` + : `import { createFileRoute } from '${scope}'\n` + }, + otherLink: (i) => + k > 0 + ? `Other` + : '', + }) + for (const [file, content] of Object.entries(files)) { + write(path.join(root, 'src/routes', file), content) + } + } + + const app = path.join(workspace, 'modular', 'app') + writePackage( + app, + { + name: '@bench/app', + type: 'module', + dependencies: Object.fromEntries( + roots.map((_, k) => [moduleName(k), '*']), + ), + }, + roots.map((root, k) => [moduleName(k), root]), + ) + write( + path.join(app, 'src/routes/__root.tsx'), + `import { Outlet, createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute({ component: () => }) +`, + ) + write( + path.join(app, 'src/routes/index.tsx'), + `import { createFileRoute } from '@tanstack/react-router' +import { ${roots.map((_, k) => `m${k}`).join(', ')} } from '../routeScope.gen' + +export const Route = createFileRoute('/')({ + component: () => ( + + ), +}) +`, + ) + return { roots, app } +} + +const appRouteModules = { + includes: Array.from({ length: moduleCount }, (_, k) => ({ + module: moduleName(k), + at: `/f${k}`, + })), +} + +async function generate(root, routeModules) { + const config = getConfig( + { + disableLogging: true, + tmpDir: path.join(workspace, '.tmp'), + routesDirectory: './src/routes', + generatedRouteTree: './src/routeTree.gen.ts', + ...(routeModules ? { routeModules } : {}), + }, + root, + ) + await new Generator({ config, root }).run() +} + +async function timed(fn) { + const start = performance.now() + const result = await fn() + return { ms: performance.now() - start, result } +} + +/** `tsc --noEmit --extendedDiagnostics` in `root`. */ +function typeCheck(root) { + const start = performance.now() + const result = spawnSync( + tsc, + ['-p', 'tsconfig.json', '--noEmit', '--extendedDiagnostics'], + { cwd: root, encoding: 'utf8' }, + ) + const ms = performance.now() - start + if (result.status !== 0) { + throw new Error(`tsc failed in ${root}:\n${result.stdout}${result.stderr}`) + } + const metric = (name) => { + const match = new RegExp(`^${name}:\\s+([\\d.,]+)`, 'm').exec(result.stdout) + return match ? Number(match[1].replace(/,/g, '')) : undefined + } + const memory = /^Memory used:\s+([\d.,]+)K/m.exec(result.stdout) + return { + ms, + files: metric('Files'), + lines: metric('Lines'), + types: metric('Types'), + instantiations: metric('Instantiations'), + memoryMB: memory + ? Math.round(Number(memory[1].replace(/,/g, '')) / 1024) + : undefined, + checkSeconds: metric('Check time'), + } +} + +function declarationSnapshot(dir) { + const declarations = new Map() + const walk = (current) => { + for (const entry of readdirSync(current)) { + const full = path.join(current, entry) + const stat = statSync(full) + if (stat.isDirectory()) { + walk(full) + } else if (/\.d\.(?:ts|mts|cts)$/.test(full)) { + declarations.set(path.relative(dir, full), readFileSync(full)) + } + } + } + if (existsSync(dir)) { + walk(dir) + } + return declarations +} + +function declarationChanges(before, after) { + let changed = 0 + for (const file of new Set([...before.keys(), ...after.keys()])) { + const previous = before.get(file) + const current = after.get(file) + if (!previous || !current || !previous.equals(current)) { + changed++ + } + } + return changed +} + +// The workload owns its declaration build just like an ordinary package does. +function emitTypes(root) { + const outDir = path.join(root, routeTypesTsconfig.compilerOptions.outDir) + rmSync(outDir, { recursive: true, force: true }) + const result = spawnSync( + tsc, + ['-p', 'tsconfig.route-types.json', '--pretty', 'false'], + { + cwd: root, + encoding: 'utf8', + }, + ) + if (result.error) { + throw result.error + } + if (result.status !== 0) { + throw new Error( + `Declaration build failed in ${root}:\n${result.stdout}${result.stderr}`, + ) + } +} + +function format(ms) { + return `${(ms / 1000).toFixed(2)} s` +} + +const routesPerFeature = groups * 3 + 1 +const compilerVersion = spawnSync(tsc, ['--version'], { encoding: 'utf8' }) +const revision = spawnSync('git', ['rev-parse', 'HEAD'], { + cwd: repoRoot, + encoding: 'utf8', +}) +console.log( + `Environment: Node ${process.version}; ${compilerVersion.stdout.trim()}; revision ${revision.status === 0 ? revision.stdout.trim() : 'unavailable'}`, +) +console.log( + `Workload: ${moduleCount} features x ${routesPerFeature} routes = ${moduleCount * routesPerFeature} routes (+ app root and index)`, +) + +// Single application. +const single = path.join(workspace, 'single') +writeSingleApp(single) +const singleGenerate = await timed(() => generate(single)) +const singleCheck = typeCheck(single) + +// Route modules, in dependency order, as a task runner would run them. +const { roots, app } = writeModules() +let modulesGenerateMs = 0 +let modulesEmitMs = 0 +for (const root of roots) { + modulesGenerateMs += (await timed(() => generate(root))).ms + const emitted = await timed(() => emitTypes(root)) + modulesEmitMs += emitted.ms +} +const appGenerate = await timed(() => generate(app, appRouteModules)) +const appCheck = typeCheck(app) +const moduleChecks = roots.map((root) => typeCheck(root)) +const declarations = roots + .map((root) => { + const files = declarationSnapshot( + path.join(root, routeTypesTsconfig.compilerOptions.outDir), + ) + return { + files: files.size, + bytes: [...files.values()].reduce( + (sum, content) => sum + content.length, + 0, + ), + } + }) + .reduce((a, b) => ({ files: a.files + b.files, bytes: a.bytes + b.bytes })) + +// Incremental: an implementation-only change in the first module. +const first = roots[0] +const firstOutDir = path.join(first, routeTypesTsconfig.compilerOptions.outDir) +const coldDeclarations = declarationSnapshot(firstOutDir) +const itemFile = path.join(first, 'src/routes/item0.tsx') +writeFileSync( + itemFile, + readFileSync(itemFile, 'utf8').replace('>Next<', '>Next item<'), +) +const implementationEmit = await timed(() => emitTypes(first)) +const implementationDeclarations = declarationSnapshot(firstOutDir) +const implementationChanges = declarationChanges( + coldDeclarations, + implementationDeclarations, +) + +// Incremental: a contract change (a new optional search param) in the first +// module. +const searchFile = path.join(first, 'src/routes/search0.tsx') +writeFileSync( + searchFile, + readFileSync(searchFile, 'utf8').replace( + "q: String(search.q ?? ''),", + "q: String(search.q ?? ''),\n ...(search.sort ? { sort: String(search.sort) } : {}),", + ), +) +const contractGenerate = await timed(() => generate(first)) +const contractEmit = await timed(() => emitTypes(first)) +const contractChanges = declarationChanges( + implementationDeclarations, + declarationSnapshot(firstOutDir), +) +const dependentCheck = typeCheck(roots[1]) +const contractAppCheck = typeCheck(app) + +const rows = [ + [ + 'Generate (cold)', + format(singleGenerate.ms), + `${format(modulesGenerateMs + appGenerate.ms)} (modules ${format(modulesGenerateMs)}, app ${format(appGenerate.ms)})`, + ], + ['Emit declarations (cold)', '-', format(modulesEmitMs)], + ['Application type check', format(singleCheck.ms), format(appCheck.ms)], + ['Application program files', singleCheck.files, appCheck.files], + ['Application program lines', singleCheck.lines, appCheck.lines], + ['Application types', singleCheck.types, appCheck.types], + [ + 'Application instantiations', + singleCheck.instantiations, + appCheck.instantiations, + ], + ['Application memory (MB)', singleCheck.memoryMB, appCheck.memoryMB], + [ + 'Module type checks (sum)', + '-', + format(moduleChecks.reduce((sum, check) => sum + check.ms, 0)), + ], + [ + 'Largest module program files', + '-', + Math.max(...moduleChecks.map((check) => check.files ?? 0)), + ], + [ + 'Declaration files / size', + '-', + `${declarations.files} / ${Math.round(declarations.bytes / 1024)} KiB`, + ], + [ + 'Implementation change: emit', + '-', + `${format(implementationEmit.ms)}, ${implementationChanges} declarations changed`, + ], + [ + 'Contract change: generate + emit', + '-', + `${format(contractGenerate.ms + contractEmit.ms)}, ${contractChanges} declarations changed`, + ], + ['Contract change: dependent module check', '-', format(dependentCheck.ms)], + ['Contract change: application check', '-', format(contractAppCheck.ms)], +] + +console.log('\n| Metric | Single application | Route modules |') +console.log('| --- | --- | --- |') +for (const [metric, singleValue, modularValue] of rows) { + console.log(`| ${metric} | ${singleValue} | ${modularValue} |`) +} + +if (process.env.KEEP) { + console.log(workspace) +} else { + rmSync(workspace, { recursive: true, force: true }) +} diff --git a/scripts/benchmarks/route-modules/measure.test.mjs b/scripts/benchmarks/route-modules/measure.test.mjs new file mode 100644 index 0000000000..e1003f302a --- /dev/null +++ b/scripts/benchmarks/route-modules/measure.test.mjs @@ -0,0 +1,32 @@ +import assert from 'node:assert/strict' +import { spawnSync } from 'node:child_process' +import path from 'node:path' +import { test } from 'node:test' +import { fileURLToPath } from 'node:url' + +const script = fileURLToPath(new URL('./measure.mjs', import.meta.url)) +const root = path.resolve(path.dirname(script), '../../..') + +test('the benchmark measures declaration changes for implementation and contract edits', () => { + const result = spawnSync(process.execPath, [script, '2', '1'], { + cwd: root, + encoding: 'utf8', + timeout: 120_000, + maxBuffer: 8 * 1024 * 1024, + }) + const output = `${result.stdout}${result.stderr}` + assert.equal(result.error, undefined, output) + assert.equal(result.status, 0, output) + + const implementation = + /Implementation change: emit[^\n]*, (\d+) declarations changed/.exec(output) + assert.ok(implementation, output) + assert.equal(Number(implementation[1]), 0, output) + + const contract = + /Contract change: generate \+ emit[^\n]*, (\d+) declarations changed/.exec( + output, + ) + assert.ok(contract, output) + assert.ok(Number(contract[1]) > 0, output) +}) diff --git a/scripts/benchmarks/route-modules/scoped-match.mjs b/scripts/benchmarks/route-modules/scoped-match.mjs new file mode 100644 index 0000000000..9e420ce417 --- /dev/null +++ b/scripts/benchmarks/route-modules/scoped-match.mjs @@ -0,0 +1,241 @@ +import assert from 'node:assert/strict' +import fs from 'node:fs/promises' +import os from 'node:os' +import path from 'node:path' +import { createRequire } from 'node:module' +import { performance } from 'node:perf_hooks' +import { realpathSync } from 'node:fs' + +// Run only after building router-generator and react-router through Nx. +// Usage: node scripts/benchmarks/route-modules/scoped-match.mjs +// This is a focused CPU probe, not a heap-retention or individual-call-tail test. +const repository = path.resolve(process.argv[2] ?? process.cwd()) +const requireGenerator = createRequire( + path.join(repository, 'packages/router-generator/package.json'), +) +const { Generator, getConfig } = requireGenerator('@tanstack/router-generator') +const { createJiti } = requireGenerator('jiti') +const workspace = realpathSync( + await fs.mkdtemp(path.join(os.tmpdir(), 'route-module-guard-benchmark-')), +) + +async function write(file, content) { + await fs.mkdir(path.dirname(file), { recursive: true }) + await fs.writeFile(file, content) +} + +async function link(root, name, target) { + const destination = path.join(root, 'node_modules', name) + await fs.mkdir(path.dirname(destination), { recursive: true }) + await fs.symlink(target, destination, 'dir') +} + +async function fixture(routeCount) { + const directory = path.join(workspace, String(routeCount)) + const provider = path.join(directory, 'provider') + const host = path.join(directory, 'host') + const moduleId = `@guard/provider-${routeCount}` + for (const root of [provider, host]) { + await write( + path.join(root, 'package.json'), + JSON.stringify({ + name: root === provider ? moduleId : `@guard/host-${routeCount}`, + type: 'module', + dependencies: { + '@tanstack/react-router': '*', + ...(root === host ? { [moduleId]: '*' } : {}), + }, + ...(root === provider + ? { + tanstack: { router: { module: true } }, + exports: { + './route-module': './src/routeModule.gen.ts', + './route-types': './src/routeContract.gen.ts', + }, + } + : {}), + }), + ) + await link( + root, + '@tanstack/react-router', + path.join(repository, 'packages/react-router'), + ) + } + await link(host, moduleId, provider) + await write( + path.join(provider, 'src/routes/__root.tsx'), + `import { createModuleRoot } from '../routeScope.gen' +export const Route = createModuleRoot()({})`, + ) + for (let index = 0; index < routeCount; index++) { + const segment = `p${String(index).padStart(4, '0')}` + await write( + path.join(provider, `src/routes/${segment}.tsx`), + `import { createFileRoute } from '../routeScope.gen' +export const Route = createFileRoute('${moduleId}:/${segment}')({})`, + ) + } + await write( + path.join(host, 'src/routes/__root.tsx'), + `import { createRootRoute } from '@tanstack/react-router' +export const Route = createRootRoute()`, + ) + await write( + path.join(host, 'src/routes/outside.tsx'), + `import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/outside')({})`, + ) + for (const root of [provider, host]) { + const config = getConfig( + { + target: 'react', + disableLogging: true, + routesDirectory: './src/routes', + generatedRouteTree: './src/routeTree.gen.ts', + ...(root === host + ? { + routeModules: { includes: [{ module: moduleId, at: '/module' }] }, + } + : {}), + }, + root, + ) + await new Generator({ root, config }).run() + } + const lastSegment = `p${String(routeCount - 1).padStart(4, '0')}` + const entry = path.join(host, 'src/benchmark.ts') + await write( + entry, + `import { createRouter, createMemoryHistory } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' +import { isScopedMatch } from '../../provider/src/routeScope.gen' +const history = createMemoryHistory({ initialEntries: ['/module/p0000'] }) +const router = createRouter({ routeTree, history, isServer: true }) +export { isScopedMatch } +export const first = router.matchRoutes('/module/p0000').at(-1)! +export const lastMatches = router.matchRoutes('/module/${lastSegment}') +export const last = lastMatches.at(-1)! +export const miss = router.matchRoutes('/outside').at(-1)! +export function dispose() { history.destroy() }`, + ) + const jiti = createJiti(path.join(directory, 'load.mjs'), { + moduleCache: true, + fsCache: false, + }) + const loaded = await jiti.import(entry) + assert.equal(typeof loaded.isScopedMatch, 'function') + assert.equal(loaded.first.routeId, `${moduleId}:/p0000`) + assert.equal(loaded.last.routeId, `${moduleId}:/${lastSegment}`) + assert.equal(loaded.miss.routeId, '/outside') + assert.equal(loaded.isScopedMatch(loaded.first), true) + assert.equal(loaded.isScopedMatch(loaded.last), true) + assert.equal(loaded.isScopedMatch(loaded.miss), false) + assert.equal(loaded.lastMatches.filter(loaded.isScopedMatch).length, 2) + return loaded +} + +const BATCH = 1024 +const SAMPLE_COUNT = 12 +const SAMPLE_MILLISECONDS = 25 +let retainedChecksum = 0 + +function sample(operation, expectedBatchChecksum, duration) { + const started = performance.now() + let elapsed = 0 + let batches = 0 + let checksum = 0 + do { + for (let index = 0; index < BATCH; index++) { + checksum += operation(index) + } + batches++ + elapsed = performance.now() - started + } while (elapsed < duration) + assert.equal(checksum, expectedBatchChecksum * batches) + retainedChecksum += checksum + return { + nsPerOperation: (elapsed * 1e6) / (batches * BATCH), + operations: batches * BATCH, + } +} + +function measure(routeCount, name, operation, expectedBatchChecksum) { + sample(operation, expectedBatchChecksum, 150) + const samples = Array.from({ length: SAMPLE_COUNT }, () => + sample(operation, expectedBatchChecksum, SAMPLE_MILLISECONDS), + ) + const means = samples.map((value) => value.nsPerOperation) + const mean = means.reduce((sum, value) => sum + value, 0) / SAMPLE_COUNT + const deviation = Math.sqrt( + means.reduce((sum, value) => sum + (value - mean) ** 2, 0) / + (SAMPLE_COUNT - 1), + ) + const sorted = [...means].sort((left, right) => left - right) + console.log( + JSON.stringify({ + benchmark: 'generated-isScopedMatch', + routes: routeCount, + name, + hz: 1e9 / mean, + meanNsPerOperation: mean, + standardDeviationNs: deviation, + rme95Percent: + ((2.201 * deviation) / Math.sqrt(SAMPLE_COUNT) / mean) * 100, + // These are percentiles of batch means, not individual-call latency. + batchMeanP50Ns: sorted[Math.floor(SAMPLE_COUNT * 0.5)], + batchMeanP95Ns: sorted[Math.ceil(SAMPLE_COUNT * 0.95) - 1], + samples, + }), + ) +} + +try { + console.log( + JSON.stringify({ + node: process.version, + repository, + batch: BATCH, + samples: SAMPLE_COUNT, + }), + ) + for (const routeCount of [8, 64, 512]) { + const fixtureData = await fixture(routeCount) + const { isScopedMatch, first, last, miss, lastMatches } = fixtureData + const mixed = [first, last, miss, lastMatches[0]] + measure( + routeCount, + 'first leaf hit', + () => Number(isScopedMatch(first)), + BATCH, + ) + measure( + routeCount, + 'last leaf hit', + () => Number(isScopedMatch(last)), + BATCH, + ) + measure( + routeCount, + 'ordinary route miss', + () => Number(isScopedMatch(miss)), + 0, + ) + measure( + routeCount, + 'mixed hits and misses', + (index) => Number(isScopedMatch(mixed[index % mixed.length])), + BATCH / 2, + ) + measure( + routeCount, + 'filter actual ancestor match list', + () => lastMatches.filter(isScopedMatch).length, + BATCH * 2, + ) + fixtureData.dispose() + } + console.log(JSON.stringify({ retainedChecksum })) +} finally { + await fs.rm(workspace, { recursive: true, force: true }) +} diff --git a/scripts/benchmarks/route-modules/start-types.mjs b/scripts/benchmarks/route-modules/start-types.mjs new file mode 100644 index 0000000000..24b7a1ecff --- /dev/null +++ b/scripts/benchmarks/route-modules/start-types.mjs @@ -0,0 +1,325 @@ +import { createHash } from 'node:crypto' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { spawnSync } from 'node:child_process' +import { performance } from 'node:perf_hooks' + +const args = process.argv.slice(2) +function option(name, fallback) { + const index = args.indexOf(name) + return index === -1 ? fallback : args[index + 1] +} +const root = fs.realpathSync(option('--root', process.cwd())) +const label = option('--label', 'candidate') +const output = path.resolve( + option('--out', path.join(os.tmpdir(), `start-module-types-${label}`)), +) +const counts = option('--counts', '1,8,32').split(',').map(Number) +const repeats = Number(option('--repeats', '3')) +const warmups = Number(option('--warmups', '1')) +const compilerPackage = option('--compiler-package', 'typescript59') +const run = args.includes('--run') +if ( + !counts.every((n) => Number.isInteger(n) && n > 0) || + !Number.isInteger(repeats) || + repeats < 1 || + !Number.isInteger(warmups) || + warmups < 0 +) { + throw new Error( + 'Counts/repeats must be positive integers and warmups nonnegative.', + ) +} +const packageRoot = path.join(root, 'packages/start-client-core') +const packageJson = JSON.parse( + fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8'), +) +const modern = Object.hasOwn(packageJson.exports, './_internal/route-module') +const factoryEntry = modern + ? '@tanstack/start-client-core/_internal/route-module' + : '@tanstack/start-client-core' +const compilerRoot = fs.realpathSync( + path.join(root, 'node_modules', compilerPackage), +) +const compiler = path.join(compilerRoot, 'lib/tsc.js') +const compilerVersion = JSON.parse( + fs.readFileSync(path.join(compilerRoot, 'package.json'), 'utf8'), +).version + +if (fs.existsSync(path.join(output, 'results.json'))) { + throw new Error( + `Results already exist in ${output}; use a new --out to preserve the recorded run.`, + ) +} +fs.mkdirSync(output, { recursive: true }) +function link(target, destination) { + fs.mkdirSync(path.dirname(destination), { recursive: true }) + if (fs.existsSync(destination)) { + if (fs.realpathSync(destination) !== fs.realpathSync(target)) { + throw new Error(`Existing link points elsewhere: ${destination}`) + } + return + } + fs.symlinkSync(target, destination, 'dir') +} +link(packageRoot, path.join(output, 'node_modules/@tanstack/start-client-core')) +link( + fs.realpathSync(path.join(root, 'node_modules/@types/node')), + path.join(output, 'node_modules/@types/node'), +) +fs.writeFileSync( + path.join(output, 'package.json'), + JSON.stringify({ private: true, type: 'module' }, null, 2) + '\n', +) + +function source(count, scenario) { + const ids = Array.from( + { length: count }, + (_, index) => `@start-type-probe/fragment-${index}`, + ) + const declarations = modern + ? `declare module '@tanstack/start-client-core' {\n interface StartModuleRequirements {\n${ids.map((id) => ` '${id}': { requestContext: { viewer: string } }`).join('\n')}\n }\n}` + : `const requireViewer = requireRequestContext<{ viewer: string }>()` + const fragments = ids + .map((id, index) => { + const middleware = + scenario === 'flat' + ? `const middleware${index} = createMiddleware({ type: 'function' }).server(({ next }) => next({ context: { step${index}: true } }))` + : `// This object differs from sharedAudit at runtime but has the same type. +const independentAudit${index} = createMiddleware({ type: 'function' }).server(({ next }) => next({ context: { auditTag: 'fragment' } })) +const dependency${index} = createMiddleware({ type: 'function' }) + .middleware([sharedAudit, independentAudit${index}]) + .server(({ next }) => next({ context: { step${index}: true } })) +const middleware${index} = createMiddleware({ type: 'function' }) + .middleware([dependency${index}, sharedAudit]) + .server(({ context, next }) => { + const tag: string = context.auditTag + const retainsInference: 0 extends (1 & typeof context.auditTag) ? never : true = true + return next({ context: { lastAuditTag: tag, retainsInference } }) + })` + return `${middleware} +const fragment${index} = createStartModule('${id}')(() => ({ +${modern ? '' : ' requestMiddleware: [requireViewer],\n'} functionMiddleware: [middleware${index}], +}))` + }) + .join('\n\n') + return `// Same executable middleware graph and context on both revisions. +// Only the package's supported factory export and requirement syntax differ. +import { createStart, createMiddleware${modern ? '' : ', requireRequestContext'} } from '@tanstack/start-client-core' +import { createStartModule } from '${factoryEntry}' +import type { AssertStartModules, ValidateStartModules } from '@tanstack/start-client-core' + +${declarations} + +const viewer = createMiddleware().server(({ next }) => next({ context: { viewer: 'benchmark' } })) +const sharedAudit = createMiddleware({ type: 'function' }).server(({ next }) => next({ context: { auditTag: 'host' } })) + +${fragments} + +const fragments = [${ids.map((_, index) => `fragment${index}`).join(', ')}] as const +export const start = createStart(() => ({ + requestMiddleware: [viewer], + functionMiddleware: [sharedAudit], + extends: fragments, +})) +export type Validation = AssertStartModules> +export const valid: Validation = true +type ExpectTrue = T +type Options = Awaited> +// Force the complete installed contribution tuple without relying on any. +export type InstalledCount = ExpectTrue +` +} + +const cases = [ + { name: 'empty', count: 0, scenario: 'flat' }, + ...['flat', 'nested-dedupe'].flatMap((scenario) => + counts.map((count) => ({ name: `${scenario}-${count}`, count, scenario })), + ), +] +for (const item of cases) { + const directory = path.join(output, item.name) + fs.mkdirSync(directory, { recursive: true }) + const code = source(item.count, item.scenario) + fs.writeFileSync(path.join(directory, 'consumer.ts'), code) + fs.writeFileSync( + path.join(directory, 'tsconfig.json'), + JSON.stringify( + { + compilerOptions: { + target: 'ES2022', + module: 'ESNext', + moduleResolution: 'Bundler', + lib: ['DOM', 'DOM.Iterable', 'ES2022'], + types: ['node'], + strict: true, + skipLibCheck: true, + noEmit: true, + incremental: false, + }, + files: ['consumer.ts'], + }, + null, + 2, + ) + '\n', + ) + item.sourceSha256 = createHash('sha256').update(code).digest('hex') +} + +const declarations = [ + 'createStart.d.ts', + 'createStartModule.d.ts', + 'createMiddleware.d.ts', + 'createServerFn.d.ts', +].map((name) => { + const file = path.join(packageRoot, 'dist/esm', name) + return { + file, + sha256: createHash('sha256').update(fs.readFileSync(file)).digest('hex'), + } +}) +const revision = spawnSync('git', ['rev-parse', 'HEAD'], { + cwd: root, + encoding: 'utf8', +}).stdout.trim() +const status = spawnSync('git', ['status', '--porcelain'], { + cwd: root, + encoding: 'utf8', +}).stdout +const manifest = { + label, + root, + revision, + dirty: status.length > 0, + node: process.version, + compilerPackage, + compilerVersion, + factoryEntry, + requirements: modern + ? 'type-only augmentation' + : 'baseline requirement marker', + warmups, + repeats, + skipLibCheck: true, + declarations, + cases, + command: [ + process.execPath, + compiler, + '--project', + '/tsconfig.json', + '--extendedDiagnostics', + '--pretty', + 'false', + ], + notes: [ + 'Parent must build the selected checkout through Nx before running this probe.', + 'Instantiations is the primary metric. Wall time is supporting evidence only.', + 'Each subprocess is a fresh compiler process; the first run per case is discarded.', + 'No source aliases or manual declaration stubs: package exports resolve built declarations.', + "Requirements use each revision's supported syntax; executable middleware and host context are equivalent.", + 'Nested cases reuse a global object and add distinct objects with equal types, without breaking required context.', + 'skipLibCheck matches repository consumer defaults and isolates referenced generic work; full declaration correctness uses the package matrix.', + ], +} +fs.writeFileSync( + path.join(output, 'manifest.json'), + JSON.stringify(manifest, null, 2) + '\n', +) +console.log( + `Prepared ${cases.length} cases in ${output}; TypeScript ${compilerVersion}; ${run ? 'running' : 'no compiler runs requested'}.`, +) +if (run) { + const results = [] + for (const item of cases) { + const samples = [] + for (let sample = -warmups; sample < repeats; sample++) { + const started = performance.now() + const result = spawnSync( + process.execPath, + [ + compiler, + '--project', + path.join(output, item.name, 'tsconfig.json'), + '--extendedDiagnostics', + '--pretty', + 'false', + ], + { + cwd: root, + encoding: 'utf8', + timeout: 120_000, + maxBuffer: 8 * 1024 * 1024, + }, + ) + const elapsedMs = performance.now() - started + const log = `${result.stdout ?? ''}${result.stderr ?? ''}` + const sampleName = + sample < 0 ? `warmup-${sample + warmups + 1}` : `sample-${sample + 1}` + fs.writeFileSync(path.join(output, item.name, `${sampleName}.log`), log) + if (result.error || result.status !== 0) { + fs.writeFileSync( + path.join(output, 'failed.json'), + JSON.stringify( + { + case: item.name, + sample: sampleName, + status: result.status, + error: String(result.error ?? ''), + log, + }, + null, + 2, + ) + '\n', + ) + throw new Error( + `${item.name}/${sampleName} failed. See ${path.join(output, item.name, `${sampleName}.log`)}; no successful measurement claimed.`, + ) + } + const metric = (name) => + Number(new RegExp(`^${name}:\\s+([\\d.]+)`, 'm').exec(log)?.[1]) + const value = { + elapsedMs, + instantiations: metric('Instantiations'), + types: metric('Types'), + checkSeconds: metric('Check time'), + totalSeconds: metric('Total time'), + memoryKiB: metric('Memory used'), + } + if (!Number.isFinite(value.instantiations)) { + throw new Error( + `Missing extended diagnostics for ${item.name}/${sampleName}`, + ) + } + if (sample >= 0) { + samples.push(value) + } + } + const instantiationCounts = [ + ...new Set(samples.map((sample) => sample.instantiations)), + ] + if (instantiationCounts.length !== 1) { + throw new Error( + `Unstable compiler work for ${item.name}: ${instantiationCounts.join(', ')}`, + ) + } + const elapsed = samples + .map((sample) => sample.elapsedMs) + .sort((a, b) => a - b) + const result = { + ...item, + instantiations: instantiationCounts[0], + medianElapsedMs: elapsed[Math.floor(elapsed.length / 2)], + samples, + } + results.push(result) + fs.writeFileSync( + path.join(output, 'results.json'), + JSON.stringify({ ...manifest, results }, null, 2) + '\n', + ) + console.log( + `${item.name}: ${result.instantiations} instantiations; ${result.medianElapsedMs.toFixed(1)} ms median (${repeats} samples; ${warmups} discarded warmup).`, + ) + } +} From b2ad239b6bab6a9639f862dcb378278d5770b46d Mon Sep 17 00:00:00 2001 From: Manuel Schiller <6340397+schiller-manuel@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:21:32 +0100 Subject: [PATCH 02/14] test(route-modules): tidy the settings profile fixture pages Group the profile page's API probes into labeled Match, Links and Navigation sections and give them spacing. Point the framework Link probes and the React deferred members link at orgs the fixtures actually use instead of arbitrary ids, and style the installation switcher in the React fixture. Co-Authored-By: Claude Opus 5.5 --- .../route-modules/e2e/scope-parity.spec.ts | 16 ++-- .../packages/settings/src/routes/profile.tsx | 91 ++++++++++++------- .../packages/web/src/profile-links.tsx | 5 +- .../packages/web/src/routes/__root.tsx | 14 ++- .../route-modules/packages/web/src/styles.css | 82 +++++++++++++++++ .../tests/host-parameter-contracts.test.ts | 4 +- .../route-modules/e2e/scope-parity.spec.ts | 6 +- e2e/solid-router/route-modules/index.html | 41 +++++++++ .../packages/settings/src/routes/profile.tsx | 81 +++++++++++------ .../route-modules/e2e/scope-parity.spec.ts | 6 +- e2e/vue-router/route-modules/index.html | 41 +++++++++ .../packages/settings/src/routes/profile.tsx | 85 +++++++++++------ 12 files changed, 361 insertions(+), 111 deletions(-) diff --git a/e2e/react-router/route-modules/e2e/scope-parity.spec.ts b/e2e/react-router/route-modules/e2e/scope-parity.spec.ts index 1e762a0d6c..6793cc39d8 100644 --- a/e2e/react-router/route-modules/e2e/scope-parity.spec.ts +++ b/e2e/react-router/route-modules/e2e/scope-parity.spec.ts @@ -132,24 +132,24 @@ for (const base of ['/orgs/globex/settings', '/people/ada/settings']) { page, }) => { await page.goto(`${base}/profile`) - const host = page.getByRole('link', { name: 'Application host' }) - await expect(host).toHaveAttribute('href', '/orgs/9') - await host.click() - await expect(page).toHaveURL('/orgs/9') + const home = page.getByRole('link', { name: 'Application home' }) + await expect(home).toHaveAttribute('href', '/') + await home.click() + await expect(page).toHaveURL('/') }) } test('a local Link resolves options already wrapped by the same local scope', async ({ page, }) => { - await page.goto('/orgs/7/settings/profile') + await page.goto('/orgs/globex/settings/profile') const members = page.getByRole('link', { - name: 'Deferred members', + name: 'Acme members', exact: true, }) - await expect(members).toHaveAttribute('href', '/orgs/7/settings/members') + await expect(members).toHaveAttribute('href', '/orgs/acme/settings/members') await members.click() - await expect(page).toHaveURL('/orgs/7/settings/members') + await expect(page).toHaveURL('/orgs/acme/settings/members') await expect(page.getByText('MEMBERS_PAGE')).toBeVisible() }) diff --git a/e2e/react-router/route-modules/packages/settings/src/routes/profile.tsx b/e2e/react-router/route-modules/packages/settings/src/routes/profile.tsx index 29e5fdec2b..7237906480 100644 --- a/e2e/react-router/route-modules/packages/settings/src/routes/profile.tsx +++ b/e2e/react-router/route-modules/packages/settings/src/routes/profile.tsx @@ -36,37 +36,6 @@ function Profile() { return (

Profile

- {match?.routeId} - {match?.localRouteId} - - {JSON.stringify(match?.params)} - - API members - {ProfileLinks ? : null} - -
Custom members - - PROFILE_MATCH - - - MEMBERS_MATCH - - - {scopedRouter.buildLocation({ to: '/members' }).href} - - - - - Route home - - Application host -
Kind
{profile.kind}
@@ -76,6 +45,66 @@ function Profile() {
All settings + + {/* Every module-relative API, each resolved inside this installation. */} +
+

Match

+
+
Route id
+
+ {match?.routeId} +
+
Local id
+
+ {match?.localRouteId} +
+
Params
+
+ + {JSON.stringify(match?.params)} + +
+
Router href
+
+ + {scopedRouter.buildLocation({ to: '/members' }).href} + +
+
MatchRoute
+
+ + PROFILE_MATCH + + + MEMBERS_MATCH + +
+
+ +

Links

+

+ API members + Custom members + Route home + {ProfileLinks ? : null} + {/* The framework's own Link keeps application coordinates. */} + Application home +

+ +

Navigation

+

+ + + + +

+
) } diff --git a/e2e/react-router/route-modules/packages/web/src/profile-links.tsx b/e2e/react-router/route-modules/packages/web/src/profile-links.tsx index f05267a00b..c35747e91f 100644 --- a/e2e/react-router/route-modules/packages/web/src/profile-links.tsx +++ b/e2e/react-router/route-modules/packages/web/src/profile-links.tsx @@ -1,8 +1,9 @@ import * as settings from '@route-modules/settings/scope' import { orgSettings } from './routeScope.gen' +// Built once, outside any installation: always the Acme organization's members. const deferredMembers = settings.linkOptions( - orgSettings.linkOptions({ to: '/members', params: { orgId: '7' } }), + orgSettings.linkOptions({ to: '/members', params: { orgId: 'acme' } }), ) export function ProfileLinks() { @@ -13,6 +14,6 @@ export function ProfileLinks() { // The host owns its installation namespace; the provider renders this slot // inside the profile match so the local receiver has a real nearest scope. return organizationProfile ? ( - Deferred members + Acme members ) : null } diff --git a/e2e/react-router/route-modules/packages/web/src/routes/__root.tsx b/e2e/react-router/route-modules/packages/web/src/routes/__root.tsx index 72374fa0e4..fb1918b3fe 100644 --- a/e2e/react-router/route-modules/packages/web/src/routes/__root.tsx +++ b/e2e/react-router/route-modules/packages/web/src/routes/__root.tsx @@ -58,16 +58,22 @@ function AppShell() { -