diff --git a/.changeset/rsbuild-manifest-module-chunks-once.md b/.changeset/rsbuild-manifest-module-chunks-once.md new file mode 100644 index 0000000000..02febd9d84 --- /dev/null +++ b/.changeset/rsbuild-manifest-module-chunks-once.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +Rsbuild: the Start manifest pass that runs after every client compilation (builds and each dev update) reads an imported module's chunks once per compilation and counts the module once per importing chunk, instead of once per import connection. The manifest is unchanged; the pass takes about 40 % less time (on a 333-route app, tens of milliseconds less per HMR update). diff --git a/.changeset/rsbuild-manifest-own-chunks.md b/.changeset/rsbuild-manifest-own-chunks.md new file mode 100644 index 0000000000..04e8e29928 --- /dev/null +++ b/.changeset/rsbuild-manifest-own-chunks.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +Rsbuild: a route's client manifest entry lists only its own chunks and CSS. When two routes shared a module in a chunk of its own, each route's entry also listed the other route's chunk as a preload and its stylesheet. diff --git a/.changeset/rsbuild-rule-use-falsy-loaders.md b/.changeset/rsbuild-rule-use-falsy-loaders.md new file mode 100644 index 0000000000..a84a054fbd --- /dev/null +++ b/.changeset/rsbuild-rule-use-falsy-loaders.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +fix: the Rsbuild RSC integration skips falsy entries in a rule's `use` array (Rspack's conditionally disabled loaders) instead of treating them as loaders. diff --git a/.changeset/rsbuild-virtual-modules-build.md b/.changeset/rsbuild-virtual-modules-build.md new file mode 100644 index 0000000000..01a0c5ee6e --- /dev/null +++ b/.changeset/rsbuild-virtual-modules-build.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +Rsbuild: fix the Rsbuild plugin build after two changes to its virtual modules crossed. Without this fix the package does not build, so no release could ship it. The Rsbuild dev manifest is written to its virtual module under the app's root. diff --git a/.changeset/rsbuild-virtual-modules-root.md b/.changeset/rsbuild-virtual-modules-root.md new file mode 100644 index 0000000000..427043a712 --- /dev/null +++ b/.changeset/rsbuild-virtual-modules-root.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +Rsbuild: Start writes its virtual modules under the app's root, not the working directory. An app built or served from another directory (`rsbuild build --root ` from a monorepo root) no longer fails with "Module not found" on the packages they import, such as RSC's serialization adapters. diff --git a/.changeset/rsc-security-floor.md b/.changeset/rsc-security-floor.md new file mode 100644 index 0000000000..9c828f13b3 --- /dev/null +++ b/.changeset/rsc-security-floor.md @@ -0,0 +1,8 @@ +--- +'@tanstack/react-start-rsc': patch +--- + +Raise the minimum RSC bundler peer dependencies to versions with the React Server Components fixes for GHSA-xqc2-xf4c-x3h3 (CVE-2026-126187, unauthenticated RCE) and GHSA-h3gv-c5rc-p453 (server function DoS): + +- `@vitejs/plugin-rsc` to `>=0.5.38` (GHSA-59pf-q495-3c99), which vendors a fixed `react-server-dom-webpack`. +- `react-server-dom-rspack` to `>=0.1.1`, the first release built from React sources that include the fix. diff --git a/.changeset/start-server-fn-custom-id-check.md b/.changeset/start-server-fn-custom-id-check.md new file mode 100644 index 0000000000..384f0ade06 --- /dev/null +++ b/.changeset/start-server-fn-custom-id-check.md @@ -0,0 +1,7 @@ +--- +'@tanstack/start-plugin-core': minor +--- + +A server function id that a custom `serverFns.generateFunctionId` returns and that never worked over HTTP now fails the build, with an error naming the file, the function and the id: whitespace, a control or non-ASCII character, any of `"`, `#`, `/`, `<`, `>`, `?`, `\`, `^`, `` ` ``, `{`, `}`, the ids `.` and `..`, and a percent-encoding the server reads as another id (`%41`, lowercase hex, `%2E`) or rejects. The client puts the id in the URL unencoded, so a `#` or `?` ended the path and a `/` cut the id short (the call silently ran another server function of the file or none), and the other characters reached the server percent-encoded and matched no function. An id embedding a non-ASCII `functionName` is one of these. One case did work and now fails the build: such an id on a server function only SSR code called. + +Ids with `%` or the other characters URLs allow (such as `:`, `@`, `+`, `=`, `,`, `;`, `!`, `*`, `(`, `)`, `&`, `'`, `|`, `[`, `]`) still build and reach their handler, with a deprecation warning (from the Vite plugin; the Rsbuild plugin does not print compiler warnings yet): the next major version rejects them, since proxies and servers may decode or rewrite them (hash the inputs instead, as the documented example does). An id with `'` no longer breaks the server bundle. diff --git a/.changeset/start-vite-root-library-discovery.md b/.changeset/start-vite-root-library-discovery.md new file mode 100644 index 0000000000..d4e8221c59 --- /dev/null +++ b/.changeset/start-vite-root-library-discovery.md @@ -0,0 +1,5 @@ +--- +'@tanstack/start-plugin-core': patch +--- + +Vite: Start finds the Start libraries it bundles in the SSR build from Vite's root, not the working directory. A `vite build ` run from another directory (a monorepo root, a script) no longer leaves them external and uncompiled, where their server fns returned `undefined`. diff --git a/.coderabbit.yaml b/.coderabbit.yaml new file mode 100644 index 0000000000..21d884dbeb --- /dev/null +++ b/.coderabbit.yaml @@ -0,0 +1,12 @@ +# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json + +reviews: + request_changes_workflow: false + slop_detection: + enabled: true + +knowledge_base: + code_guidelines: + enabled: true + filePatterns: + - 'CONTRIBUTING.md' diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index a33150af03..9dd0def7bd 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -4,6 +4,14 @@ body: - type: markdown attributes: value: | + + Thank you for reporting an issue :pray:. This issue tracker is for reporting bugs found in TanStack Router and/or Start. diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000000..a5ef10f1ff --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,22 @@ +## 🎯 Changes + + + +## ✅ Checklist + +- [ ] I have followed the steps in the [Contributing guide](https://github.com/TanStack/router/blob/main/CONTRIBUTING.md). +- [ ] I have tested code changes locally with the relevant test commands, or tests do not apply to this pull request. +- [ ] I fully understand the code in this pull request, including any code generated with AI assistance. + +## 🚀 Release Impact + +- [ ] This change affects published code, and I have generated a [changeset](https://github.com/changesets/changesets/blob/main/docs/adding-a-changeset.md). +- [ ] This change is docs/CI/dev-only (no release). + + diff --git a/.github/renovate.json b/.github/renovate.json index 01be1ce5c2..6fd5aa1c86 100644 --- a/.github/renovate.json +++ b/.github/renovate.json @@ -21,7 +21,6 @@ "@types/node", "@types/react", "@types/react-dom", - "h3", "node", "react", "react-dom", diff --git a/.github/workflows/client-nav-benchmarks.yml b/.github/workflows/benchmarks.yml similarity index 88% rename from .github/workflows/client-nav-benchmarks.yml rename to .github/workflows/benchmarks.yml index a56bb70334..bbc3a1fa24 100644 --- a/.github/workflows/client-nav-benchmarks.yml +++ b/.github/workflows/benchmarks.yml @@ -18,9 +18,18 @@ on: pull_request: paths: - 'packages/**' + - '!packages/**/tests/**' + - '!packages/**/__tests__/**' + - '!packages/**/*.test.*' - 'benchmarks/**' + - '.nvmrc' workflow_dispatch: +concurrency: + group: benchmarks-${{ github.ref }} + cancel-in-progress: false + queue: single + permissions: contents: read # required for actions/checkout id-token: write # required for OIDC authentication with CodSpeed @@ -72,7 +81,8 @@ jobs: @benchmarks/${{ matrix.benchmark }}:build:${{ matrix.framework }} - name: Run ${{ matrix.benchmark }}:${{ matrix.framework }} CodSpeed benchmark - uses: CodSpeedHQ/action@9d332c4d90b43981c3e55ae8e38e68709996240f # v4.17.0 + uses: CodSpeedHQ/action@373d6868929f444bc08d901fd0eb0ad52a8875ea # v5.2.1 + timeout-minutes: 20 with: mode: ${{ matrix.mode }} run: >- diff --git a/.github/workflows/bundle-size.yml b/.github/workflows/bundle-size.yml index d0deda36a7..51ffa28e4c 100644 --- a/.github/workflows/bundle-size.yml +++ b/.github/workflows/bundle-size.yml @@ -8,11 +8,19 @@ on: paths: - 'packages/**' - 'benchmarks/**' + - 'scripts/benchmarks/bundle-size/**' + - '.nvmrc' + - 'package.json' + - 'pnpm-lock.yaml' push: branches: [main] paths: - 'packages/**' - 'benchmarks/**' + - 'scripts/benchmarks/bundle-size/**' + - '.nvmrc' + - 'package.json' + - 'pnpm-lock.yaml' workflow_dispatch: concurrency: @@ -43,7 +51,7 @@ jobs: uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main - name: Measure Bundle Size - run: pnpm nx run @benchmarks/bundle-size:build --outputStyle=stream --skipRemoteCache + run: pnpm benchmark:bundle-size --outputStyle=stream --skipRemoteCache - name: Capture Benchmark Outputs id: capture @@ -101,6 +109,8 @@ jobs: cat benchmarks/bundle-size/results/pr-comment.md - name: Upsert Sticky PR Comment + # Fork PRs have a read-only GITHUB_TOKEN, so they cannot update comments. + if: ${{ github.event.pull_request.head.repo.full_name == github.repository }} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | @@ -110,7 +120,7 @@ jobs: benchmark-main: name: Publish Bundle Size History - if: github.event_name == 'push' && github.ref == 'refs/heads/main' && github.repository_owner == 'TanStack' + if: (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && github.ref == 'refs/heads/main' && github.repository_owner == 'TanStack' runs-on: ubuntu-latest permissions: contents: write @@ -125,7 +135,7 @@ jobs: uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main - name: Measure Bundle Size - run: pnpm nx run @benchmarks/bundle-size:build --outputStyle=stream --skipRemoteCache + run: pnpm benchmark:bundle-size --outputStyle=stream --skipRemoteCache - name: Publish Benchmark Dashboard uses: benchmark-action/github-action-benchmark@52576c92bccf6ac60c8223ec7eb2565637cae9ba # v1.22.1 with: diff --git a/.github/workflows/compiler-platforms.yml b/.github/workflows/compiler-platforms.yml new file mode 100644 index 0000000000..ad70e39bb6 --- /dev/null +++ b/.github/workflows/compiler-platforms.yml @@ -0,0 +1,101 @@ +name: Compiler Platforms + +# The main PR workflow only runs on Linux x64 (glibc). The compilers load a +# native Yuku binary per platform and handle platform-specific paths, so run +# their unit tests and a Vite and Rsbuild production build on the other +# platforms we ship to. + +on: + pull_request: + paths: + - 'packages/router-utils/**' + - 'packages/router-generator/**' + - 'packages/router-plugin/**' + - 'packages/start-plugin-core/**' + - 'pnpm-lock.yaml' + - '.github/workflows/compiler-platforms.yml' + schedule: + # Weekly, to catch new Yuku releases and runner image updates + - cron: '0 6 * * 1' + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.event.number || github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +env: + NX_DAEMON: 'false' + NX_NO_CLOUD: 'true' + +defaults: + run: + shell: bash + +jobs: + compiler: + name: ${{ matrix.name }} + runs-on: ${{ matrix.os }} + # actions/setup-node only ships glibc builds, so musl uses Alpine's Node image + container: ${{ matrix.container }} + strategy: + fail-fast: false + matrix: + include: + - name: Windows x64 + os: windows-latest + - name: macOS arm64 + os: macos-latest + - name: Linux arm64 + os: ubuntu-24.04-arm + - name: Linux x64 musl + os: ubuntu-latest + container: node:24.8.0-alpine3.22@sha256:3e843c608bb5232f39ecb2b25e41214b958b0795914707374c8acc28487dea17 + steps: + - name: Install system packages + if: ${{ matrix.container }} + shell: sh + run: apk add --no-cache bash git + - name: Keep LF line endings + # Snapshots are stored with LF. Windows runners check out CRLF by default, + # and with `* text=auto` disabling autocrlf alone still uses the native eol + run: | + git config --global core.autocrlf false + git config --global core.eol lf + - name: Checkout + uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + - name: Setup pnpm + if: ${{ !matrix.container }} + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 + - name: Setup Node + if: ${{ !matrix.container }} + uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0 + with: + node-version-file: .nvmrc + package-manager-cache: false + - name: Setup pnpm (container) + if: ${{ matrix.container }} + run: npm install --global "$(node -p "require('./package.json').packageManager")" + - name: Install dependencies + run: >- + pnpm install --frozen-lockfile + --filter . + --filter "@tanstack/router-utils..." + --filter "@tanstack/router-generator..." + --filter "@tanstack/router-plugin..." + --filter "@tanstack/start-plugin-core..." + --filter "tanstack-react-start-e2e-basic..." + - name: Unit tests + run: >- + pnpm nx run-many --targets=test:unit + --projects=@tanstack/router-utils,@tanstack/router-generator,@tanstack/router-plugin,@tanstack/start-plugin-core + --skip-nx-cache --outputStyle=static + - name: Production builds + run: >- + pnpm nx run-many --targets=build:vite:ssr,build:rsbuild:ssr + --projects=tanstack-react-start-e2e-basic + --skip-nx-cache --outputStyle=static diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml index d8c779b170..fde1100409 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -9,6 +9,8 @@ permissions: jobs: labeler: + # Fork PRs have a read-only GITHUB_TOKEN, so they cannot update labels. + if: ${{ github.event.pull_request.head.repo.full_name == github.repository }} runs-on: ubuntu-latest steps: - name: Labeller diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 71026a0a92..ae19b4f0d2 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -10,6 +10,13 @@ concurrency: env: NX_CLOUD_ACCESS_TOKEN: ${{ secrets.NX_CLOUD_ACCESS_TOKEN }} SERVER_PRESET: 'node-server' + # Enable dynamic task packing for distributed CI. + NX_CLOUD_AGENT_TASK_QUEUE: true + NX_CLOUD_AUTO_TASK_PACKING: true + NX_CLOUD_AGENT_UNCAPPED_GROUP_WORK: true + NX_CLOUD_PACKING_MEM_MULTIPLIER: 1.5 + NX_CLOUD_BUFFER_TASK_COMPLETIONS: true + NX_CLOUD_CONTINUOUS_ASSIGNMENT: true permissions: contents: read @@ -26,8 +33,8 @@ jobs: with: fetch-depth: 0 persist-credentials: false - - name: Start Nx Agents - run: npx nx-cloud start-ci-run --distribute-on=".nx/workflows/dynamic-changesets.yaml" + - name: Start Nx Workers + run: npx nx-cloud start-workers - name: Setup Tools uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main - name: Get base and head commits for `nx affected` @@ -36,9 +43,9 @@ jobs: main-branch-name: main - name: Run Checks run: pnpm run test:pr --parallel=3 - - name: Stop Nx Agents + - name: Stop Nx Workers if: ${{ always() }} - run: npx nx-cloud stop-all-agents + run: npx nx-cloud stop-all-workers preview: name: Preview runs-on: ubuntu-latest diff --git a/.gitignore b/.gitignore index 1699592784..70028b2860 100644 --- a/.gitignore +++ b/.gitignore @@ -66,6 +66,7 @@ nx-cloud.env .nx/workspace-data .nx/polygraph .nx/self-healing +.nx/migrate-runs gpt/db.json diff --git a/.nvmrc b/.nvmrc index b404027604..63f87c20ef 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -24.8.0 +26.12.1 diff --git a/.nx/ci-config.yaml b/.nx/ci-config.yaml new file mode 100644 index 0000000000..2f0783feb4 --- /dev/null +++ b/.nx/ci-config.yaml @@ -0,0 +1,5 @@ +dte: + distribute-on: + small-changeset: 6 linux-medium-js + medium-changeset: 12 linux-medium-js + large-changeset: 18 linux-medium-js diff --git a/.nx/workflows/dynamic-changesets.yaml b/.nx/workflows/dynamic-changesets.yaml deleted file mode 100644 index 786111053d..0000000000 --- a/.nx/workflows/dynamic-changesets.yaml +++ /dev/null @@ -1,4 +0,0 @@ -distribute-on: - small-changeset: 4 linux-medium-js - medium-changeset: 8 linux-medium-js - large-changeset: 14 linux-medium-js diff --git a/.nx/workflows/ultracache-config.yaml b/.nx/workflows/ultracache-config.yaml new file mode 100644 index 0000000000..b3ed223621 --- /dev/null +++ b/.nx/workflows/ultracache-config.yaml @@ -0,0 +1,124 @@ +ignore-reads: + - e2e/.gitignore + - '**/src/routeTree.gen.ts' +ignore-writes: + - '**/src/routeTree.gen.ts' +task-exclusions: + - target: test:build + ignore-reads: + - LICENSE + # HMR tests edit these inputs in place and restore their original contents. + # Keep them out of cached outputs so cache replay never overwrites source. + - project: tanstack-react-start-e2e-deferred-hydration + target: test:e2e + ignore-writes: + - e2e/react-start/deferred-hydration/src/routes/components.tsx + - project: tanstack-react-start-e2e-hmr + target: test:e2e + ignore-writes: &hmr-source-writes + - e2e/react-start/hmr/src/components/AliasedRouteImportChildPanel.tsx + - e2e/react-start/hmr/src/components/AliasedRouteImportParentPanel.tsx + - e2e/react-start/hmr/src/hmr/server-fn-hmr-factory.ts + - e2e/react-start/hmr/src/routes/__root.tsx + - e2e/react-start/hmr/src/routes/child.tsx + - e2e/react-start/hmr/src/routes/component-hmr-inline-error-split.tsx + - e2e/react-start/hmr/src/routes/component-hmr-inline-nosplit.tsx + - e2e/react-start/hmr/src/routes/component-hmr-inline-split.tsx + - e2e/react-start/hmr/src/routes/component-hmr-lowercase-named-split.tsx + - e2e/react-start/hmr/src/routes/component-hmr-named-error-split.tsx + - e2e/react-start/hmr/src/routes/component-hmr-named-nosplit.tsx + - e2e/react-start/hmr/src/routes/component-hmr-named-split.tsx + - e2e/react-start/hmr/src/routes/index.tsx + - e2e/react-start/hmr/src/routes/inputs.tsx + - project: tanstack-react-start-e2e-hmr + target: test:e2e--vite-ssr + ignore-writes: *hmr-source-writes + - project: tanstack-react-start-e2e-hmr + target: test:e2e--vite-ssr--bundled-dev + ignore-writes: *hmr-source-writes + - project: tanstack-react-start-e2e-hmr + target: test:e2e--rsbuild-ssr + ignore-writes: *hmr-source-writes + - project: tanstack-react-start-e2e-rsbuild + target: test:e2e--rsbuild-ssr + ignore-writes: + - e2e/react-start/rsbuild/src/routes/index.tsx + - project: tanstack-react-start-e2e-server-functions + target: test:e2e + ignore-writes: + - e2e/react-start/server-functions/src/routes/consistent.tsx + # Scaffolding tests deliberately populate tracked empty route fixtures. + - project: '@tanstack/router-generator' + target: test:unit + ignore-writes: + - packages/router-generator/tests/generator/custom-scaffolding/routes/__root.tsx + - packages/router-generator/tests/generator/custom-scaffolding/routes/api/bar.tsx + - packages/router-generator/tests/generator/custom-scaffolding/routes/foo.lazy.tsx + - packages/router-generator/tests/generator/custom-scaffolding/routes/index.tsx + # These reads are of scratch files created by the same test invocation. + - project: tanstack-solid-start-e2e-basic-auth + target: test:e2e + ignore-reads: + - e2e/solid-start/basic-auth/.tmp/dev.db + - project: tanstack-vue-start-e2e-basic-auth + target: test:e2e + ignore-reads: + - e2e/vue-start/basic-auth/.tmp/dev.db + - project: '@tanstack/router-generator' + target: test:unit + ignore-reads: + - packages/router-generator/tests/generator/file-modification/routes/[(]test[)]/initiallyEmpty.tsx + - packages/router-generator/tests/generator/file-modification/routes/[(]test[)]/initiallyEmpty.lazy.tsx + # Mutable counters are scratch state, not artifacts to replay from cache. + - project: tanstack-react-start-e2e-basic-tsr-config + target: test:e2e + ignore-reads: + - e2e/react-start/basic-tsr-config/count.txt + ignore-writes: + - e2e/react-start/basic-tsr-config/count.txt + - project: tanstack-solid-start-e2e-basic-tsr-config + target: test:e2e + ignore-reads: + - e2e/solid-start/basic-tsr-config/count.txt + ignore-writes: + - e2e/solid-start/basic-tsr-config/count.txt + - project: tanstack-vue-start-e2e-basic-tsr-config + target: test:e2e + ignore-reads: + - e2e/vue-start/basic-tsr-config/count.txt + ignore-writes: + - e2e/vue-start/basic-tsr-config/count.txt + # Paraglide downloads compiler plugins from the URLs in settings.json. + # Ignore warm-cache reads; the settings remain inputs and cache files outputs. + - project: tanstack-react-start-e2e-i18n-paraglide + target: build + ignore-reads: + - e2e/react-start/i18n-paraglide/project.inlang/cache/plugins/* + - project: tanstack-router-e2e-react-i18n-paraglide + target: build + ignore-reads: + - e2e/react-router/i18n-paraglide/project.inlang/cache/plugins/* + - project: tanstack-react-start-e2e-i18n-paraglide + target: test:e2e + ignore-reads: + - e2e/react-start/i18n-paraglide/project.inlang/cache/plugins/* + - project: tanstack-router-e2e-react-i18n-paraglide + target: test:e2e + ignore-reads: + - e2e/react-router/i18n-paraglide/project.inlang/cache/plugins/* + - project: tanstack-router-i18n-paraglide + target: build + ignore-reads: + - examples/react/i18n-paraglide/project.inlang/cache/plugins/* + - project: tanstack-start-i18n-paraglide + target: build + ignore-reads: + - examples/react/start-i18n-paraglide/project.inlang/cache/plugins/* + - project: tanstack-router-solid-i18n-paraglide + target: build + ignore-reads: + - examples/solid/i18n-paraglide/project.inlang/cache/plugins/* + - project: tanstack-solid-start-i18n-paraglide + target: build + ignore-reads: + - examples/solid/start-i18n-paraglide/project.inlang/cache/plugins/* diff --git a/.prettierignore b/.prettierignore index 65991e1964..de501452ad 100644 --- a/.prettierignore +++ b/.prettierignore @@ -17,4 +17,7 @@ node_modules /.nx/workspace-data **/src/routeTree.gen.ts packages/router-plugin/tests/**/test-files/** -.nx/self-healing \ No newline at end of file +.nx/self-healing + +# Preserve the pinned upstream URL fixtures byte for byte. +packages/router-core/tests/fixtures/wpt-url/urltestdata*.json diff --git a/AGENTS.md b/AGENTS.md index 490cb691d4..f47b5103e1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,177 +1,41 @@ # AGENTS.md -## Project overview +## Scope -TanStack Router is a type-safe router with built-in caching and URL state management for React and Solid applications. This monorepo contains two main products: +- Read applicable nested `AGENTS.md` files before editing or testing a subtree. +- Shared routing belongs in `packages/router-core`; check React, Solid, and Vue bindings for shared changes. Shared Start runtime/build logic lives in `packages/start-*-core`. -- **TanStack Router** - Core routing library with type-safe navigation, search params, and path params -- **TanStack Start** - Full-stack framework built on top of TanStack Router +## Work and validation -## Setup commands +- Start bug fixes with a failing regression test that uses only public APIs to reproduce and assert user- or developer-visible behavior. Do not manufacture bugs by mutating internals. Establish whether real usage can reach the failing state before adding runtime handling; simplify handling of states proven unreachable. +- When removing an API, option, or behavior, delete its tests. Never add tests that assert the removed thing is gone, such as `not.toHaveProperty('oldName')`, a type error for the old call, or a runtime throw. +- For suspected dependency issues, verify the upstream root cause, then propose an upstream fix to the user, including for other `@tanstack/*` packages. **Never implement a workaround in this repository unless the user explicitly authorizes it.** +- During debugging/prototyping, keep fixes aligned with the PR's intended architecture. If making a test pass requires another flag, counter, copied deadline, or duplicate completion authority, stop and consolidate state and ownership. Remove superseded paths instead of accumulating patches and bundle growth. +- Use Node from `.nvmrc` and pnpm from root `package.json`. Install at the root with `CI=1 pnpm install --frozen-lockfile`. +- For sandbox-blocked registry/store access, escalate the same command; report the blocker if unavailable. Do not change stores, delete dependencies/lockfiles, use `--force`/`--ignore-scripts`, or weaken workspace trust/build policies to bypass it. +- Never manually edit `pnpm-lock.yaml` or any `routeTree.gen.ts`. Regenerate the lockfile with `pnpm install --no-frozen-lockfile` after intentional dependency changes; regenerate route trees through app builds/dev servers or the generator fixture harness. +- Always use control-flow braces. Run `pnpm format` before validation. +- Use Nx: workspace imports consume built packages, so direct runners can test stale dependencies. Inspect resolved targets with `pnpm nx show project --json`; some are inferred. +- Run finite validation through `run-many` with explicit projects and targets, including a single project/target. Nx automatically selects `summary` output when it detects an AI agent: omit `--outputStyle` for normal runs. Read the reported full log files for failures; use `--outputStyle=summary` if agent detection is unavailable. +- Use `--outputStyle=static` or `pnpm nx run :` only when diagnosing a task and its full output is needed. Continuous/watch targets may use live output. -- Install deps: `pnpm install` -- Setup e2e testing: `pnpm exec playwright install` -- Build packages: `pnpm build` (affected) or `pnpm build:all` (force all) -- Start dev server: `pnpm dev` -- Run tests: `pnpm test` +```sh +CI=1 NX_DAEMON=false pnpm nx run-many -p -t --skipRemoteCache +``` -## Code style +- Run one Nx command at a time. For a ~20-second startup/graph stall, stop, run `pnpm nx reset`, and retry once, then escalate. Do not apply that timeout to running tests. +- For code changes, run affected packages' `test:unit`, `test:types`, and `test:eslint` where available, including affected consumers; use `test:e2e` for browser/app behavior and `test:build` for exports/build changes. Root `pnpm test` includes the full e2e suite. Published-code changes require `pnpm changeset`. -- TypeScript strict mode with extensive type safety -- Framework-agnostic core logic separated from React/Solid bindings -- Type-safe routing with search params and path params -- Use workspace protocol for internal dependencies (`workspace:*`) -- Always use curly braces for `if`, `else`, loops, and similar control statements. Never write one-line bodies like `if (foo) x = 1`. +## Runtime rules -## Dev environment tips +- Import `isServer` from `@tanstack/router-core/isServer`. Conditional exports select: `development` → `undefined`; server (`workerd`, `worker`, `deno`, `node`, `bun`) → `true` except `NODE_ENV=test` → `undefined`; browser/fallback → `false`. `development` wins; `NODE_ENV=development` alone does not select it. +- Keep `isServer ?? router.isServer` directly in each branch condition for dead-code elimination; negate the whole expression for client branches. Never extract it into a variable (e.g. `const serverRendering = isServer ?? router.isServer`) or helper. Without a router, inline `isServer ?? typeof window === 'undefined'` (or the existing `document` check). Keep the constant first and use `??`, never `||`. +- **Never create UI/router reactivity on the server, including development/tests.** Branch before reactive setup; use direct reads and core non-reactive stores. Required transport listeners are allowed only with request-scoped lifetimes and cleanup. +- Shared route definitions/build metadata must not acquire request/user data. Keep it on the request's Router, context, or QueryClient. +- HMR can replace code while caches and pending work survive. Invalidate derived state or bypass caching in development; reject stale async results while preserving intentional HMR identities/state. +- Gate developer diagnostics and message construction with direct `process.env.NODE_ENV !== 'production'` checks. Preserve required validation/throws in production (e.g. detailed development error, compact `invariant()` failure). `!== 'development'` also enables the guarded code in tests; preserve existing dev-server mode gates. -- This is a pnpm workspace monorepo with packages organized by functionality -- Nx provides caching, affected testing, targeting, and parallel execution for efficiency -- Use `pnpm nx show projects` to list all available packages -- Target specific packages: `pnpm nx run @tanstack/react-router:test:unit` -- Target multiple packages: `pnpm nx run-many --target=test:eslint --projects=@tanstack/history,@tanstack/router-core` -- Run affected tests only: `pnpm nx affected --target=test:unit` -- Exclude patterns: `pnpm nx run-many --target=test:unit --exclude="examples/**,e2e/**"` -- Navigate to examples and run `pnpm dev` to test changes: `cd examples/react/basic && pnpm dev` -- **Granular unit testing through Nx (recommended):** - - Specific files: `pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx tests/Scripts.test.tsx` - - Test patterns: `pnpm nx run @tanstack/react-router:test:unit -- tests/ClientOnly.test.tsx -t "should render fallback"` - - Name patterns: `pnpm nx run @tanstack/react-router:test:unit -- -t "navigation"` (all tests with "navigation" in name) - - Exclude patterns: `pnpm nx run @tanstack/react-router:test:unit -- --exclude="**/*link*" tests/` - - List tests: `pnpm nx run @tanstack/react-router:test:unit -- list tests/link.test.tsx` (or `-- list` for all) -- **Available test targets per package:** `test:unit`, `test:types`, `test:eslint`, `test:build`, `test:perf`, `build` -- **Testing strategy:** Package level (nx) → File-level args via nx → Test-level args (`-t`) via nx → Pattern-level args (`--exclude`) via nx -- **Agent execution guardrails (important):** - - Always prefer `pnpm nx ...` over `npx nx ...`. - - Prefer Nx targets over direct test runners so task dependencies (including required builds) remain in the graph. - - In sandbox, run Nx with `CI=1 NX_DAEMON=false pnpm nx run : --outputStyle=stream --skipRemoteCache` - - Run only one Nx command at a time. - - If an Nx command shows no output for ~20 seconds, stop, run `pnpm nx reset` once, and retry once. - - Do not loop retries indefinitely. If it still hangs or sandbox blocks graph/daemon behavior, request escalation immediately. +## Performance and final bundle pass -## Testing instructions - -- **Critical**: Always run unit and type tests during development - do not proceed if they fail -- **Test types:** `pnpm test:unit`, `pnpm test:types`, `pnpm test:eslint`, `pnpm test:e2e`, `pnpm test:build` -- **Full CI suite:** `pnpm test:ci` -- **Fix formatting:** `pnpm format` -- **Efficient targeted testing workflow:** - 1. **Affected only:** `pnpm nx affected --target=test:unit` (compares to main branch) - 2. **Specific packages:** `pnpm nx run @tanstack/react-router:test:unit` - 3. **Specific files:** `pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx` - 4. **Specific patterns:** `pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx -t "preloading"` -- **Pro tips:** - - Use `pnpm nx run @tanstack/react-router:test:unit -- list` to explore available tests before running - - Use `-t "pattern"` to focus on specific functionality during development - - Use `--exclude` patterns to skip unrelated tests - - Keep all test filtering arguments behind `pnpm nx run ... -- ...` for maximum precision while preserving task dependencies -- **Example workflow:** `pnpm nx run @tanstack/react-router:test:unit` → `pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx` → `pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx -t "preloading"` - -## PR instructions - -- Always run `pnpm test:eslint`, `pnpm test:types`, and `pnpm test:unit` before committing -- Test changes in relevant example apps: `cd examples/react/basic && pnpm dev` -- Update corresponding documentation in `docs/` directory when adding features -- Add or update tests for any code changes -- Use internal docs links relative to `docs/` folder (e.g., `./guide/data-loading`) - -## Package structure - -**Core packages:** - -- `packages/router-core/` - Framework-agnostic core router logic -- `packages/react-router/`, `packages/solid-router/` - React/Solid bindings and components -- `packages/history/` - Browser history management - -**Tooling:** - -- `packages/router-cli/` - CLI tools for code generation -- `packages/router-generator/` - Route generation utilities -- `packages/router-plugin/` - Universal bundler plugins (Vite, Webpack, ESBuild, Rspack) -- `packages/virtual-file-routes/` - Virtual file routing system - -**Developer experience:** - -- `packages/router-devtools/`, `packages/*-router-devtools/` - Development tools -- `packages/eslint-plugin-router/` - ESLint rules for router - -**Validation adapters:** - -- `packages/zod-adapter/`, `packages/valibot-adapter/`, `packages/arktype-adapter/` - -**Start framework:** - -- `packages/*-start/`, `packages/start-*/` - Full-stack framework packages - -**Examples & testing:** - -- `examples/react/`, `examples/solid/` - Example applications (test changes here) -- `e2e/` - End-to-end tests (requires Playwright) -- `docs/router/`, `docs/start/` - Documentation with React/Solid subdirectories - -**Dependencies:** Uses workspace protocol (`workspace:*`) - core → framework → start packages - -## Common development tasks - -**Adding new routes:** - -- Use file-based routing in `src/routes/` directories -- Or use code-based routing with route definitions -- Run route generation with CLI tools - -**Testing changes:** - -- Build packages: `pnpm build` or `pnpm dev` (watch mode) -- Run example apps to test functionality -- Use devtools for debugging router state - -**Documentation updates:** - -- Update relevant docs in `docs/` directory -- Ensure examples reflect documentation changes -- Test documentation links and references -- Use relative links to `docs/` folder format - -## Framework-specific notes - -**React:** - -- Uses React Router components and hooks -- Supports React Server Components (RSC) -- Examples include React Query integration -- Package: `@tanstack/react-router` - -**Solid:** - -- Uses Solid Router components and primitives -- Supports Solid Start for full-stack applications -- Examples include Solid Query integration -- Package: `@tanstack/solid-router` - -## Environment requirements - -- **Node.js** - Required for development -- **pnpm** - Package manager (required for workspace features) -- **Playwright** - Required for e2e tests (`pnpm exec playwright install`) - -## Key architecture patterns - -- **Type Safety**: Extensive TypeScript for type-safe routing -- **Framework Agnostic**: Core logic separated from framework bindings -- **Plugin Architecture**: Universal bundler plugins using unplugin -- **File-based Routing**: Support for both code-based and file-based routing -- **Search Params**: First-class support for type-safe search parameters - -## Development workflow - -1. **Setup**: `pnpm install` and `pnpm exec playwright install` -2. **Build**: `pnpm build:all` or `pnpm dev` for watch mode -3. **Test**: Make changes and run relevant tests (use nx for targeted testing) -4. **Examples**: Navigate to examples and run `pnpm dev` to test changes -5. **Quality**: Run `pnpm test:eslint`, `pnpm test:types`, `pnpm test:unit` before committing - -## References - -- **Documentation**: https://tanstack.com/router -- **GitHub**: https://github.com/TanStack/router -- **Discord Community**: https://discord.com/invite/WrRKjPJ +- For runtime/memory changes, compare identical baseline/candidate workloads using the relevant [benchmark guide](benchmarks/AGENTS.md): client navigation, Start SSR, or memory. Add coverage for unmeasured mechanisms. +- **Last phase for every change affecting emitted client JavaScript**, including core/build transforms: complete the full [bundle-size-optimization skill](.agents/skills/bundle-size-optimization/SKILL.md) after correctness and performance validation. The full workflow is mandatory. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c28d01241b..4b6e808af1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,30 +1,95 @@ -# Contributing +# Contributing to TanStack Router -- Clone the repo - - `gh repo clone TanStack/router` -- Ensure `node` is installed - - https://nodejs.org/en/ -- Ensure `pnpm` is installed - - https://pnpm.io/installation - - Why? We use `pnpm` to manage workspace dependencies. It's easily the best monorepo/workspace experience available as of when this was written. -- Install dependencies - - `pnpm install` - - This installs dependencies for all of the packages in the monorepo, even examples! - - Dependencies inside of the packages and examples are automatically linked together as local/dynamic dependencies. -- Install test dependencies - - `pnpm exec playwright install` (required for e2e tests) -- Run the build or dev watcher - - `pnpm build:all` (build all packages) or - - `pnpm build` (cached build with [nx affected](https://nx.dev/nx-api/nx/documents/affected)) or - - `pnpm dev` -- Navigate to an example - - `cd examples/react/basic` -- Run the example - - `pnpm dev` -- Make changes to the code - - If you ran `pnpm dev` the dev watcher will automatically rebuild the code that has changed -- Editing the docs locally and previewing the changes - - The documentations for all the TanStack projects are hosted on [tanstack.com](https://tanstack.com), which is a TanStack Start application (https://github.com/TanStack/tanstack.com). You need to run this app locally to preview your changes in the `TanStack/router` docs. +TanStack Router is a community project. Contributions to both TanStack Router and TanStack Start are welcome. + +## Setup + +1. Clone the repository: + + ```sh + gh repo clone TanStack/router + ``` + +2. Install [Node.js](https://nodejs.org/en/) and [pnpm](https://pnpm.io/installation). This repository requires pnpm `11.x.x` or newer. +3. Install dependencies: + + ```sh + pnpm install + ``` + + This installs dependencies for the entire monorepo, including examples. Workspace dependencies are linked automatically. + +4. Install the Playwright browsers if you will run end-to-end tests: + + ```sh + pnpm exec playwright install + ``` + +5. Create a branch for your changes: + + ```sh + git checkout -b my-new-branch + ``` + +## Before you start + +- Search the [open and closed issues](https://github.com/TanStack/router/issues?q=is%3Aissue) before reporting a bug. If it has not already been reported, use the [bug report template](https://github.com/TanStack/router/issues/new?template=bug_report.yml). +- Search the [open and closed pull requests](https://github.com/TanStack/router/pulls?q=is%3Apr) before starting work to avoid duplicating an existing contribution. +- Pull requests that require API changes must first be proposed as an issue and receive maintainer sign-off before implementation begins. + +## Pull request guidelines + +Every pull request must follow the [TanStack Router pull request template](.github/pull_request_template.md). Complete its description and checklist without removing or bypassing the required sections. + +- Keep each pull request focused on one change or topic. Pull requests that combine unrelated changes will be closed with a request to split them into separately reviewable contributions. +- Write a concise description that clearly explains what changed and why. Follow the sections in the pull request template; a long, unstructured description makes a contribution harder to review. +- Every change that affects a published package must include a changeset. Create it with `pnpm changeset`; documentation, CI, examples, and development-only changes do not require one. + +## Development + +- `pnpm build:all` builds all packages. +- `pnpm build` runs the cached Nx build for affected packages. +- `pnpm dev` builds the packages and starts the development watcher. + +To run an example application, move into its directory and start its development server. For example: + +```sh +cd examples/react/basic +pnpm dev +``` + +## Testing and linting + +Run the checks relevant to your changes while developing: + +- `pnpm test:eslint` checks linting for affected packages. +- `pnpm test:types` checks types for affected packages. +- `pnpm test:unit` runs unit tests for affected packages. +- `pnpm test:build` checks builds for affected packages. +- `pnpm test:e2e` runs end-to-end tests and requires the Playwright browsers. + +Before opening a pull request, run at least: + +```sh +pnpm test:eslint +pnpm test:types +pnpm test:unit +``` + +To run the full CI test suite, use `pnpm test:ci`. For faster feedback, use an Nx target for a specific package or pass a test file or test name after `--`. For example: + +```sh +pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx +pnpm nx run @tanstack/react-router:test:unit -- tests/link.test.tsx -t "preloading" +``` + +Add appropriate unit tests for isolated behavior and end-to-end tests for browser or application workflows. Test relevant example applications when the change affects them. + +## Documentation + +Update the relevant documentation for user-facing changes. Documentation lives in the `docs/` directory, with separate sections for Router and Start. Use relative links within the `docs/` directory, such as `./guide/data-loading`. + +The documentation sites are hosted on [tanstack.com](https://tanstack.com), which is a [TanStack Start application](https://github.com/TanStack/tanstack.com). To preview documentation changes locally, clone both repositories as siblings: > [!NOTE] > The website fetches the doc pages from GitHub in production, and searches for them at `../router/docs` in development. Your local clone of `TanStack/router` needs to be in the same directory as the local clone of `TanStack/tanstack.com`. @@ -53,7 +118,7 @@ git clone git@github.com:TanStack/tanstack.com.git --depth=1 --single-branch --b > [!NOTE] > Your `tanstack` directory should look like this: > -> ``` +> ```text > tanstack/ > | > +-- router/ (<-- this directory cannot be called anything else!) @@ -75,6 +140,21 @@ pnpm dev > [!WARNING] > You will need to update the `docs/(router or start)config.json` file (in `TanStack/router`) if you add a new documentation page! -You can see the whole process in the screen capture below: +## AI-assisted contributions -https://github.com/fulopkovacs/form/assets/43729152/9d35a3c3-8153-4e74-9cb2-af275f7a269b + + +AI tools can be useful for exploring the codebase, drafting changes, and writing tests. They do not replace the contributor's responsibility for the result. + +1. **Keep the contribution in your own voice**. Review and rewrite generated code comments, issue reports, and pull request descriptions so they reflect what you actually mean. +2. **Keep ownership of technical decisions**. Understand every change, verify its behavior with the appropriate tests and documentation, and be ready to explain it during review. +3. **Do not paste LLM output verbatim into the codebase or a contribution**. Treat generated text and code as a draft: check its claims, adapt it to the repository, and remove anything you cannot justify. Issues or pull requests that appear to contain unreviewed LLM output may be closed without further review. +4. **Do not mass-submit unrelated or low-quality AI-generated pull requests**. We treat that behavior as spam and may close the pull requests, block the contributor, and report the GitHub account. + +AI-assisted contributions follow the same standards for correctness, testing, documentation, and review as every other contribution. diff --git a/ISSUES.md b/ISSUES.md deleted file mode 100644 index f7aee4da83..0000000000 --- a/ISSUES.md +++ /dev/null @@ -1,489 +0,0 @@ -# PR #7805 review issue ledger - -This ledger is the source of truth for review findings against: - -- PR: `TanStack/router#7805` -- Base: `0b178a79e2e872df0107bd7f0faa891c4c9815ef` -- Head under test: `6683863a75a46297765b288957fccd147006ef0c` -- Prior review: - -Consult this file before investigating a concern. Update it immediately when evidence changes. Production code must not be fixed during this review. - -## Checkout and build record - -- Local branch: `codex/pr-7805-review`, checked out at exact PR head `6683863a75a46297765b288957fccd147006ef0c` against base `0b178a79e2e872df0107bd7f0faa891c4c9815ef`. -- Dependency setup: `CI=1 pnpm i` completed successfully. -- PR build: `CI=1 NX_DAEMON=false pnpm build` completed successfully for all 43 selected projects (7 cached). The only infrastructure warning was Nx Cloud DNS `ENOTFOUND`; local builds succeeded. -- Completion audit on 2026-07-18 reran the same build at the unchanged PR head: all 43 selected projects succeeded again (42 from the local cache, one executed). Nx Cloud again reported only the non-blocking DNS `ENOTFOUND` warning. -- Review tests are deliberately red while production remains untouched. Focused Nx targets are run one at a time with daemon/remote cache disabled; each verified production row below names its retained failing test. G01 and P09 are intentionally green controls. - -### Final focused validation matrix - -All commands below ran from the repository root with `CI=1 NX_DAEMON=false`, `--outputStyle=stream`, `--skipRemoteCache`, and `--skipNxCache`. A red result is expected for a retained production regression; it is a validation failure only if the test passes unexpectedly or fails for setup/type noise. - -- **Router core:** one 14-file focused run completed with 12 failing files and 2 passing files; 13 failing cases and 3 passing cases. The failures are P02 (runtime and exported type), P04, P08, P10, P12, D01, N02-N05, and N10. N03 contributes two independent failing cases. G01 and P09 pass; P12's fresh-chain control also passes. The only reported type-test failure is P02's four deliberately missing public fields; there are no incidental source/type errors or unhandled test errors. -- **React adapter/server/hydration:** one five-file focused run completed with all 8 cases failing for P03, P06, P07, P11, N06, N07 sync, N07 async, and N08. Type checking reports no errors. -- **Vue adapter:** the two-file focused run fails exactly N01 and Vue's P05 teardown acknowledgement. Type checking reports no errors. -- **Solid adapter:** the Nx target's client phase ran the full package suite: 53 files passed and only the retained P05 file failed; 824 tests passed, one retained review test failed, and one test was skipped by the existing suite. Type checking reports no errors. The target stops before its server-mode phase because the intentional client regression is red; the P05 test is client-only. -- **Router plugin HMR:** the exact H01 name-filtered run executes one retained test and fails because `hotRoute.lazyFn` remains the old importer, the old importer runs twice, and the new importer never runs. Type checking reports no errors. An earlier mistyped name filter matched nothing and is not validation evidence. - -Across those final runs, the production ledger contains **21 verified issues represented by 25 failing cases in 21 files**. No production implementation file was changed to obtain these results. - -The completion audit reran the package-relative focused filters and reproduced the exact core, React, Vue, and HMR matrices plus Solid's retained P05 failure. A preceding core invocation accidentally supplied repository-relative paths to package-rooted Vitest and matched no files; it is explicitly discarded as validation evidence. The corrected core rerun immediately afterward produced the 12-failing/2-passing-file and 13-failing/3-passing-case matrix recorded above. - -## Validation standard - -A production behavior issue is **VERIFIED** only when all of the following are present: - -1. A focused regression test fails on the PR head for the claimed behavioral reason. -2. The failure is checked against the intended contract/reference behavior so the test is not merely asserting a preference or failing for setup noise. -3. The code path and impact are independently reviewed by the primary investigator and at least two additional reviewers. -4. The issue has a concrete, implementation-ready repair outline and acceptance criteria in `PLAN.md`. - -A test-suite-only finding is classified separately. It requires three independent reviewers to prove that the existing test can pass while its named behavior is absent, that its setup measures unrelated work, or that the claimed interleaving has no oracle. These findings enter only the test-hardening section of `PLAN.md`; they are not evidence of an additional runtime defect. Their implementation must add a diagnostic oracle and prove it fails under the named negative mutation before any related production fix is credited. - -Statuses: - -- `UNVERIFIED`: inherited claim or new hypothesis; not yet reproduced here. -- `TEST-WRITTEN`: focused test exists but its signal or expected contract is still under review. -- `VERIFIED`: failing regression plus three independent reviews agree. -- `VERIFIED TEST-GAP` / `VERIFIED BOGUS-ORACLE` / `VERIFIED PARITY-GAP`: three independent reviews prove a test-only false-positive or missing-coverage window; no additional runtime defect is claimed. -- `VERIFIED COVERAGE-GAP`: three reviewers confirm a documented interleaving is not actually exercised; it remains test-only. -- `VERIFIED WITH `: the test gap is closed by the named production issue's retained failing regression rather than a duplicate test. -- `NOT-VALIDATED`: reproduction failed, the contract does not require the behavior, or independent reviewers rejected the claim. It remains here to prevent repeat investigation. -- `FIXED-UPSTREAM`: not a PR-head defect after comparison; retained for history. -- `COVERAGE-VALIDATED`: the production behavior passes a strong focused test, but that direct regression coverage is absent from the PR and should be retained as a test-only improvement. - -## Status summary - -| ID | Severity / class | Area | Current status | Reproduction / control evidence | Independent reviews | -| --- | ------------------------- | ------------------------------------------------------------------------- | --------------------- | ---------------------------------------------------------------------------------------------- | ------------------------- | -| P01 | Blocker | Babel/Vite transform of `declare` class fields | NOT-VALIDATED | none (supported-pipeline controls pass) | 3/3 falsification reviews | -| P02 | Blocker | Removed public `RouterState` fields | VERIFIED | `packages/router-core/tests/pr-7805-review-c-router-state-compat.test{.ts,-d.ts}` | 3/3 | -| P03 | Major | React transition callback after unmount | VERIFIED | `packages/react-router/tests/pr-7805-review-transitioner-unmount.test.tsx` | 3/3 | -| P04 | Major | Background asset projection mutates committed matches | VERIFIED | `packages/router-core/tests/pr-7805-review-p04-background-projection.test.ts` | 3/3 | -| P05 | Major | Solid/Vue false rendered acknowledgement after unmount | VERIFIED | `packages/{solid,vue}-router/tests/pr-7805-review-transitioner-unmount.test.tsx` | 3/3 | -| P06 | Major | React lazy component retry keeps stale reload latch | VERIFIED | `packages/react-router/tests/pr-7805-review-lazy-retry-module-error.test.tsx` | 3/3 | -| P07 | Blocker | Generic SSR redirects converted to HTTP 200 | VERIFIED | `packages/react-router/tests/pr-7805-review-ssr-regressions.test.tsx` | 3/3 | -| P08 | Major | Pending-session takeover preserves stale visible snapshot | VERIFIED | `packages/router-core/tests/pr-7805-review-p08-pending-takeover.test.ts` | 3/3 | -| P09 | Moderate | Preload redirect limit/cycle handling | NOT-VALIDATED | exact-boundary test passes | 3/3 falsification reviews | -| P10 | Major | Blocking child consumes stale background parent | VERIFIED | `packages/router-core/tests/pr-7805-review-p10-semantic-parent.test.ts` | 3/3 | -| P11 | Major | Functional `ssr()` failure skips lazy boundary chunk | VERIFIED | `packages/react-router/tests/pr-7805-review-ssr-regressions.test.tsx` | 3/3 | -| P12 | Moderate | Failed redirect target leaks redirect-chain authority | VERIFIED | `packages/router-core/tests/pr-7805-review-p12-redirect-authority.test.ts` | 3/3 | -| G01 | Coverage gap | Child-local `loaderDeps` change with stable parent | COVERAGE-VALIDATED | `packages/router-core/tests/pr-7805-review-c-child-loader-deps-reuse.test.ts` passes | 3/3 | -| D01 | Audit | Client/server conditional exports and DCE | VERIFIED | `packages/router-core/tests/pr-7805-review-c-server-dce.test.ts` | 3/3 | -| N01 | Major candidate | Vue global error boundary cannot reset on same-route reload | VERIFIED | `packages/vue-router/tests/pr-7805-review-global-boundary-reset.test.tsx` | 3/3 | -| N02 | Major candidate | Planning-time self redirects bypass the redirect-cycle budget | VERIFIED | `packages/router-core/tests/pr-7805-review-n02-planning-redirect-budget.test.ts` | 3/3 | -| N03 | Major candidate | Late preload can cache/join a child from a superseded parent generation | VERIFIED | two cases in `packages/router-core/tests/pr-7805-review-n03-preload-parent-generation.test.ts` | 3/3 | -| N04 | Major candidate | Superseded load waits for obsolete component preload | VERIFIED | `packages/router-core/tests/pr-7805-review-n04-obsolete-component-preload.test.ts` | 3/3 | -| N05 | Major candidate | Stale pre-commit background candidate leaks its flight lease | VERIFIED | `packages/router-core/tests/pr-7805-review-n05-background-candidate-lease.test.ts` | 3/3 | -| N06 | Major candidate | Global error boundary does not reset after child-only background recovery | VERIFIED | `packages/react-router/tests/pr-7805-review-global-boundary-background-reset.test.tsx` | 3/3 | -| N07 | Major candidate | Functional SSR failure erases route context seen by its boundary | VERIFIED | `packages/react-router/tests/pr-7805-review-server-context-frontier.test.tsx` (sync + async) | 3/3 | -| N08 | Major candidate | Hydrated unresolved frontier retains incomplete parent context | VERIFIED | `packages/react-router/tests/pr-7805-review-server-context-frontier.test.tsx` | 3/3 | -| N09 | Component-chunk candidate | Repeated component preload calls after removal of the route-level cache | NOT-VALIDATED | none (documented design; no at-most-once contract) | 3/3 falsification reviews | -| N10 | Major candidate | Same-ID flight join ignores freshly rerun own route/beforeLoad context | VERIFIED | `packages/router-core/tests/pr-7805-review-n10-inflight-preload-own-context.test.ts` | 3/3 | -| H01 | HMR candidate | Explicit source-chained `.lazy()` retains old importer | VERIFIED | `packages/router-plugin/tests/handle-route-update.test.ts` | 3/3 | -| T01 | Test gap | Vue root-pending test never asserts pending UI | VERIFIED TEST-GAP | existing test passes without pending UI | 3/3 | -| T02 | Bogus test oracle | Preload-redirect selector counts include initial load | VERIFIED BOGUS-ORACLE | existing React/Solid/Vue tests do not isolate preload | 3/3 | -| T03 | E2E gap | Issue 7120 does not prove View Transition/stale-frame path | VERIFIED TEST-GAP | existing Playwright test passes without either named oracle | 3/3 | -| T04 | E2E gap | Issue 7457 does not observe transient blank frames | VERIFIED TEST-GAP | existing Playwright test samples only endpoints | 3/3 | -| T05 | E2E gap | Solid issue 7283 does not assert configured pending minimum | VERIFIED TEST-GAP | existing Playwright test discards recorded timestamps | 3/3 | -| T06 | Coverage gap | Generic lazy retry tests miss module-not-found branch | VERIFIED WITH P06 | retained P06 failing regression supplies coverage | 3/3 | -| T07 | Coverage caveat | Preloaded-mount test does not reproduce original race | VERIFIED COVERAGE-GAP | existing test explicitly documents limitation | 3/3 | -| T08 | Parity gap | Pending replacement/stale-content coverage differs by adapter | VERIFIED PARITY-GAP | framework test-matrix audit | 3/3 | -| T09 | Test setup gap | React issue-7051 overlaps initial load and drops predecessor navigation | VERIFIED TEST-GAP | existing test admits false-positive setup/settlement paths | 3/3 | -| T10 | Test oracle gap | React listener-error test never proves throwing listener ran | VERIFIED BOGUS-ORACLE | existing test passes if throwing listener is skipped | 3/3 | -| T11 | Test quality gap | Vue abort test uses multi-second timing and weak abort oracles | VERIFIED TEST-GAP | existing test has only delayed/at-least-once endpoints | 3/3 | -| T12 | Bogus test oracle | Pending-preload reuse test codifies a context-insensitive loader join | VERIFIED BOGUS-ORACLE | N10 fails while the existing one-loader test passes | 3/3 | - -## Prior-review claims and local validation - -### P01 — Babel/Vite transform rejects runtime `declare` class fields - -- Prior claim: source-consuming React/Vite/Babel pipelines process class features before TypeScript stripping and reject `declare` fields in `packages/router-core/src/router.ts`. -- Suspect declarations: `shouldViewTransition`, `isViewTransitionTypesSupported`, `_tx`, `_flights`, `_committedMatches`, `_pending`, `_serverResult`, `_rendered`, `_refreshRoute`. -- Required proof: a repository-owned transform/build test using the affected pipeline fails on the PR head specifically at a `declare` field, plus confirmation that an initialized field form is accepted by the same pipeline. -- Local falsification: the repository-supported Vite 8/React pipeline parses the TypeScript source and strips the `declare` fields successfully; the PR package build also completes. A failure can be constructed only by ordering a raw Babel class-features transform before TypeScript transformation, but no supported repository pipeline or documented source-consumer contract using that ordering was found. -- Independent falsification: build/API, adapters, and client-lane reviewers separately inspected the repository transform order, package exports, supported consumer/build paths, and the deliberately misordered raw Babel control. All reject the contrived Babel ordering as evidence of a supported PR regression. -- Status: **NOT-VALIDATED**. - -### P02 — public `RouterState` fields were removed incompatibly - -- Prior claim: `loadedAt`, `isTransitioning`, `statusCode`, and `redirect` disappeared from the public `RouterState` interface and runtime state without a major release/changeset. -- Required proof: a public-package type test and, where applicable, runtime test that passes at the base contract and fails on the PR head; confirm docs/exports make the fields public rather than internal. -- Contract decision needed: compatibility restoration versus explicit major-version migration. A test cannot by itself decide semver policy. -- Focused tests: `packages/router-core/tests/pr-7805-review-c-router-state-compat.test-d.ts` exercises the exported type and `packages/router-core/tests/pr-7805-review-c-router-state-compat.test.ts` exercises a real router state object. -- Local results: the runtime test fails because `loadedAt`, `isTransitioning`, `statusCode`, and `redirect` are all absent from `router.state`; the type test independently reports missing-property errors for all four names on the exported `RouterState`. The independent public-entrypoint/docs/v1-semver reviews below establish that the silent removal is a compatibility blocker. -- Independent reviews: build/API primary established the type/runtime removal; adapters reviewer independently confirmed public entrypoint re-exports, public docs, v1 semver, and deprecation precedent; client-lane reviewer independently compared the base interface, runtime initial values, public selectors, and lack of migration/changeset. All three accept the tests and contract. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED**. - -### P03 — React load can hang after `Transitioner` unmount - -- Prior claim: cleanup drains existing acknowledgements but leaves stale `router.startTransition` and `router._rendered` callbacks installed. A later load enqueues an acknowledgement no mounted tree can resolve. -- Required proof: mount and settle, unmount, trigger a history/router load, and demonstrate that completion/onResolved/idle hangs on the PR head. The same test must distinguish an actual liveness failure from an intentionally absent `onRendered` event. -- Focused test: `packages/react-router/tests/pr-7805-review-transitioner-unmount.test.tsx`. It fails after the provider is synchronously unmounted: a later no-subscriber `router.navigate()` returns `stalled` after 100 ms instead of resolving, remains pending, and does not advance `resolvedLocation`. Source review confirms teardown removes the history listener but leaves the transition callback installed, so the final commit enqueues an acknowledgement after the only renderer has gone. -- Independent reviews: adapters primary reproduction; client-lane reviewer independently traced the core fallback and unresolvable post-unmount acknowledgement; build/API reviewer independently validated the cleanup/ownership path and test oracle. All three accept the liveness defect. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED**. - -### P04 — background asset projection mutates committed matches before currentness check - -- Prior claim: `runBackground` shallow-copies the lane; `projectLane` writes asset fields on shared match objects before CAS/currentness validation, leaking stale or unnotified state. -- Required proof: block an async `head`/`scripts` projection, retain direct references and subscription counts, supersede the background transaction, then show committed objects change before/without valid publication. -- Focused test now isolated in `packages/router-core/tests/pr-7805-review-p04-background-projection.test.ts` fails: the retained committed object changes from `{title:'foreground-refresh'}` to `{title:'discarded-background'}` after the losing background projection settles. Controls prove the initial/foreground titles, separate stale reload, successor `/slow` pending state, and exact presented object identity before release. -- Independent reviews: client-lane primary reproduction; build/API reviewer independently confirmed shared base-object projection before CAS; adapters reviewer independently re-derived the shallow-copy/mutating-projection path and accepted the identity oracle. All three accept the defect. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED**. - -### P05 — Solid and Vue report rendered after provider unmount - -- Prior claim: stale framework transition callbacks remain callable after teardown and resolve `true`, causing false `onRendered` events and `pendingMinMs` obligations. -- Required proof: framework-specific mount/unmount/load tests demonstrating resolution occurs but a post-unmount publication is incorrectly acknowledged/rendered; remount must still work. -- Focused tests: `packages/solid-router/tests/pr-7805-review-transitioner-unmount.test.tsx` and `packages/vue-router/tests/pr-7805-review-transitioner-unmount.test.tsx`. Both fail on the final negative event assertion: after unmount, navigation legitimately completes to idle `/next`, but the stale transition callback emits one `onRendered` event for `/` to `/next`. Each test subscribes only after initial idle, excluding mount noise. The Solid package's other 824 client tests passed (one skipped); the focused Vue invocation ran exactly the two requested files. -- Independent reviews: adapters primary reproduction; client-lane reviewer independently confirmed `onRendered`'s renderer-ack contract and missing cleanup; build/API reviewer independently checked framework closures, core false fallback, and test isolation. All three accept both adapter failures. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED**. - -### P06 — React lazy retry retains module-reload intent after successful retry - -- Prior claim: recognized dynamic-import failure sets closure-level `reload = true`; retry resets `error`/`loadPromise` but not `reload`, so a later successful preload still reloads/suspends on first render. -- Required proof: exact sequence `recognized module failure -> successful retry -> render`, asserting a valid component renders without reload. Include control cases for immediate render after failure and generic errors. -- Focused regression: `packages/react-router/tests/pr-7805-review-lazy-retry-module-error.test.tsx`. It uses the browser-recognized dynamic-import `TypeError`, asserts the reload session-storage marker after the failed preload, successfully retries the importer, then renders once with a fake reload spy. It fails exactly because the stale latch still calls `window.location.reload()` and throws the eternal suspense promise after the successful retry. The PR's existing generic-error retry test cannot enter this branch. Two independently authored drafts reproduced the same signal and were consolidated into this stronger single case. -- Independent reviews: build/API primary, adapters reviewer, and client-lane reviewer independently confirmed the recognized error classifier, attempt-specific reload intent, successful retry contract, and genuine eternal-promise failure. All three accept the tests. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED**. - -### P07 — generic SSR redirect becomes `200 + Location` - -- Prior claim: core `createRequestHandler` always invokes framework renderers after load; render helpers map non-render server results to status 200, while TanStack Start separately short-circuits redirects. -- Required proof: exercise the real generic request handler and real React/Solid/Vue string/stream response helpers with thrown and returned redirects; assert status, Location, custom headers, body, and render-callback invocation. -- Local failing regression: `packages/react-router/tests/pr-7805-review-ssr-regressions.test.tsx`, test `P07: generic SSR preserves redirect response status and headers`. -- Command: `CI=1 NX_DAEMON=false pnpm nx run @tanstack/react-router:test:unit --outputStyle=stream --skipRemoteCache --skipNxCache -- tests/pr-7805-review-ssr-regressions.test.tsx`. -- PR-head result: **fails** with `expected 200 to be 307`; the redirect's `Location` and custom header survive. The code flow confirms `createRequestHandler` calls `router.load()`, dehydrates, constructs headers, and invokes `cb` without branching on `_serverResult.type`. The React string renderer then assigns 200 for every non-`render` result. The same status fallback exists in React/Solid/Vue string and stream renderers, while TanStack Start separately short-circuits its redirect at `packages/start-server-core/src/createStartHandler.ts`. -- Reference control: base/main's string renderer uses the public server `statusCode` store and therefore returns the redirect's 307. The regression test deliberately does **not** require the callback to be skipped or the body to be empty, because base invokes the renderer; those are possible repair choices, not necessary facts for validating the status regression. -- Completed review controls: independent reviewers confirmed the generic-handler composition and all six renderer fallback sites, traced both returned and thrown redirect normalization, and compared base cleanup/dehydration ordering. The focused failure pins the shared status bug; the returned/renderer/status matrix remains an implementation acceptance expansion in `PLAN.md`. -- Independent reviews: root primary reproduction; adapters reviewer independently confirmed the generic-handler contract, renderer fallback, redirect-header controls, public/default composition, and Start's contrasting short-circuit; build/API reviewer independently compared base/public composition and both returned/thrown redirect normalization across all six renderer paths. All three accept the failing test and contract. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED**. - -### P08 — pending-session ownership transfer leaves prior transaction's snapshot visible - -- Prior claim: same-boundary/same-match-ID takeover transfers timing ownership but, when `session.ack` exists, skips publishing the successor snapshot. Search/state/context can differ without changing match ID. -- Required proof: two controlled overlapping same-route navigations with identical match ID and differing search/state; a visible pending component must demonstrate whether old values remain while location is new. Verify the original pending-min deadline is preserved. -- Focused test now isolated in `packages/router-core/tests/pr-7805-review-p08-pending-takeover.test.ts` fails: after the first pending lane visibly has search revision one and the successor location visibly has revision two, the pending match still exposes revision one. A shared loader gate keeps both same-match-ID navigations overlapped and both navigation promises subsequently settle; the hardened test bounded-waits for successor publication and drains both promises in `finally`. -- Independent reviews: client-lane primary reproduction; build/API reviewer independently confirmed the same-ID owner-transfer/early-return path; adapters reviewer independently re-derived the timing/snapshot split and accepted the test. All three accept the defect. The repair test must add nonzero `pendingMinMs` preservation. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED**. - -### P09 — preload redirect limit is off by one and disconnected from lane cycle handling - -- Prior claim: preload starts at zero, stops only at `redirects > 20`, and omits accumulated depth from `executeClientLane`, allowing 21 follows and bypassing the intended cycle error. -- Required proof: focused tests at exact redirect counts (19/20/21), across thrown/returned and beforeLoad/loader redirects; confirm intended public preload-cycle contract and `reloadDocument` behavior. -- Focused test: `packages/router-core/tests/pr-7805-review-p09-preload-redirect-boundary.test.ts`. It passes on the PR head: a preload starting at step zero follows redirects through step 20 (exactly twenty follows) and does not execute step 21; the next redirect is rejected by the `redirects > 20` entry guard. The prior review counted visited locations rather than redirect edges and therefore described the correct boundary as off by one. -- Independent falsification: client-lane, build/API, and isolated-test reviewers separately traced the recursion counter and agreed with the edge-count oracle. The test also prevents a future boundary regression and should be retained as coverage. -- Remaining coverage recommendation: table-test thrown/returned redirects from `beforeLoad`, loader, and lazy-chunk failures plus `reloadDocument`; this is hardening, not evidence for the rejected claim. -- Status: **NOT-VALIDATED**. Do not add a production fix for P09. - -### P10 — mixed background-parent/blocking-child publication is incoherent - -- Prior claim: the background parent has a fresh `semanticParent`, but a blocking child receives `tasks[index - 1]?.match`, which resolves to the stale foreground parent; final publication can pair fresh parent data with child data derived from the stale generation. -- Required proof: controlled revisions with parent background reload and child blocking reload; child awaits `parentMatchPromise` and records revision. Test mixed-mode inverse and all-foreground controls. -- Focused regression: `packages/router-core/tests/pr-7805-review-p10-semantic-parent.test.ts`. The final finite harness starts exactly two parent and two child loaders, releases the private parent candidate as revision 2, and fails because the committed child still contains `{parentRevision: 1}` instead of 2. Controlled start signals and runaway-call sentinels exclude deadlock and accidental retry as explanations. -- Source cause: `createLoaderTask` is passed the fresh `semanticParent`, and the background candidate correctly receives it, but the blocking `shouldReload` context and foreground `loadResource` call use `tasks[index - 1]?.match`. For a background parent task that promise resolves to its stale foreground match, even though the function returns the candidate promise as the semantic chain for descendants. -- Independent reviews: client-lane primary, build/API, and adapters reviewers independently traced the mixed-mode promise graph; the isolated-test reviewer validated the corrected oracle and exact call counts. They agree a published child must be derived from the same parent generation that is published with it. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED**. - -### P11 — functional `ssr()` failure can skip lazy boundary readiness - -- Prior claim: `match.ssr` remains undefined when functional SSR selection throws, so the later `match.ssr === true` guard does not load a lazy error/not-found boundary chunk. -- Required proof: sync and async functional `ssr()` failures on lazy routes rendered through a framework; test inherited `true`, `false`, and `data-only` policy and both error/not-found boundaries. -- Local failing regression: `packages/react-router/tests/pr-7805-review-ssr-regressions.test.tsx`, test `P11: a functional ssr failure renders its lazy error boundary`. -- Command: same focused React test command recorded under P07. -- PR-head result: **fails** with the built-in `Something went wrong!` UI instead of `lazy reports boundary: ssr selection failed`. The response status is correctly 500, isolating the failure to boundary readiness/rendering rather than error classification. -- Source flow: `contextualize` assigns `match.ssr` only after awaiting `resolveSsr`; a thrown option leaves it `undefined`. `applyFailure` selects the failing match, but terminal chunk readiness is guarded by `match.ssr === true`, so `loadRouteChunk(route, 'errorComponent')` is skipped. -- Completed review controls: independent reviewers confirmed inherited/default selective-SSR semantics, genuine lazy-route setup, and base serial-failure boundary readiness. N07's separate sync/async eager-boundary cases cover selector rejection timing without masking P11; the full policy/not-found matrix remains an implementation acceptance expansion in `PLAN.md`. -- Independent reviews: root primary reproduction; adapters reviewer independently confirmed the uninitialized `match.ssr` path, terminal-chunk guard, base boundary behavior, and inherited/default selective-SSR nuance; build/API reviewer independently confirmed sync/async selector rejection, genuine lazy-route setup, and base serial-error readiness. All three accept the failing test for the default/inherited-true case. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED**. - -### P12 — redirecting flag survives a failed target build - -- Prior claim: foreground/background redirect handling sets `tx.redirecting = true`, awaits `router.navigate`, and clears without `finally`; a thrown target-build hook leaves authority that an unrelated navigation can inherit. -- Required proof: make target location building fail, then start an unrelated navigation and inspect behavioral redirect-depth/cycle consequences. Cover synchronous and asynchronous failure only where the actual build APIs allow them. -- Focused regression: `packages/router-core/tests/pr-7805-review-p12-redirect-authority.test.ts`. Its control proves an independent A/B redirect cycle makes 21 loader calls before producing `Redirect cycle detected`. After a redirect whose target `search` builder throws, the otherwise identical unrelated cycle fails the oracle at 20 calls: the new transaction inherited the failed predecessor's depth. Alternating routes, the imperative no-history-subscriber commit fallback, bounded timers, and a runaway sentinel exclude same-URL test-helper behavior and unbounded recursion. -- Source cause: both foreground and background redirect paths set `tx.redirecting = true`, await `router.navigate(...)`, and clear the marker only on normal fulfillment. `loadClientRoute` treats any marked prior owner as chain authority at transaction construction. A target-build throw therefore leaves a stale authority marker on the old transaction. -- Independent reviews: client-lane, build/API, and adapters reviewers independently accepted the authority/finally analysis; the isolated-test reviewer validated the fresh-chain control and one-hop budget loss. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED**. - -## Prior-review coverage/audit items - -### G01 — child-local `loaderDeps` identity coverage - -- Prior assessment: no known production bug, but no direct test proves stable parent identity plus changed child-only deps reuses only the parent context. -- Focused passing test: `packages/router-core/tests/pr-7805-review-c-child-loader-deps-reuse.test.ts`. Its corrected setup proves the cached parent is a successful preload with a numeric `_preloadContext`, the planned navigation retains the exact parent match ID/donor, parent `beforeLoad` runs only with `preload:true`, child `beforeLoad` runs for versions 1 and 2 with `[true, false]`, the child loader runs twice, and final context/data are version 2. -- A first draft failed only because it incorrectly read a nonexistent `deps` argument from `beforeLoad`; that harness error was corrected and is not production evidence. -- This remains a test-only gap, not a production defect. Retain the passing focused test in the eventual test patch. -- Independent reviews: root authored/corrected and ran the case; client-lane reviewer independently confirmed its stable-parent/changed-child contract and complement to the inverse reuse test; adapters reviewer independently traced the cached donor, call sequence, docs contract, and committed context/data oracles. All accept it as durable missing coverage. -- Status: **COVERAGE-VALIDATED**. - -### D01 — compile-time `isServer` conditional exports and dead-code elimination - -- User-provided invariant: production `isServer` is a compile constant and bundlers are expected to eliminate the unreachable lane. -- Required audit matrix: - - production browser resolves literal `false` and excludes server-lane implementation/sentinels; - - production server resolves literal `true` and excludes unjustified client-only implementation where the public surface permits; - - development resolves `undefined` and runtime-falls back to `router.isServer`, intentionally retaining both lanes; - - Node conditions plus Vite/Rollup/Rolldown/esbuild resolution do not reorder the condition mapping. -- Aggregate bundle size is insufficient: inspect exact artifacts/symbols and execute lane-selection smoke tests. -- Local primary evidence: a production Vite 8/Rolldown server bundle (`ssr: true`, Node conditions, `ssr.noExternal: true`, production define) correctly includes the server lane, but also retains `load-client.js` with approximately 29.6 kB unminified rendered code and all three rendered exports (`transferMatchResources`, `loadClientRoute`, `preloadClientRoute`). Output sentinels include `executeClientLane`, `preloadClientRoute`, and `Redirect cycle detected`. An esbuild production/Node control independently retains the client lane; a production browser control retains only the client lane; a development control intentionally retains both. -- Source cause: `RouterCore` statically imports client-lane functions directly, and ordinary bundlers do not propagate the condition-selected literal far enough across that module boundary to prune those imported declarations. Runtime dispatch is correct; the verified defect is server-artifact reachability/DCE, not wrong lane execution. -- Focused regression: `packages/router-core/tests/pr-7805-review-c-server-dce.test.ts` now fails on the intended production Vite SSR module-graph assertion: `load-server.js` is present and exports `loadServerRoute`, but `load-client.js` is also rendered with exports `transferMatchResources`, `loadClientRoute`, and `preloadClientRoute`. The initial `import.meta.url` harness failure was corrected and is excluded from evidence. -- Independent reviews: build/API primary reproduced Vite and esbuild artifacts; adapters reviewer independently confirmed conditional export resolution, package `sideEffects:false`, and the documented compile-constant DCE contract; client-lane reviewer independently traced static imports/references and audited the focused Vite test's strengths and remaining matrix risks. All three accept this as a production-server artifact/DCE defect, not a runtime-dispatch defect. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED**. - -## Newly discovered hypotheses - -Add new candidates here before beginning a lengthy investigation. Each must receive a new stable ID and remain in the ledger even if rejected. - -### N01 — Vue global error boundary reset key is non-reactive - -- Candidate: `MatchesInner` derives its global boundary `resetKey` through `Vue.computed(() => router.stores.matchStores.get(matchId)?.get().fetchCount)`. A raw TanStack Store `Atom.get()` does not establish Vue reactivity; the same-route root `matchId` remains stable, and after the boundary catches a render failure its failed subtree no longer supplies incidental subscriptions. A later `router.invalidate()` increments `fetchCount` but may never invalidate the computed key, leaving the fallback permanently mounted. -- Focused test: `packages/vue-router/tests/pr-7805-review-global-boundary-reset.test.tsx`. It fails by timing out while looking for `Recovered page`; the global `transient render failure` fallback remains mounted. A control proves the same root match's `fetchCount` increased after `router.invalidate()`, isolating the missing boundary reset from a failed reload. -- Required proof: focused Vue run fails exactly at recovered content, compare a `useStore`-backed selector control, and obtain two independent reviews of boundary ownership/reset semantics and the same-route setup. -- Independent reviews: adapters primary reproduction; client-lane reviewer independently confirmed base's reactive reset key, raw Atom behavior, and CatchBoundary semantics; build/API reviewer independently validated the same-ID dependency graph and recommended collision-safe ID+generation selection. All three accept the failure. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED**. - -### N02 — planning-time redirects bypass the transaction redirect budget - -- Candidate: a redirect thrown while `matchRoutes` runs route `context()` is followed by `loadClientRoute` before a transaction exists, so it does not establish or increment the redirect-depth authority later enforced by lane reduction. A self redirect therefore recurses without reaching the finite `Redirect cycle detected` result. -- Focused regression: `packages/router-core/tests/pr-7805-review-n02-planning-redirect-budget.test.ts`. The safe harness subscribes history like a mounted adapter, permits 21 self redirects from route `context()`, and then throws an ordinary bounded sentinel. It fails because the sentinel is reached; a compliant twenty-hop chain would stop at 21 context calls without entering the bailout. The earlier OOM reproduction is explicitly excluded from evidence. -- Source cause: the `matchRoutes` catch in `loadClientRoute` follows a planning redirect before constructing `LoadTransaction`, and the recursive navigation has neither a redirect-depth parameter nor an authority transaction to inherit. Loader/beforeLoad redirects are reduced after transaction creation and therefore do use `tx.redirects`. -- Independent reviews: client-lane, build/API, and adapters reviewers independently traced preflight/planning ownership; the isolated-test reviewer validated mounted history behavior, the finite cap, and the negative sentinel oracle. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED**. - -### N03 — late preload child may outlive its semantic parent generation - -- Candidate: a child preload reads parent revision 1 through `parentMatchPromise`; the active parent is then invalidated and commits revision 2 before the child finishes. The old preload must not publish/cache child data derived from revision 1 for later navigation. -- Focused regressions: `packages/router-core/tests/pr-7805-review-n03-preload-parent-generation.test.ts` contains two independently failing manifestations. In the late-publication case, a child preload observes parent revision 1, the parent commits revision 2, and the stale child is nevertheless cached and later navigated with one child call/data revision 1. In the in-flight case, the later navigation joins the same child flight keyed only by match ID and likewise publishes revision 1. Both expect a second child call and revision 2. -- Source cause: `LoaderFlight` and `router._flights` identify work only by child match ID; they carry no semantic-parent generation. Preload cache CAS checks active child IDs and cache object identity but not ancestry generation. Stable params/search/deps therefore allow a child result derived from an obsolete parent object to join or publish after the parent reloads under the same ID. -- Independent reviews: client-lane, build/API, and adapters reviewers independently accepted the parent-generation invariant and both source paths; the isolated-test reviewer corrected the call-count oracle and reproduced both failures separately. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED**. - -### N04 — superseded load awaits an obsolete component preload - -- Candidate: a navigation blocks in a component's `preload`; a successor navigation commits a different route, but the first public load promise may remain unresolved until the obsolete component preload settles even though it can no longer publish. -- Focused regression: `packages/router-core/tests/pr-7805-review-n04-obsolete-component-preload.test.ts`. `/first` blocks forever in its component's `preload`; `/second` supersedes and commits, but the first public `router.load()` promise remains unsettled until the obsolete preload is manually released. The failure is `false` versus expected `true` after a successor commit and macrotask. -- Source cause: loader outcomes are abort-raced via `waitFor`, but `task.ready` directly awaits `loadRouteChunk(route)` through `chunkFailure`. `reduceLane` awaits that readiness even after the transaction controller is aborted, so `tx.done`, `loadClientRoute`, and callers remain coupled to an unabortable result that can no longer publish. -- Independent reviews: client-lane, build/API, and adapters reviewers independently traced supersession and readiness ownership; the isolated-test reviewer confirmed that public superseded loads are expected to settle once the current successor owns publication, while the underlying shared import may safely continue for cache reuse. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED**. - -### N05 — stale pre-commit background candidate leaks its flight lease - -- Candidate: a foreground transaction can finish a stale reload into a private `lane.background[].candidate`, then lose ownership while awaiting `startViewTransition` before commit. The stale exits release only `result.matches`; the candidate is not in that array, and `runBackground` (whose losing CAS would release it) has not started yet. -- Source path: `createLoaderTask` creates the separate candidate and flight lease around `packages/router-core/src/load-client.ts:577`; stale exits around 1220 and 1231 transfer only foreground matches; supersession around 1395 transfers only the previous owner's matches; `runBackground` cleanup around 1146 is unreachable before commit. A zero lease is what aborts/removes the shared flight. -- Focused regression: `packages/router-core/tests/pr-7805-review-n05-background-candidate-lease.test.ts`. It settles a stale reload into a private background candidate, blocks before commit, commits `/other`, drains the losing load, and fails because the candidate loader's public abort signal remains live. A settled flight keeps its controller live until its last lease is released, making the signal a direct ownership oracle. -- Source cause: the candidate is stored only in `result.background[].candidate`. Stale exits before `commit` release `result.matches`, and supersession releases `previousOwner.matches`; neither includes private candidates. `runBackground` owns the later cleanup, but it is never scheduled when currentness is lost before the commit closure runs. -- Independent reviews: client-lane, build/API, and adapters reviewers independently audited candidate creation/lease transfer and the stale exits; the isolated-test reviewer reproduced the leaked signal and completed the control/error-exit symmetry audit. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED**. - -### N06 — global error boundary reset key may miss child-only background recovery - -- Candidate: React and Solid global CatchBoundary reset keys are derived from the root match identity/generation; Vue's N01 repair is likely to use the same shape. A child-only stale-while-revalidate success in `runBackground` replaces only the child candidate in `base.slice()`, preserving the exact root object and its `fetchCount`. If stale child rendering latches the global boundary and the background child later becomes healthy, the committed recovery may not change the reset key. -- Source distinction: a route-local child boundary observes the child's generation and is not the target. The reproduction intentionally omits a route error component so the global boundary owns the thrown render error. Base/main keyed the global boundary with reactive public `loadedAt`, but the exact child-only SWR publication introduced/exercised here was not reproduced on base and base did not advance `loadedAt` for a later SWR completion. N06 is therefore a current-head correctness failure, not evidence that public `loadedAt` historically had background-generation semantics. -- Focused regression: `packages/react-router/tests/pr-7805-review-global-boundary-background-reset.test.tsx`. The hardened run fails only at finding `Recovered child revision 2`. Before that assertion it proves exactly two loader calls; foreground stale data 1; background child data 2; unchanged root object and `fetchCount`; replaced child object with `fetchCount + 1`; idle `/child`; and no unexpected warnings/errors. The global fallback remains latched. -- Independent reviews: adapters primary authored and source-traced the candidate; isolated client reviewer independently confirmed global (not route-local) boundary ownership and the child-only `runBackground` publication; client-lane reviewer independently audited `CatchBoundary` reset semantics and the hardened controls; root ran and inspected both versions. All accept the defect across the root-only key shape used by React, Solid, and Vue. -- Repair direction: use one private reactive committed-match-tree revision that changes for every accepted foreground/background semantic publication, but not pending presentation, preload/cache-only, or losing lanes. Coordinate N01 with that signal, while preserving P02's separate historical `loadedAt` contract. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED**. - -### N07 — functional SSR failure may erase context seen by the selected boundary - -- Candidate: `executeServerLane` copies matches with `context: {}` before `contextualize`. That function invokes/awaits a functional `ssr()` selector before rebuilding `match.context` from router, parent, and `__routeContext`. If the selector throws, the error match may retain `{}` even after P11 makes its lazy boundary ready. A boundary component, boundary `head`, or `useRouteContext` could therefore observe missing router/route context. -- Base comparison: base/main kept the route-matched context through the serial failure path. The focused reproduction renders through the public React server request path and public route-context hook rather than relying on private match fields. -- Focused regression: `packages/react-router/tests/pr-7805-review-server-context-frontier.test.tsx`, sync and async N07 cases. Both return the correct 500 and render the eager route boundary with the correct selector error, but fail because the boundary receives `|||||no-failing-beforeLoad` instead of router context, layout route context, completed ancestor `beforeLoad` context, and failing-route static route context. The failing route's own `beforeLoad` remains at exactly zero calls, proving the expected fix must not fabricate it. The eager boundary isolates this from P11's lazy-boundary readiness defect. -- Source cause: `executeServerLane` resets every planned match to `context: {}`; `contextualize` awaits `resolveSsr(route.options.ssr, ...)` before assigning the current match's parent + `__routeContext` context. A synchronous throw or rejected selector exits before assignment. Completed ancestors have valid context in the serial parent chain, but the selected failure match never receives it. -- Independent reviews: adapters, isolated-server/test, client-transaction/server, and root reviews independently traced the ordering and accepted the public boundary contract; three separate test authors converged on the same eager-boundary isolation before consolidation. -- Acceptance-oracle correction: the final feasibility audit rejected returned redirect/cancellation selector controls because a functional `ssr()` selector may return only `undefined | SSROption`. The plan now covers ordinary sync throws/async rejections and only supported thrown/rejected redirect/not-found terminal sentinels; it does not invent a broader selector API. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED**. - -### N08 — hydrated unresolved frontier may retain incomplete parent context - -- Candidate: `hydrate.ts` includes the first serialized `ssr:false` or `pending` match in `presented` but not `committed`; context rebuilding iterates only the committed prefix. The visible frontier fallback may retain context from initial client `matchRoutes`, before serialized parent `__beforeLoadContext` is installed, while the server gave that frontier the complete parent context. -- Focused regression: `packages/react-router/tests/pr-7805-review-server-context-frontier.test.tsx`, N08 case. It runs a real server router load, proves the `ssr:false` child loader is skipped, proves the server pending match/fallback contain `server-authenticated|child-route-context`, dehydrates the real bootstrap, and calls client `hydrate`. Before mounting, the presented child remains `status:'pending'`/`ssr:false` but fails because its context contains only `childToken`; the transported parent `auth` value is absent. A gated client loader and hydration diagnostic checks remain after the core assertion so the eventual repair must also preserve DOM hydration. -- Source cause: hydration reconstructs context only while iterating `committed`. It deliberately includes one non-committed `ssr:false`/pending frontier in `presented`, but that match keeps its initial client `matchRoutes` context from before serialized ancestor `__beforeLoadContext` was installed. -- Contract boundary: semantic adoption, chunks, head/scripts, and resolved location must remain capped at the committed prefix; only the already-presented frontier needs a context projection from the rebuilt parent plus its existing `__routeContext`/serialized `__beforeLoadContext`. Client replanning still owns loader execution and terminal semantics. -- Independent reviews: adapters, isolated-server/test, client-transaction/server, and root reviews independently accepted the server/client consistency contract and the prefix-vs-presentation distinction; three independently authored real dehydration/hydration proofs converged before consolidation. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED**. - -### N09 — route-level component preload memoization was removed - -- Candidate: the old `loadRouteChunk` used `_componentsLoaded` and `_componentsPromise` to call the normal `component`/`pendingComponent` preloads once and coalesce concurrent callers. The rewrite deliberately calls their public `.preload()` methods again for every normal `loadRouteChunk`, including every waiter joined to one lazy-route import. -- Counterevidence/declared contract: the new `packages/router-core/INTERNALS.md` explicitly says there is deliberately no component-promise cache because dynamic imports and framework wrappers already cache module work. The React/Solid/Vue `lazyRouteComponent` implementations do coalesce an in-flight import. The new component-preload retry regression also depends on core re-invoking `.preload()` after failure, so restoring the old latch would regress retry semantics. -- Contract check performed: reviewers separately compared custom `AsyncRouteComponent.preload`, sequential success, concurrent calls, and retry-after-rejection to determine whether the old route-level once/deduplication behavior was compatibility surface. The result is recorded in the falsification paragraph below; no open investigation remains. -- Independent falsification: root, adapters, and isolated client reviewers independently compared base, current wrappers, public docs/types, and the new retry contract. Base suppressed later normal route-chunk passes after success but permanently latched a rejected `_componentsPromise`; it did not establish a general public at-most-once contract. Direct framework-wrapper `.preload()` calls can already reinvoke their importer after success, while in-flight calls coalesce and native module loading caches success. The public `AsyncRouteComponent` surface promises only a callable promise-returning preload, not call-count semantics. -- Non-blocking note: document that custom preload functions must tolerate repeated calls, and retain wrapper-level concurrent coalescing plus retry-after-rejection coverage. A supported component demonstrating duplicated semantic/network harm could reopen this as compatibility/performance policy, but callback count alone is not a correctness oracle. -- Status: **NOT-VALIDATED**. Do not add N09 to `PLAN.md` and do not write a once-only failing test that would reintroduce base's permanent rejection latch. - -### N10 — same-ID flight join may ignore the route's freshly rerun own context - -- Failure: `packages/router-core/tests/pr-7805-review-n10-inflight-preload-own-context.test.ts` starts a gated child preload under stable ancestry and `beforeLoad` context version 1, then starts navigation to the same match ID while that loader is pending. Navigation correctly reruns `beforeLoad` and produces context version 2, but the child loader runs only once under version 1 and final state combines context version 2 with loader data version 1. The focused isolated Nx run fails on the exact two-loader/final-v2 assertions, with no type or setup errors. -- Source cause: `executeClientLane` provisionally attaches `router._flights.get(match.id)` before contextualization. The navigation then computes its fresh route/beforeLoad context, but `loadResource` accepts the already-attached flight by ID and joins its v1 result. Match ID covers route/path/loaderDeps, not route-context or beforeLoad-context provenance, so identity is not a loader-input compatibility proof. -- Distinction from N03: N03 changes an accepted parent generation. N10 keeps the parent stable and changes the child's own post-contextualization inputs. A repair keyed only by parent generation therefore leaves this independently reproduced context/data split. -- Contract: the preload is still pending, so it cannot donate completed beforeLoad context. Public loader semantics promise that `loader({context})` receives the accepted route and beforeLoad context for that load. Once navigation has rerun context to version 2, it may not publish data calculated from version 1 merely because the match ID is unchanged. The effective-input provenance must cover both `__routeContext` and `__beforeLoadContext`. -- Independent reviews: the isolated test author reproduced the failure and checked the public context/preload contract; the final-plan auditor independently traced the provisional join; the artifact/source auditor independently derived the same context/data mismatch; root source review confirmed the ID omission and final publication path. All accept the exact failing oracle. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED**. - -## HMR and test-quality hypotheses - -### H01 — explicit source-chained lazy importer may not refresh under HMR - -- Candidate: `handleRouteUpdate` clears `oldRoute._lazy` but intentionally does not copy `newRoute.lazyFn`. This is correct for generator-owned `.lazy()` mutation because the fresh source export does not contain that generated importer and the live route should retain its generator wiring. A source file that explicitly returns `createFileRoute(...)(...).lazy(newImporter)`, however, may keep the old importer after HMR. -- Focused regression: `packages/router-plugin/tests/handle-route-update.test.ts`, `uses the new source-chained lazy importer during a hot refresh`. It performs a real client load with `oldImporter`, hot-updates the route to `.lazy(newImporter)`, and lets the real `_refreshRoute` rematerialize. It fails because `hotRoute.lazyFn` is still the old function; the old importer is invoked twice and the new importer zero times (the first identity assertion reports the failure before the call-count assertions). -- Source cause: public `Route.lazy()` stores its argument on `route.lazyFn`, outside `route.options`. `handleRouteUpdate` copies only `newRoute.options`, clears `oldRoute._lazy`, and refreshes. Clearing the materialized value therefore reloads through stale `oldRoute.lazyFn`. -- Independent reviews: build/HMR primary, client-lane reviewer, and adapters reviewer independently confirmed the public chaining contract, real refresh path, and missing field transfer. All also flag a provenance constraint: generated route trees install their own lazy importer on the live route while the freshly imported source route lacks one, so unconditional `oldRoute.lazyFn = newRoute.lazyFn` would break generated lazy routes and cannot detect explicit source removal. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED**. - -### T01 — Vue root pending test has no pending assertion - -- `packages/vue-router/tests/Matches.test.tsx`, test named `should show pendingComponent of root route`, only waits for final content; it never asserts either the root or default pending component. -- Its explanatory comments describe Vue as only handling thrown promises and unable to show the initial pending state, while this PR changed `MatchInner` to render `status === 'pending'` directly. The name/comments therefore do not match the oracle or current implementation. -- Required hardening: gate the loader, assert the intended root pending UI (and exclusion of the default fallback if that distinction matters), release, then assert final content and event ordering. -- Independent reviews: build/test primary found the mismatch; adapters reviewer independently checked the new direct-pending render path; client-lane reviewer independently confirmed the test never queries either pending component. All agree the test passes if pending rendering is deleted. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED TEST-GAP**; this does not prove Vue pending rendering currently fails. - -### T02 — preload-redirection selector-count tests do not isolate preload - -- React, Solid, and Vue `store-updates-during-navigation.test.tsx` variants immediately capture selector call counts after `render()` without awaiting initial idle/resolved `/`. The measured delta for `preload redirect` can include initial provider-load publications. Expected calls were rebaselined from 1 to 2 even though the test's own rule says increases require investigation. -- Required hardening: await initial content plus router idle/resolved location, clear/baseline the selector spy, execute only the preload, then assert the active semantic `RouterState` snapshot remains unchanged. Treat exact render/call count as a secondary performance signal, not the primary correctness oracle. -- Acceptance-oracle correction: the final feasibility audit traced the actual redirecting preload contract. `/posts` executes and redirects once, the preload follows it and publishes one successful non-active `/other` match to `router.stores.cachedMatches`, and no redirect object is retained in public `RouterState`. The plan therefore observes that exact cache-store publication separately while requiring zero aggregate-state notifications. -- Independent reviews: build/test primary identified the unexplained rebaseline; adapters and client-lane reviewers independently traced each framework's setup and confirmed it returns immediately after provider render while initial `router.load()` is still scheduled/running. All agree `+2` is not attributable to preload alone. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED BOGUS-ORACLE**; this is not proof of excess production notifications until the isolated test is rerun. - -### T03 — issue 7120 E2E lacks a View Transition/stale-frame oracle - -- `e2e/react-router/issue-7120/tests/issue-7120.repro.spec.ts` proves eventual `/posts`, pending disappearance, and no logged errors, but does not assert that `document.startViewTransition` exists/was invoked or that stale Home content never appears transiently. The test could pass while skipping the regression's named View Transition path. -- Required hardening: instrument/wrap `startViewTransition` before application code, assert invocation/update completion, and record DOM frames/mutations from pending through target to prove no stale Home/old match commits. -- Independent reviews: build/test primary audited the new E2E against the issue path; root independently traced its assertions and fixture; adapters reviewer independently confirmed that both a missing View Transition implementation and a transient stale commit satisfy every current assertion. All three agree the test is non-diagnostic for its named regression. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED TEST-GAP**. This is a test-suite defect, not independent proof that the production bug remains. - -### T04 — issue 7457 E2E does not detect transient blank presentation - -- `e2e/react-router/issue-7457/tests/issue-7457.repro.spec.ts` proves the pending component mounted at some point, eventual `/another`, and no errors. It does not sample the interval between pending and target, so a blank frame—or transient index content—still passes a test named `does not blank`. -- Required hardening: install a pre-navigation MutationObserver/requestAnimationFrame log and assert every observed presentation contains either pending or target, never the index route and never an empty app root. -- Independent reviews: build/test primary identified the endpoint-only oracle; root independently inspected the fixture and assertions; adapters reviewer independently demonstrated that `__pendingSeen === true` plus final target visibility says nothing about intervening presentations. All three agree the current test cannot catch the named blank-frame regression. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED TEST-GAP**. This is a test-suite defect, not independent proof that the production bug remains. - -### T05 — Solid issue 7283 does not assert `pendingMinMs` - -- The route configures `pendingMinMs: 1500` and records event timestamps, but `issue-7283-dev-hydration.spec.ts` discards timestamps and checks only `pending-mounted -> pending-unmounted -> target-mounted`. It would pass if the minimum duration were ignored. -- Required hardening: retain timestamps and assert pending visible duration against 1500 ms with a documented scheduling tolerance, while keeping the existing hydration-error and final-target assertions. -- Independent reviews: build/test primary found the discarded timing signal; root independently verified the route constant and event mapping; adapters reviewer independently confirmed that an arbitrarily short pending flash satisfies the current order-only assertion. All three agree the configured minimum is untested. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED TEST-GAP**. This is a test-suite defect, not evidence that `pendingMinMs` currently fails at runtime. - -### T06 — existing generic lazy retry tests miss recognized module errors - -- Existing React/Solid/Vue component-preload retry tests throw generic `component download failed` errors, so they do not enter module-not-found reload/session-storage behavior. This allowed P06 to pass unnoticed. -- The retained P06 failing regression now directly covers the recognized branch; two independently authored drafts were consolidated. Retain it and add an integration-level route/error-boundary version when implementing P06. -- Status: **VERIFIED WITH P06**. - -### T07 — preloaded-mount race test documents but does not reproduce original race - -- React `preloaded-mount-resolution.test.tsx` explicitly says the original timing race is nondeterministic and pins only the settled-before-mount contract, delegating deterministic guarding to a benchmark. This is honest but leaves the original interleaving without a deterministic unit regression. -- Required proof/hardening: replace timing with controlled commit/mount gates or expose a deterministic scheduler seam; otherwise keep this as a documented coverage caveat, not evidence the race itself is fixed. -- Independent reviews: build/test primary, adapters reviewer, and client-lane reviewer separately confirmed the current case strongly covers “settled before mount” but cannot force “settles during mount/effect batching,” which was the original race. All retain the current test and classify only the missing deterministic case. -- Scheduler-oracle correction: two final independent audits rejected an earlier mock schedule that let loader microtasks run before the initial MatchesInner layout effect. The final plan now executes all three initial queued layout callbacks synchronously in real commit order, starts the initial load from Transitioner's own mount callback, lets the initial acknowledgement harmlessly run before any final transition waiter exists, and only then releases the fast loader in the post-layout microtask batch. The next match commit's acknowledgement is the one that must settle the captured direct `router.load()` promise; no `commitLocationPromise` is created. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED COVERAGE-GAP**; no runtime regression is claimed. - -### T08 — pending replacement coverage is uneven across adapters - -- React and Solid cover child/root pending-promise replacement; Vue covers root only. Solid has an explicit same-route stale-content/no-fallback test, while React/Vue lack direct parity. -- Required hardening: add a table-equivalent matrix for root/child replacement, same-route stale-content retention, and no-fallback behavior across all three adapters, using framework-appropriate render flushes. -- Independent reviews: build/test primary, adapters reviewer, and client-lane reviewer independently enumerated current HEAD and reached the same framework matrix. All classify this as factual coverage parity debt, not evidence that uncovered adapters are broken. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED PARITY-GAP**. - -### T09 — React issue-7051 tests leave transaction setup/settlement ambiguous - -- `issue-7051-force-pending-suspense.test.tsx` renders `RouterProvider` and then explicitly calls `router.load()` instead of first awaiting provider-driven initial idle, allowing overlapping initial loads to affect the force-pending setup. Its second case discards the `/first` navigation promise and awaits only `/second`, so a superseded predecessor can remain stuck without failing the test. -- Required hardening: await initial UI/idle without a second explicit load; capture both navigation promises; assert predecessor remains pending only while the successor is active and drain both after successor settlement, with bounded cleanup. -- Independent reviews: adapters reviewer found the setup; root independently confirmed the immediate explicit load and discarded promise; isolated client reviewer independently traced provider effect startup and proved both the redundant initial load and unobserved predecessor settlement can regress without failing current assertions. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED TEST-GAP**. This is not evidence that current production settlement hangs; it establishes that the added regressions do not exclude that failure. - -### T10 — React listener-error test does not prove the throwing listener executed - -- `transitioner-listener-errors.test.tsx` registers a listener that should throw for `/first`, but records neither invocation nor the thrown error. Later-listener and route-hook assertions all pass if the first subscriber is accidentally skipped, so the test cannot distinguish “error was isolated” from “throwing callback never ran.” -- Required hardening: wrap the throwing callback in a spy/log, assert its exact `/first` event before/alongside the later subscriber, and assert the router reports/contains the deliberate exception according to the emitter contract without swallowing unrelated errors. -- Independent reviews: adapters reviewer found the missing oracle; root independently confirmed no assertion reaches the first listener; isolated client reviewer independently proved every current UI/hook/later-listener assertion still passes if the first subscriber is deleted or skipped. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED BOGUS-ORACLE**. The production emitter currently catches and reports subscriber errors, but this test never proves that path ran. - -### T11 — Vue pending-loader abort test is slow and under-specified - -- `packages/vue-router/tests/loaders.test.tsx`, `navigating away from pending UI aborts its loader`, waits roughly three seconds of real timers, asserts only that pending and abort callbacks ran at least once, and does not capture the signal, exact loader/abort counts, predecessor promise, final idle/resolved location, pending removal, or absence of stale Foo UI. -- Required hardening: replace sleeps with controlled start/reveal/abort promises or fake time, retain both navigation promises/signals, assert exact once abort plus no error publication, drain both, and assert idle `/bar`, pending/Foo absence, and Bar presence. -- Independent reviews: adapters reviewer found the weak slow test; root independently confirmed its real-timer and at-least-once oracles; isolated client reviewer independently measured the 30 × `WAIT_TIME` pre-navigation sleep and confirmed the test observes neither exact abort ownership nor either public navigation's settlement. -- Acceptance-oracle correction: the final feasibility audit confirmed that a fulfilled loader may still be retained by its committed match's flight. The adjacent control therefore requires the signal to stay live while Foo owns that match, then abort exactly once when Bar unloads Foo and releases the final lease; it does not incorrectly equate loader completion with permanent signal immunity. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED TEST-GAP**. This is a deterministic-test and liveness-oracle defect, not proof that Vue currently aborts incorrectly. - -### T12 — pending-preload reuse test codifies a context-insensitive loader join - -- `packages/router-core/tests/preload-beforeload-reuse.test.ts`, `keeps beforeLoad independent while joining a pending preload loader`, expects two `beforeLoad` calls but only one loader call. Its loader returns a shared string without reading `context`, so it cannot detect the impossible state where navigation publishes fresh context beside data computed under the preload's older context. -- N10 supplies the negative proof: under the same pending-preload shape, a loader that snapshots its public context exposes version-1 data beside version-2 match context. Thus the existing one-loader expectation is not merely incomplete; it encodes the unsafe join as success. -- Required hardening: split safe reuse from incompatible reuse. Keep a one-loader control only when navigation adopts the same completed semantic input generation. For a still-pending preload whose own route/beforeLoad context is rerun, require a second loader and coherent final version-2 context/data. Gate both generations and drain them in `finally`. -- Independent reviews: isolated client/test, final-plan, artifact/source, and root reviews independently compared the existing oracle to N10's public-context reproduction. All agree the context-insensitive return value masks the defect. -- Repair plan: see `PLAN.md`. -- Status: **VERIFIED BOGUS-ORACLE**; N10 is the production defect, not a second runtime finding. - -## Post-optimization preservation audit — 2026-07-18 - -After the PR-scoped bundle-size changes, every retained review regression was rerun to prove that optimization work had not silently fixed, masked, or overwritten an outstanding PR issue: - -- Router Core: 14 review files produced 12 failing files and two passing controls; 13 cases failed and three passed, including the P02 type fixture's four missing-state-field diagnostics. -- React Router: five review files retained eight failing cases. -- Vue Router: two review files retained two failing cases. -- Solid Router: one review file retained one failing case. -- Router plugin/HMR: H01 retained its single failing source-chained-importer case. - -The final ledger therefore remains **25 failing cases in 21 failing files**, with all failures attributable to their previously documented behavioral oracle. G01 and P09 remain passing controls. No issue status or repair-plan eligibility changed, and no production defect in this ledger was fixed by the bundle-size work. - -## Review coverage inventory - -This inventory reconciles the complete 210-file `base...head` diff. “Reviewed” means the changed source/assertions were compared with their callers, lifecycle contract, and adjacent tests; it does not mean every test was executed. - -- **Router core production (review complete):** `Matches.ts`, `router.ts`, `stores.ts`, `route.ts`, `redirect.ts`, `route-chunks.ts`, all three `isServer` condition modules, `load-client.ts`, `load-server.ts`, `hydrate.ts`, generic SSR client/server/request-handler code, deletion of `load-matches.ts`, and the new `INTERNALS.md`. Client transactions received overlapping client-lane, build/API, adapters, isolated-test, and root audits. Server/hydration received the same overlapping treatment; N07 and N08 were validated with the consolidated real SSR/dehydration/hydration tests, while N09 was independently rejected. -- **React production (reviewed):** `Match`, `Matches`, `Transitioner`, `lazyRouteComponent`, both SSR renderers, and package exports/dependencies. Findings: P03, P06, P07, N06 plus React integration evidence for core N07/N08; no other production candidate survived review. -- **Solid production (reviewed):** `ClientOnly`, Match/Matches/Transitioner, lazy retry, match context/stores/useMatch, and both SSR renderers. Findings: P05/P07 and structural N06 exposure; no other production candidate survived review. -- **Vue production (reviewed):** Match/Matches/Transitioner, lazy retry, match context/stores/useMatch, and both SSR renderers. Findings: P05/P07/N01 and structural N06 exposure; no other production candidate survived review. -- **Router plugin/HMR (reviewed):** handler source, Vite/Webpack injection, all changed snapshots, handler tests, and route-generator lazy wiring relevant to provenance. Finding: H01. -- **Secondary production/config (reviewed):** Start generic redirect short-circuit, devtools age/state migration, memory benchmark change, package manifests/lockfile, preload documentation, scroll restoration, special-character route, selective-SSR fixtures, generated route trees, and the issue-7120/7457 fixtures/config. Findings are limited to T03-T05's test oracles; build/API review found the implementation/config changes otherwise coherent. -- **Router-core tests (reviewed by behavior family):** adversarial transaction/currentness, background assets/trim, chunks and failure lifecycle, granular stores/callbacks, hydration prefix/currentness/assets/boundaries, preload cache/adoption/signals/context, redirect/planning, server selection/errors/headers, and supersession. New focused tests in this worktree cover every verified production issue; G01 and P09 are passing controls. Consolidated N07/N08 integration tests fail at both the core state and public rendering oracles without unhandled diagnostics. -- **Adapter tests (review complete):** pending/root/child/minimum/replacement, hydration, error/not-found boundaries, lazy retries/chunk errors, loader aborts, redirects, transition acknowledgements/remount/listener errors, state-selector counts, links/router/useNavigate, and server rendering. Verified weaknesses are T01-T11 as categorized above; no additional adapter production candidate survived independent review. -- **E2E tests (reviewed):** issue 7120, issue 7457, React Start #4614/special characters/selective SSR, Solid selective-SSR #7283, and scroll restoration. T03-T05 require hardening; the remaining scenarios were accepted by build/API and adapter audits. - -The diff list used for reconciliation is `git diff --name-status 0b178a79...6683863a`; it contains 71 router-core, 34 React, 24 Solid, 23 Vue, 13 router-plugin, 39 E2E, two devtools, and four documentation/benchmark/Start/lockfile files. - -## Worktree notes - -- Immediately after switching from detached `4c425e0` to the PR branch, 14 generated benchmark `routeTree.gen.ts` files briefly appeared modified only by generated ordering. They later disappeared from `git status`; none is currently modified, staged, or used as review evidence. -- Review-created regression tests and `ISSUES.md`/`PLAN.md` are intentional local changes. Production-source fixes are forbidden for this task. diff --git a/PLAN.md b/PLAN.md deleted file mode 100644 index a434863c02..0000000000 --- a/PLAN.md +++ /dev/null @@ -1,838 +0,0 @@ -# PR #7805 outstanding-issue fix plan - -Target under review: `6683863a75a46297765b288957fccd147006ef0c`. - -This file intentionally contains no production changes. A production issue is added here only after a focused test fails on the PR head for the claimed reason and three independent reviewers validate the contract, reproduction, impact, and proposed repair direction. A test-suite repair is added only after three reviewers prove its false-positive/missing-oracle window; it remains explicitly test-only until its hardened oracle fails under the named negative mutation. See `ISSUES.md` for unverified and rejected findings. - -## Verified issues - -### P02 — Restore the public `RouterState` compatibility surface - -**Severity:** blocker for a v1 release. **Validated by:** failing exported-type and runtime tests plus three independent public-API/semver reviews. - -#### Observable failure - -`packages/router-core/tests/pr-7805-review-c-router-state-compat.test-d.ts` no longer compiles references to `RouterState.loadedAt`, `isTransitioning`, `statusCode`, and `redirect`. The runtime companion confirms all four are absent from `router.state`. Base/main exported and materialized all four; adapter `useRouterState` APIs expose that type, public docs still name `isTransitioning`, and this PR has no major-version migration or changeset. - -#### Required implementation - -1. Restore the four properties, with their base types, to `RouterState` in `packages/router-core/src/router.ts`: - - `loadedAt: number`; - - `isTransitioning: boolean`; - - `statusCode: number`; - - `redirect?: AnyRedirect`. -2. Restore compatibility stores in `packages/router-core/src/stores.ts` and include them in `RouterStores` and the aggregate `__store`. Initialize them to the base values in `getInitialRouterState`: `0`, `false`, `200`, and `undefined`. -3. Reproduce the base compatibility semantics at the new lane's winning foreground/server load boundary rather than inventing background-publication semantics: - - reset `statusCode` to 200 when the current load enters pending and publish its terminal 200/404/500/redirect code only from the current load; - - expose the exact `AnyRedirect` object through `redirect` when base's terminal catch classifies a redirect; this is the native `Response` instance augmented with router `.options`, so preserve its identity, status, headers, and options. Do not proactively clear it on an ordinary successful client load, because base did not do so, while a later terminal catch may replace it with that catch's redirect-or-undefined value; - - assign `loadedAt = Date.now()` exactly once at the winning foreground/server load's first accepted on-ready/presentation commit, as base did; do not derive it by incrementing the prior value. A later SWR/background completion for that load and N06's child-only background publication must not write this public clock; - - preserve the last committed values while a superseded transaction is discarded; stale, preload/cache-only, and losing background lanes must not write them. -4. Restore `isTransitioning` with its exact base writer semantics. Vue's `Transitioner` toggles the router store and must clear only its current owner on completion/unmount; React kept transition state locally and Solid did not write this compatibility store, so do not make those adapters toggle the public field as an unrelated behavior change. Its initial value remains false everywhere. -5. Keep the granular stores and the compatibility aggregate coherent inside the same batches. Do not rebuild a separate state object whose fields can lag the match/location stores. -6. If maintainers intentionally want removal instead, move it to an explicitly approved major-version migration with docs, changeset, deprecations, and consumer migration tests; silently weakening the regression tests is not an acceptable v1 fix. - -#### Tests and acceptance criteria - -1. Make both focused compatibility tests pass for the exported type and a real initial router state. -2. Add lifecycle assertions for initial, pending, successful, error, not-found, and redirect loads; verify exact status codes, exact `AnyRedirect` identity/headers/status, and that `loadedAt` changes only for the winning foreground/server load commit. Use a controlled `Date.now()` value plus a store-write counter to require that exact timestamp and exactly one accepted write, including when the later background lane settles. -3. Subscribe through React/Solid/Vue `useRouterState` and prove these fields remain reactive, including a same-route reload. -4. Add supersession controls showing a losing load performs no `loadedAt` write, cannot replace `statusCode`, and cannot leak a redirect. -5. Add Vue transition/unmount/remount controls for `isTransitioning`, plus React/Solid controls proving their public field retains the base false semantics. Coordinate Vue teardown with P05 so it cannot leave a stale true value. - -### P03 — Restore React's non-rendering transition fallback on unmount - -**Severity:** major liveness failure. **Validated by:** a focused post-unmount navigation timeout and three independent lifecycle/ownership reviews. - -#### Observable failure - -`packages/react-router/tests/pr-7805-review-transitioner-unmount.test.tsx` mounts and settles a provider, unmounts it, then performs an imperative navigation. The route work is synchronous, yet the navigation stalls, remains pending, and never advances `resolvedLocation`. React cleanup drains acknowledgements that already exist but leaves `router.startTransition` and `router._rendered` pointing at closures owned by the dead tree; the later commit queues a new acknowledgement that no `Match` can deliver. - -#### Required implementation - -1. In `packages/react-router/src/Transitioner.tsx`, give each installed transition/render callback a local owner identity. -2. During cleanup, first resolve every acknowledgement already queued by that owner with `false`. -3. If (and only if) the router still points at that owner's callbacks: - - restore `router.startTransition` to a non-rendering fallback that executes its callback and resolves `false`; - - clear `router._rendered` (or restore an equivalent inert callback that cannot acknowledge a DOM render). -4. Do not restore a captured callback from an older provider: in overlapping/StrictMode lifecycles that callback may itself belong to an unmounted tree. Use identity checks and a stable core fallback so an old cleanup cannot overwrite a newer owner. -5. Keep history unsubscription and acknowledgement cleanup synchronous with unmount. A navigation beginning immediately after testing-library/React unmount must see the fallback. - -#### Tests and acceptance criteria - -1. Make the focused navigation resolve without a timeout, with idle status and `/next` as `resolvedLocation`; assert no `onRendered` event is emitted without a renderer. -2. Replace or supplement the 100 ms race with a controlled state/microtask checkpoint so the liveness test is robust under slow CI. -3. Add StrictMode double-effect, unmount/remount, router replacement, and two-owner cleanup-order tests. The newest mounted owner must keep its callback; after the final owner leaves, the core fallback must win. -4. Cover a pending fallback/minimum-duration navigation to prove a false acknowledgement does not create a phantom `pendingMinMs` obligation. - -### P04 — Keep background asset projection private until CAS succeeds - -**Severity:** major state-corruption/notification failure. **Validated by:** a failing stale-head regression and three independent transaction/CAS reviews. - -#### Observable failure - -The P04 regression now lives in its own `packages/router-core/tests/pr-7805-review-p04-background-projection.test.ts` file. A losing background `head` result changes the exact committed root object from `foreground-refresh` to `discarded-background` even though no winning publication occurred. `runBackground` shallow-copies the match array, leaves non-reloaded entries shared with `base`, and calls mutating `projectLane` before its `_tx`/`_committedMatches` comparison. - -#### Required implementation - -1. Ensure every match that `projectLane` can write is private before any asynchronous `head`/`scripts` hook begins. For background lanes, clone each projectable index (including unchanged ancestors) into the private lane; do not rely on cloning only loader candidates. -2. Make projection cloning resource-aware. A plain object spread must not copy `_flight`/lease ownership onto a second match object. Introduce an N05 primitive such as `cloneMatchWithoutResources` for an unchanged committed ancestor, and keep an already-private transaction candidate as the projection object rather than cloning it again. If an implementation must clone a resource-owning candidate, move its resource identity and resource-bag registration to the clone without decrementing, leaving the source cleared; never leave two objects claiming one acquired lease. -3. Preserve a coherent private `matches` array for hook contexts so later route asset hooks can observe earlier projected asset results without touching committed objects. Resource-neutral projection clones may read public loader data/status but cannot release, abort, or transfer a committed owner's flight. -4. Perform the existing transaction/base CAS only after all private projection work settles. On failure, release transaction-owned background candidates exactly once through N05 and discard resource-neutral projection clones without writing stores or committed objects. Losing a projection must never release the still-committed base match's lease. -5. On success, publish the private projected lane through the normal batched `publishMatches` path. Immediately after the winning CAS and before generic previous-to-next cleanup, move (without decrementing) the corresponding committed base match's `_flight`/resource ownership into every resource-neutral projection clone that will replace it, then clear the old base pointer. Move each accepted candidate resource/bag registration into its published owner the same way. On a losing CAS, perform neither move: the base keeps its resource and transaction candidates release normally. Preserve the original object identity only for indices that neither reloaded nor projected so unrelated match stores/fetch counts do not churn. -6. Apply the same privacy and ownership rules to projection error handling: a rejected decorative hook may be logged, but partial values from a losing lane must not escape and cleanup must remain identity/lease counted. - -#### Tests and acceptance criteria - -1. Make the focused P04 test pass while retaining its exact object-identity and supersession controls. -2. Assert match-store subscribers and `fetchCount` do not change for a discarded projection, then assert exactly one notification for a winning projection. -3. Cover `head`, `scripts`, both together, ancestor projection during child reload, partial hook rejection, and two consecutive background generations settling out of order. -4. Add a control that child asset hooks see the newly projected parent in the private `matches` lane. -5. Add winning and losing projections where a **projected committed ancestor** owns a settled live flight and a child is an N05-owned candidate. On win, assert the ancestor lease moves to the published clone without abort/decrement and the old object is cleared before cleanup; on loss, assert the base object retains it. Assert the candidate has exactly one lease/owner after winning transfer, losing cleanup decrements exactly once, later unload reaches zero exactly once, and an old clone cannot abort/delete a newer same-ID flight. - -### P05 — Solid and Vue must not acknowledge renders after provider teardown - -**Severity:** major lifecycle/event correctness failure. **Validated by:** separate failing Solid and Vue regressions plus three independent framework/core reviews. - -#### Observable failure - -After provider unmount, both adapters correctly unsubscribe history and an imperative `/next` navigation reaches idle. However, stale `router.startTransition` closures still resolve `true`, causing one false `onRendered` event for a tree that no longer exists. This can also start `pendingMinMs` timing from a nonexistent render. - -#### Required implementation - -1. Give the callbacks installed by `packages/solid-router/src/Transitioner.tsx` and `packages/vue-router/src/Transitioner.tsx` explicit owner identities. -2. Register framework cleanup that, if the router still points at that owner, restores the same core non-rendering fallback used by P03 (execute callback, resolve `false`). Do not restore an older possibly-dead adapter closure. -3. Preserve normal mounted behavior: Solid may await `Solid.startTransition`; Vue may invoke and await `nextTick`; each returns `true` only while its provider owner is still mounted and current when the flush completes. -4. If unmount occurs during an in-flight transition, make its result `false`; do not emit `onRendered` or extend a pending minimum from a flush completed after teardown. -5. In Vue, coordinate with P02's `isTransitioning` compatibility store so cleanup clears only the current owner's transition state without clobbering a remounted owner. React and Solid must preserve their base store-writer behavior. - -#### Tests and acceptance criteria - -1. Make both focused tests pass: navigation still resolves to idle `/next`, but no post-unmount `onRendered` fires. -2. Add unmount-during-transition, remount, router replacement, and cleanup-order controls in both frameworks. -3. Verify mounted navigation still emits exactly one `onRendered` after the DOM contains the target. -4. Verify a false teardown acknowledgement neither starts nor prolongs `pendingMinMs`. - -### P06 — Clear React lazy reload intent when a retry begins/succeeds - -**Severity:** major recovery failure. **Validated by:** a focused failing retry/render test, an independently authored corroborating draft, and three independent classifier/retry reviews. - -#### Observable failure - -A browser-recognized dynamic-import error sets the closure-level `reload` latch. A second `.preload()` successfully imports and installs the component, but render still reloads and throws an eternal Promise because `reload` was never reset. Existing PR tests use a generic error and cannot enter this branch. - -#### Required implementation - -1. In `packages/react-router/src/lazyRouteComponent.tsx`, reset attempt-local reload intent when a genuinely new load attempt starts (alongside `error = undefined`). -2. Also ensure the success path leaves reload intent false before publishing `comp`. A successful import must always take precedence over stale failure state. -3. Preserve one-reload protection for the current recognized failure: rendering immediately after that failure should still set/check the session-storage key, call reload once, and suspend eternally while the browser reloads. -4. If a retry fails again and the storage key already exists, throw the current error instead of reloading again. Generic failures must never set reload intent. -5. Keep concurrent callers joined to the same `loadPromise`; a second call while an attempt is pending must not clear state for that same attempt. - -#### Tests and acceptance criteria - -1. Make `packages/react-router/tests/pr-7805-review-lazy-retry-module-error.test.tsx` render `PageContent`, with two importer calls and zero reload calls after the successful retry. -2. Add immediate-first-failure, repeated-recognized-failure, generic-failure, concurrent-preload, and named-export cases. -3. Exercise the behavior through an actual React route/error-boundary retry, not only direct wrapper invocation, and assert the successful component mounts without Suspense remaining stuck. -4. This retained recognized-module-error regression and its route-level expansion close T06's missing-branch coverage. Keep the existing generic-error retry cases as controls so the classification distinction remains explicit. - -### P08 — Republish the successor snapshot when a pending session transfers - -**Severity:** major location/match incoherence. **Validated by:** a failing same-ID takeover regression and three independent pending-session reviews. - -#### Observable failure - -The isolated regression is `packages/router-core/tests/pr-7805-review-p08-pending-takeover.test.ts`. The first pending route visibly has search revision one; a second navigation with the same match ID makes revision two the router location, but the visible pending match remains revision one. `offerPending` transfers `session.owner` for the same boundary/ID, then returns immediately because the predecessor already has `session.ack`. - -#### Required implementation - -1. Split `PendingSession`'s concepts instead of overloading `ack`: keep an owner/owner generation, absolute reveal deadline/timer, latched `rendered` boolean, optional `visibleUntil`, and a serialized `publicationTail`. The initial reveal acknowledgement and later successor-republication acknowledgements must not replace one another. -2. A same-boundary/same-ID takeover before reveal keeps the original absolute reveal deadline and reschedules only the timer callback for the new owner. After reveal, queue the successor's cloned pending prefix onto `publicationTail`; if a reveal/publication transition is already unresolved, append rather than race two framework transitions. -3. Before each queued publication writes, recheck current router transaction, pending-session identity, and owner generation. A third takeover makes the second owner's queued operation a no-op; the third still appends after it and publishes the newest snapshot. `finishPending` must drain the relevant tail without letting an obsolete owner wait forever. -4. Latch pending-min timing on the **first acknowledgement that returns `true`**. At that instant only, set `rendered = true` and `visibleUntil = now + pendingMinMs`. A prior false acknowledgement followed by a true successor acknowledgement starts the minimum at the true render; true followed by false must retain the first minimum. Later true acknowledgements never restart/extend it. -5. Publish every semantically current field from the successor prefix (search, params, context, loader deps/data, location-derived state, errors/assets) while stripping private flight ownership exactly as the original pending offer does. A false/unmounted acknowledgement updates neither `rendered` nor `visibleUntil`. - -#### Tests and acceptance criteria - -1. Make the focused test wait successfully for revision two before releasing the loader and drain both navigation promises in all paths. -2. Add nonzero `pendingMinMs` and assert takeover neither shortens nor restarts the first real render's deadline. Cover acknowledgement sequences true -> false, false -> true, and false -> false. -3. Add three rapid takeovers, state-only/context-only differences, predecessor acknowledgement still pending, successor superseded before its queued publish, and owner-generation cleanup ordering. -4. Add unmount/remount while a publication is queued. False acknowledgement must not create a minimum; the remounted current owner may publish/render once without an obsolete callback winning. -5. Assert location and visible match snapshots always belong to the same current transaction and mounted fallback count remains stable. - -### P10 — Use one semantic-parent chain for every child loader decision - -**Severity:** major cross-generation data incoherence. **Validated by:** a finite failing mixed-mode regression and three independent promise-graph reviews. - -#### Observable failure - -`packages/router-core/tests/pr-7805-review-p10-semantic-parent.test.ts` performs exactly two parent and child loads. The parent refreshes privately in background from revision 1 to 2 while the child uses blocking stale reload. The parent publishes revision 2, but the child publishes `{parentRevision: 1}` because it awaited the stale foreground parent. - -#### Required implementation - -1. In `packages/router-core/src/load-client.ts`, make the `semanticParent` argument to `createLoaderTask` the only parent promise used for semantic work at the next index. Pass it to both: - - `getLoaderContext` when a functional `shouldReload` runs; and - - the foreground/blocking `loadResource` call. - The background `loadResource` already receives this promise. -2. Keep `tasks[index - 1]?.match` only for mechanical task ordering/readiness if still needed; never expose it as `LoaderFnContext.parentMatchPromise`. A background task's `task.match` deliberately describes the stale foreground presentation, while `createLoaderTask`'s return value describes its fresh private candidate. -3. Preserve serial parent failure semantics. If the semantic parent cancels, redirects, errors, or is trimmed, descendants must not publish data derived from a different fallback parent. Do not convert a rejected/canceled semantic parent into the stale foreground object. -4. Build N03's generation token on this same semantic-parent abstraction so there is one definition of ancestry. Do not introduce a second parent selector for flight/cache validation. - -#### Tests and acceptance criteria - -1. Make the focused regression commit parent revision 2 and child parentRevision 2 with exactly two calls each. -2. Add matrices for all-blocking, all-background, background-parent/blocking-child, blocking-parent/background-child, and a three-level mixed chain. -3. Exercise a functional `shouldReload` that awaits/reads `parentMatchPromise`, plus parent error, redirect, not-found, and cancellation. -4. Assert no extra retry is used to hide an initially incoherent publication; the first accepted child result must use the accepted parent generation. - -### N03 — Make loader flights and preload cache entries parent-generation aware - -**Severity:** major stale-data adoption across preloads. **Validated by:** two independently failing cache/join regressions and three independent lineage reviews. - -#### Observable failure - -Both tests in `packages/router-core/tests/pr-7805-review-n03-preload-parent-generation.test.ts` start a child preload under parent revision 1, then commit the same-ID parent at revision 2. In one case the late child is cached; in the other a navigation joins its in-flight loader. Both execute the child only once and publish `{parentRevision: 1}`. Correct behavior rejects the obsolete lineage, executes a revision-2 child, and publishes revision 2. - -#### Required implementation - -1. Add an opaque private `SemanticToken` to each `WorkMatch` generation. A token identifies the complete accepted semantic inputs/results for that match—not only its ID or immediate parent—and is never a public timestamp or inferred from equal data. -2. Refactor the P10 semantic-parent value from a bare promise into an internal descriptor such as `{match: Promise, generation: SemanticToken}`. Pass only `.match` through the public `parentMatchPromise`; use `.generation` as one input when contextualizing the child. -3. After route/static context and `beforeLoad` donation-or-execution are known, derive/allocate the child's **loader-input token** from its existing `match.id` (which already encodes route/path/params/loaderDeps policy), semantic-parent result generation, its own route-context invocation generation, and its own beforeLoad invocation generation. Add an explicit invalidation or route-implementation epoch only where the existing contract requires work after that epoch. Do not add raw search, a mere stale/fresh cause, or equal-value hashing: search intentionally affects loader identity through `loaderDeps`, and current stale-preload adoption controls must remain valid. Preserve context provenance only for an explicit complete donor reuse. A fresh own context/beforeLoad invocation gets a new token even under the same parent/ID and even if its returned value is referentially/equally identical. -4. Allocate a result `SemanticToken` for every fresh loader semantic generation (or fresh no-loader context generation) and retain it through pending clones, commit, cache clones, hydration, descendant descriptors, and P04's projection helpers. A resource-neutral projection clone of an unchanged match preserves the exact base result token while its resource moves only on winning CAS; a fresh background loader candidate keeps its fresh token. Losing projection clones publish neither token nor resource. -5. Extend `LoaderFlight` with `inputGeneration` and `resultGeneration`. Defer flight lookup/acquire until contextualization has established the expected loader-input token; same match ID and parent token alone are insufficient. Join only an identical input token. Never decrement a flight lease that the lane did not increment, and preserve identity-checked deletion so an obsolete flight cannot delete a newer same-ID flight. -6. Store live flights in an ID bucket/index keyed by the complete loader-input generation, or an equivalent structure that can retrieve **every** live compatible generation. Incompatible same-ID flights coexist while owned, and starting B must not make an older compatible A undiscoverable to a later A waiter. Do not abort an old flight merely because a new lineage starts if another preload/navigation still owns it. -7. At `preloadClientRoute` publication, validate a prefix, not independent child IDs. For each candidate, determine the accepted semantic parent from the current active prefix, an unchanged CAS-valid cache prefix, or the already accepted preload prefix. At the first parent-generation mismatch, release that match and every descendant and cache none of the suffix. -8. Initialize tokens deterministically for initial client matches and for each accepted contiguous hydration prefix, in route order, using a client-local root/router-context generation. Tokens need not be serialized because comparisons are runtime-local, but every hydrated/cache/pending clone must carry its assigned token before it can be a donor or flight parent. Replacing router context creates a new root input generation. -9. Retain the existing active-ID exclusion, planned-cache object CAS, development `beforeLoad` function check, and lease transfer. Generation checking is an additional invariant, not a replacement for those guards. - -#### Tests and acceptance criteria - -1. Make both N03 regressions execute the child twice and publish revision 2. -2. Prove an unchanged parent generation still shares one flight between concurrent preload/navigation, while a real same-ID reload with equal returned data does not. -3. Cover beforeLoad-only parent context changes, multi-level descendants, siblings, parent failure/control, and a newer same-ID flight coexisting with an obsolete leased flight. -4. Add same-parent/same-ID cases where the child's own expired `beforeLoad` reruns to a different context, search changes route context without changing loaderDeps, and a no-loader parent changes context. Fresh own input must not join; explicit complete donor reuse must join. -5. Cover initial/hydrated-prefix token initialization, pending/cache clone transfer, P04 winning/losing projection clones, invalidation, clearCache, router-context replacement, and HMR route-function replacement. -6. Assert stale suffixes never enter `cachedMatches`, all rejected leases reach zero, and a valid matching-input-generation cache remains reusable. -7. Add an A -> incompatible B -> A overlap: the final A waiter must find/coalesce with the still-live first A flight, B must remain independently owned, and cleanup of either generation must not remove the other. - -### N10 — Reject same-ID flights created under a different own-context generation - -**Severity:** major context/data coherence failure. **Validated by:** one focused failing preload/navigation regression, public loader-context documentation, and four independent source/test reviews. - -#### Observable failure - -`packages/router-core/tests/pr-7805-review-n10-inflight-preload-own-context.test.ts` holds a preload loader under child context version 1, then navigates to the same match ID under stable ancestry. Navigation reruns child `beforeLoad` to version 2, yet joins the pending version-1 flight. The final match exposes context version 2 beside loader data version 1, and the loader ran once instead of once per incompatible input generation. - -This is distinct from N03's changed-parent cases. Match ID includes route/path/loaderDeps but not either the route's `context()` result or its accepted `beforeLoad` context. A same-ID lookup before contextualization therefore cannot prove that the pending flight consumed the inputs required by the current load. - -#### Required implementation - -1. Remove provisional `router._flights.get(match.id)` attachment before `contextualize`. A waiter may discover/acquire a reusable flight only after its effective loader-input generation is known. -2. Build that input generation compositionally from the N03 token model: existing `match.id`, semantic parent-result generation, route-context invocation generation, beforeLoad invocation generation, and only an explicit invalidation/implementation epoch whose established contract requires post-epoch work. Preserve stable sentinels when a route has no own context/beforeLoad hook and preserve an exact completed donor's generation; allocate a unique generation whenever either hook actually reruns, even if it returns an equal value or `undefined`. Do not key on raw search or a mere stale/fresh cause, and do not compare context values by shallow/deep equality. -3. Join only a flight whose exact input-generation token matches. If a still-pending preload cannot donate its completed semantic generation, let navigation run its own contextualization and create a second same-ID flight. Both flights retain independent lease/controller ownership until their original owners finish. -4. Bind loader result generation to the exact input generation that invoked `loader`. `applySuccess` may publish that result only into a match carrying the same accepted generation; never graft older loader data onto a freshly contextualized match. -5. Preserve the safe reuse cases: a navigation that explicitly adopts a completed successful preload's complete context/data generation may reuse it; truly concurrent waiters that share the same established generation may coalesce; and a pending route with no own context/beforeLoad hook may share when all remaining input components match. Match ID alone, referentially equal returned context, or equal serialized data is insufficient. -6. Coordinate cache publication with N03's prefix validation. A late version-1 preload may finish for its own owner, but it cannot overwrite/cache as the active version-2 lineage or delete/abort the newer same-ID flight. - -#### Tests and acceptance criteria - -1. Make N10 record exactly two beforeLoad calls and two loader calls and commit coherent version-2 context plus version-2 loader data. Keep the stable parent, unchanged ID/loaderDeps, finite gates, and exact cleanup so N03 cannot accidentally satisfy it. -2. Rewrite the existing `preload-beforeload-reuse.test.ts` case described by T12: make its loader return the context version it actually receives and require two flights when the pending preload cannot donate its generation. -3. Add a separate positive control where a completed successful preload donates its complete generation and navigation performs one coherent loader execution; add a concurrent same-generation waiter control as well. -4. Cover synchronous `context()` and synchronous/asynchronous `beforeLoad`, route-context-only changes, beforeLoad-only changes, equal-by-value and `undefined` fresh returns, nested changed-parent/unchanged-child inputs, no-own-hook sharing, loader rejection, redirect/not-found, supersession, cache expiry/invalidation, and clearCache. -5. Assert every incompatible same-ID flight keeps its own signal/lease, old cleanup cannot abort/delete the new flight, no stale result reaches `cachedMatches`, and no promise or signal remains live after cleanup. - -### P12 — Replace the long-lived redirecting flag with an exact one-shot handoff - -**Severity:** moderate redirect-chain authority leak. **Validated by:** a failing primed/fresh budget comparison and three independent ownership reviews. - -#### Observable failure - -`packages/router-core/tests/pr-7805-review-p12-redirect-authority.test.ts` proves a fresh alternating A/B cycle gets 21 loader executions before `Redirect cycle detected`. If a prior redirect's target search builder throws, the unrelated cycle gets only 20: `tx.redirecting` survived the rejected `router.navigate` and donated one depth unit. - -#### Required implementation - -1. Remove `LoadTransaction.redirecting` as an ancestry signal. Use a private unique handoff token bound to one already-built target location/commit, never an unqualified ambient depth that any next navigation can steal. -2. Centralize foreground, background, and planning follows in `followClientRedirect(router, currentDepth, redirect)`. First resolve/build the redirect target—including params/search reducers and safety normalization—with **no handoff installed**. If target building throws or reentrantly starts an unrelated navigation, no redirect authority exists to leak. -3. After a target is built, create `{id, depth: currentDepth + 1, targetHref}` and register it only immediately before committing that trusted built location with replace/ignoreBlocker semantics. Do **not** pretend `buildLocation` knows the future history key: `RouterHistory.assignKeyAndIndex` generates it inside push/replace immediately before synchronous notification. Extend the private trusted-commit path with `_redirectHandoff` instead of calling public `navigate` and rebuilding user options. -4. For an actual history push/replace, inject `__TSR_redirectHandoff: id` into the raw target history state before commit. Teach `parseLocation` to remove that marker from public `location.state` and retain it only as a private parsed-location field. For the same-URL/same-state branch that performs no history notification, pass the token explicitly to the direct internal `load` call. Thus href is only a validation field; the unique marker or explicit token is the authority. -5. At the very start of `loadClientRoute`, before `matchRoutes`/route context can reenter navigation, atomically take only the registered marker/explicit token whose ID and target href match. Bind it to the now-generated actual `__TSR_key`/href and store its numeric depth on the successor preflight/transaction. While that exact keyed load is active, duplicate loads for the same history notification/key join/await it instead of superseding it as an unrelated depth-zero load; a different marker/key/href never inherits authority. -6. Use identity-checked cleanup around the trusted commit. If the custom history push/replace throws synchronously or no exact successor captures the marker, remove only that unconsumed token without erasing a nested newer token. After atomic capture, the successor owns the depth and cleanup; the awaited successor promise no longer controls token lifetime. An inert marker left in raw history cannot reacquire consumed authority and is never exposed in public router state. -7. Preserve the background redirect CAS (`router._tx === tx` and committed-base identity), `reloadDocument` behavior, replace/ignoreBlocker behavior, and the existing exact 20-follow boundary. - -#### Tests and acceptance criteria - -1. Make the P12 primed chain receive the same 21 calls and terminal error as its fresh control. -2. Cover foreground and background redirects, same-URL replaces, mounted and no-subscriber history flows, synchronous target-build throw, synchronous throwing custom-history commit, and a route callback starting an unrelated navigation. Do not add an ordinary blocker case: redirect commits deliberately preserve `ignoreBlocker: true`. -3. Assert an unrelated navigation started while the redirect successor is still loading does not inherit the chain. -4. Add a target search/params builder that synchronously starts an unrelated same-href navigation, duplicate `load` subscribers for one history notification, and nested internal redirects. Assert private marker stripping, actual generated-key binding, duplicate-load joining, and that only the exact built target consumes the token. -5. Keep P09's passing exact-boundary test unchanged as a guard against accidentally shifting the limit. - -### N02 — Count planning redirects in the same finite chain - -**Severity:** major unbounded recursion/OOM risk. **Validated by:** a bounded failing context-redirect regression and three independent preflight reviews. - -#### Observable failure - -`packages/router-core/tests/pr-7805-review-n02-planning-redirect-budget.test.ts` permits 21 self redirects from route `context()` and then throws an ordinary sentinel. The sentinel is reached, proving planning redirects recurse past the whole-chain cap. The test uses mounted-style history subscription and a bounded bailout; the earlier worker OOM is not part of the evidence. - -#### Required implementation - -1. Capture P12's one-shot redirect depth before calling `matchRoutes`, not after transaction construction. Planning can throw before a transaction exists, but it still belongs to the same redirect authority handed to this load. -2. In the planning catch, follow a non-document redirect through `followClientRedirect` only while the inherited depth is below 20. This makes planning -> planning and mixed planning -> loader/beforeLoad/chunk -> planning chains share one counter. -3. At the cap, create one ordinary `Error('Redirect cycle detected')` and terminate as a **current non-renderable planning failure**; do not fabricate a partial match merely to host it. Abort the current preflight and clear `router._preflight` only if it still owns that controller. Do not create a successor `_tx`; retain `_committedMatches` and the presented committed matches with exact identities, clear any pending presentation, set status to `idle`, and restore `state.location` to `resolvedLocation` (or the initial parsed committed location if no resolution has occurred). Do not roll history back: history and `router.latestLocation` remain at the final redirect target while the public router state/presentation remains the last accepted commit. -4. Report that exact cycle `Error` through `console.error` once for the whole exhausted chain, matching other non-renderable client/preload failures. Preserve each owned load attempt's normal `onBeforeNavigate` and `onBeforeLoad` emissions, but emit no route `onError`, error component, `onLoad`, `onBeforeRouteMount`, `onResolved`, or `onRendered` because no match/lane was accepted. The public `navigate()` and every history-triggered `load()` `Promise` in the chain must fulfill with `undefined` after cleanup rather than reject. -5. Never create, replace, or clear `router._tx` at this planning cap; its identity remains the captured previous owner. If that owner is an active redirecting transaction, abort its controller, finish its pending presentation, release its private resources, and let its existing `done` fulfill after the nested redirect returns, leaving the settled transaction pointer as normal. If the captured owner was already settled, do not abort or re-finalize it. Resolve and clear only the matching latest `commitLocationPromise`, relying on its resolve cascade to settle earlier redirect commit promises. Under P02, recompute `statusCode` from the retained committed presentation (existing error 500, existing not-found 404, otherwise 200), set `redirect` to undefined as this terminal catch's non-redirect result, perform no `loadedAt` or committed-tree-revision write, and clear only the current Vue transition owner if applicable. -6. If an unrelated navigation supersedes the capped preflight first, treat it as stale: do not log, alter its stores, clear its controller/handoff, or settle its commit promise, and wait for that current writer under the normal `awaitCurrent` rule. -7. `reloadDocument` redirects remain outside the client follow cap. Stale preflights must not spend depth or clear another load's handoff. - -#### Tests and acceptance criteria - -1. Make the bounded test stop at 21 context calls without reaching its sentinel. Assert one exact `console.error` cycle diagnostic; all public promises fulfilled; `latestLocation`/history at `/planning-cycle`; `state.location`, `resolvedLocation`, committed/presented match identities, and visible content retained at `/`; idle status; no pending matches; exact `onBeforeNavigate`/`onBeforeLoad` attempt counts and zero terminal events; cleared/aborted `_preflight`/handoff; and resolved/cleared matching `commitLocationPromise`. -2. Split previous-transaction ownership into two named controls, with an `_tx` store-assignment spy in both. **Active owner:** retain the exact `_tx` object identity, abort that owner's controller exactly once, finish its pending presentation and release each private resource exactly once, and require its existing `done` to fulfill with `undefined` only after the nested capped load unwinds; there must be zero `_tx` assignments. **Already-settled owner:** retain the exact `_tx` object, controller/signal state, settled `done`, presentation, and resources with zero abort/finalize/release calls and zero `_tx` assignments. -3. In success/error/not-found retained-presentation controls, assert `statusCode` is respectively 200/500/404, `redirect` is undefined, `loadedAt` and the private committed-tree revision are not written, and Vue `isTransitioning` ends false for the cleaned current owner while React/Solid remain at their base false value. -4. Add exact 19/20/21 planning cases; mixed context/beforeLoad/loader/lazy redirects; mounted, no-subscriber, and multiple-subscriber flows; reloadDocument; previous committed error/not-found; initial load without a resolved commit; and a superseding unrelated navigation. -5. Run the bounded test under a low memory limit to ensure a regression terminates diagnostically rather than exhausting the worker. - -### N04 — Abort only the obsolete lane's wait for component readiness - -**Severity:** major superseded-load liveness failure. **Validated by:** a failing stuck-component regression, the documented supersession contract, and three independent readiness reviews. - -#### Observable failure - -In `packages/router-core/tests/pr-7805-review-n04-obsolete-component-preload.test.ts`, `/first` blocks in a component `preload`. `/second` supersedes and commits, yet the old public `router.load()` remains pending until the obsolete component promise is manually released. Loader work is abort-raced; `task.ready` is not. - -#### Required implementation - -1. Start the shared `loadRouteChunk(route)`/`chunkFailure` work eagerly at the same point as today, keep it running, and attach its rejection normalization immediately. Dynamic imports and route lazy caches are not transaction-owned and must not be aborted or cleared on supersession; an abandoned waiter must never create an unhandled late rejection. -2. Make only the lane's readiness waiter abort-aware. Race the already-normalized `chunkFailure` result against `options.controller.signal`. Represent abort with an explicit internal canceled readiness outcome—not a resolved `undefined` that can fall through the success path—and have `reduceLane` unwind/release without publishing a boundary or invoking `options.onReady`. -3. Preserve current-lane error priority: normalize the chunk rejection before entering the abort race, and if that normalized rejection wins before abort, select the correct error/redirect/not-found boundary and load its terminal chunk. Define simultaneous delivery deterministically (an already-settled chunk outcome wins the checkpoint; otherwise an observed lane abort cancels only the wait) so scheduling cannot randomly hide a terminal error. -4. Apply the same abort-aware wait to selected error/not-found boundary chunk readiness in `reduceLane`; an obsolete boundary import must not recreate the hang. -5. Leave `loadClientRoute`'s final `awaitCurrent(router, tx)` semantics intact. The old load may wait for the successor transaction, but after the successor settles it must not wait for old private work. -6. Ensure a chunk rejection that arrives after abandonment is handled and cannot produce an unhandled rejection, stale error UI, console noise, or cache corruption. - -#### Tests and acceptance criteria - -1. Strengthen N04 with a gated `/second`: old load remains pending while the successor is pending, then settles immediately when `/second` commits while `/first`'s component preload is still unresolved. Release the obsolete gate only in cleanup. -2. Cover abort before/during/after component readiness, async loader then stuck component, lazy route plus component/pending/error/not-found chunks, and chunk failure racing abort. -3. Prove a component chunk shared with the successor continues and can be reused; do not “fix” liveness by aborting or clearing the shared import. -4. Assert a canceled readiness outcome never calls `onReady`, never emits success lifecycle events, and a late shared rejection is observed exactly once without stale UI or console/unhandled-rejection noise. - -### N05 — Give every private background candidate explicit transaction ownership - -**Severity:** major loader-flight lease leak. **Validated by:** a failing abort-signal ownership regression and three independent cleanup audits. - -#### Observable failure - -`packages/router-core/tests/pr-7805-review-n05-background-candidate-lease.test.ts` settles a private stale-reload candidate, supersedes before the commit closure, drains the losing load, and finds the candidate's loader signal still live. The candidate is outside `result.matches`; all pre-commit stale exits therefore miss its last lease. - -#### Required implementation - -1. Add a private background-candidate resource bag to `LoadTransaction` (a `Set` or a generalized lane-resource owner). Register a candidate immediately in `createLoaderTask`, before starting its resource load; waiting until `executeClientLane` returns leaves a supersession window. -2. Centralize idempotent resource primitives: release all registered candidates; transfer/move a candidate and its registration to a new match without decrementing; and clone a match's public semantic fields without copying `_flight`. `releaseFlight` clearing `_flight` makes repeated defensive calls safe, but explicit registration and identity checks must still prevent incorrect lease counts. P04 must use these primitives rather than spreading resource-bearing matches. -3. Release registered candidates on every losing path: serial/control return, unexpected transaction catch, stale after execute, stale inside view transition, superseding `previousOwner`, start-transition failure, trim, background reduction control/error, and losing background CAS. -4. Keep candidates registered with the transaction after the foreground commit while `runBackground` owns their eventual reduction. On successful background publication, transfer/unregister them because the projected committed matches now own the resources; on loss, release/unregister. -5. Coordinate existing cleanup in `trimLane` and `reduceLane` with the bag so a candidate released there is also unregistered. A stale old candidate must never abort/delete a newer same-ID flight; retain the map's flight identity checks. -6. Do not conflate this with N04: component readiness is a non-abortable shared waiter, while N05 concerns exact loader-flight lease ownership. - -#### Tests and acceptance criteria - -1. Make N05 abort the candidate signal and remove the old flight after the successor commits and the losing transition drains. -2. Cover pending and already-settled candidates, stale before/inside view transition, multiple parent/child candidates, redirect/error/not-found/trim, and unexpected publication rejection. -3. Verify successful background publication keeps the accepted resource usable, shared flights decrement exactly one lease per losing owner, and a newer same-ID flight survives old cleanup. - -### H01 — Transfer source-owned lazy importers safely during HMR - -**Severity:** major development correctness failure. **Validated by:** a real failing hot-refresh regression and three independent HMR/provenance reviews. - -#### Observable failure - -The new test in `packages/router-plugin/tests/handle-route-update.test.ts` initially materializes `oldImporter`, hot-updates the route to `.lazy(newImporter)`, and invokes the real router refresh. `hotRoute.lazyFn` remains old; old code imports twice and new code never imports because `lazyFn` lives outside `options` and the handler only clears `_lazy`. - -#### Required implementation - -1. Add explicit private provenance for lazy importer ownership. Public/source `.lazy(importer)` must mark the importer as source-owned. Generator-emitted route-tree `.lazy(importer)` must mark it as generator-owned through an internal second parameter/helper or equivalent metadata that survives route-tree mutation. -2. Update the router generator output and snapshots to install generated importers with that marker. Do not infer ownership from `newRoute.lazyFn === undefined`: a freshly re-imported source route legitimately lacks generator wiring, but an explicit source route may also have removed `.lazy()`. -3. Extend `AnyRouteWithPrivateProps` and `handleRouteUpdate` to reconcile importer plus provenance before clearing `_lazy`: - - source old -> source new: replace with the new importer; - - source old -> source removed: clear it; - - generator-owned live -> fresh source without an explicit importer: preserve generator wiring; - - any fresh explicit source importer: prefer it over prior generated/source ownership. -4. Mirror the reconciled importer/provenance onto the fresh HMR export in `syncHotRouteExport`, just as generated routing state is mirrored, so aliased imports and later updates see the live owner. -5. Clear `_lazy` only after the importer decision, then rebuild indexes and call `_refreshRoute` as today. Preserve component identity/Fast Refresh logic and stable generated route options. -6. Apply the same generated handler semantics to Vite and Webpack snapshots; the handler is stringified, so keep all required logic self-contained in `handleRouteUpdate` or substituted literals. - -#### Tests and acceptance criteria - -1. Make the failing explicit-old -> explicit-new test call each importer exactly once and leave `hotRoute.lazyFn === newImporter`. -2. Add explicit -> removed, generator-owned -> source refresh without importer, generated importer update after route-tree regeneration, source overriding generated, repeated updates, and importer rejection/retry cases. -3. Run both Vite and Webpack HMR code-generation snapshots and one real refresh/load integration per adapter framework. - -### P07 — Generic Router SSR turns redirects into HTTP 200 responses - -**Severity:** blocker. **Validated by:** one failing end-to-end handler/renderer regression plus three independent source/contract reviews. - -#### Observable failure - -`packages/react-router/tests/pr-7805-review-ssr-regressions.test.tsx` drives the documented `createRequestHandler(...)(renderRouterToString(...))` composition. A route redirect with status 307, `Location: /target`, and a custom header returns `200 + Location` on this branch. The header assertions pass, isolating the defect to status selection. Base/main returned 307 through `stores.statusCode`. - -The same two-arm fallback appears in all six public renderer implementations: - -- `packages/react-router/src/ssr/renderRouterToString.tsx` -- `packages/react-router/src/ssr/renderRouterToStream.tsx` (both readable-stream and pipeable-stream response construction) -- `packages/solid-router/src/ssr/renderRouterToString.tsx` -- `packages/solid-router/src/ssr/renderRouterToStream.tsx` -- `packages/vue-router/src/ssr/renderRouterToString.tsx` -- `packages/vue-router/src/ssr/renderRouterToStream.tsx` - -`packages/router-core/src/ssr/createRequestHandler.ts` already merges the redirect response headers from `_serverResult`; TanStack Start separately short-circuits its redirect result and is not affected. - -#### Required implementation - -1. In every string/stream response creation path above, make status selection exhaustive over `router._serverResult`: - - `render` uses `result.status` (200/404/500); - - `redirect` uses `result.redirect.status` without normalizing to 200; - - an absent result may retain the defensive 200 fallback only for direct/misordered renderer use. -2. Keep the generic request-handler sequencing compatible with base: it may still dehydrate and invoke the supplied render callback. Do not introduce a callback/dehydration short-circuit as part of this fix unless that API change is separately approved; the validated regression requires the correct status, not a new empty-body contract. -3. Preserve `result.redirect.headers` merging in `getRequestHeaders`, including `Location`, custom headers, and normal header precedence. Do not reconstruct the redirect from `options`, because the `Response` is the source of its final status and headers. -4. Keep stream cleanup ownership unchanged. The change must only affect the `ResponseInit.status` used before `createSsrStreamResponse`/stream transformation. - -#### Tests and acceptance criteria - -1. Retain the failing React string regression and make it pass without weakening its 307, `Location`, or custom-header assertions. -2. Add table-driven coverage for both returned and thrown redirects and at least one non-default redirect code (for example 301 or 308). Include redirects from `beforeLoad` and `loader`, because both normalize into the same server result through different phases. -3. Exercise React, Solid, and Vue string renderers and every stream response-construction branch that the test environment supports. At minimum, unit-test each adapter's status selector so a future `: 200` fallback cannot recur in one framework. -4. Add controls that normal render responses still produce 200/404/500 and that redirect headers survive unchanged. -5. Assert renderer/request cleanup still runs once on success and failure. Do not add an empty-body or callback-not-called expectation; that was not base behavior and is not needed to repair this regression. - -### P11 — Functional `ssr()` failures skip the lazy route boundary chunk - -**Severity:** major. **Validated by:** one failing real React SSR/lazy-route regression plus three independent source/contract reviews. - -#### Observable failure - -`packages/react-router/tests/pr-7805-review-ssr-regressions.test.tsx` defines a genuinely lazy `/reports` route whose functional `ssr()` throws. The server response correctly has status 500, but renders the built-in `Something went wrong!` fallback instead of the lazy route's error component. - -In `packages/router-core/src/load-server.ts`, `contextualize` assigns `match.ssr` only after `await resolveSsr(...)` succeeds. A synchronous throw or asynchronous rejection therefore leaves `match.ssr` undefined. `applyFailure` correctly selects and commits the route error boundary, but terminal boundary readiness is guarded by `match.ssr === true`, so `loadRouteChunk(route, 'errorComponent')` is skipped. Base/main explicitly loaded the lazy boundary for a serial-phase route failure. - -#### Required implementation - -1. Split SSR policy resolution into a non-throwing local effective fallback and the optional functional override: - - shell mode: root is renderable and descendants are not; - - a `false` parent forces `false` and must continue to skip the child selector; - - an explicit non-function option is inherited exactly as today; - - an undefined option uses `router.options.defaultSsr ?? true`; - - when the parent is `data-only`, an otherwise `true` fallback remains `data-only`. -2. Do **not** assign the fallback to `match.ssr` before invoking the selector. Compute it in a local variable, call/await the functional option with the same `matches` snapshot shape as the PR/base contract (completed ancestors carry their policies; the current and future entries retain their pre-selector values), and assign the normalized functional result only on success. If it throws/rejects, assign the local fallback to the current match immediately before failure reduction. This preserves selector input while still making terminal boundary readiness deterministic. -3. Keep terminal chunk loading policy-based: - - fallback/effective `true` loads the selected lazy `errorComponent` or `notFoundComponent` before rendering; - - `data-only` and `false` do not server-render route boundary components; - - global root not-found still loads both the normal route chunk and not-found boundary as required by its existing path. -4. Do not blindly set `match.ssr = true` in the catch block. That would violate inherited `data-only`, `false`, shell-mode, and default-SSR semantics. -5. Preserve route-order failure priority and loader-prefix truncation. The selector failure remains a serial failure at its route index; this repair only makes its already-selected presentation boundary ready. - -#### Tests and acceptance criteria - -1. Retain the failing React SSR regression and make the lazy boundary text render with status 500. -2. Add sync-throw and async-rejection cases. Assert the lazy loader runs once and the correct boundary owns the error. -3. Add policy matrix controls for default/inherited `true`, inherited `data-only`, explicit/default `false`, and shell mode. Only effective `true` may preload/render the boundary on the server. -4. Add an `onError` conversion to `notFound()` case and verify the selected lazy not-found boundary and 404 status; include an ordinary error control to prevent accidental reclassification. -5. Verify descendants beyond the serial failure remain omitted and their `beforeLoad`, loaders, normal chunks, `head`, and `scripts` do not run. -6. Hydrate at least the effective-true error response and assert the server and client choose the same lazy boundary, preventing the current default-server/custom-client hydration mismatch. -7. Add a selector-input oracle over a nested route: record the current, completed-ancestor, and future-descendant `matches[].ssr` values seen by both sync and async selectors. The repair must not expose the locally computed fallback early or otherwise change this public selector snapshot. - -### N07 — Preserve route context when a functional SSR selector fails - -**Severity:** major server-rendering correctness defect. **Validated by:** one focused sync/async failing test plus independent adapters, server/hydration, client-transaction, and root reviews. - -#### Failure mechanism and invariant - -`executeServerLane` creates request-local match copies with `context: {}`. During serial `contextualize`, the current route's functional `ssr()` selector is awaited before the match receives its already-known parent and static route context. A thrown/rejected selector therefore selects the right route boundary and 500 status while leaving that boundary's `useRouteContext()` empty. The required phase boundary is: - -```text -completed ancestor context - -> current static __routeContext - -> functional SSR selection - -> validation/current beforeLoad (only if selection succeeds) -``` - -The context visible after selector failure must include router context, all completed ancestor route/beforeLoad context, and the failing route's already-planned static `__routeContext`. It must not include or synthesize the failing route's own `__beforeLoadContext`, because its `beforeLoad` has not run. - -#### Required production changes - -1. In `packages/router-core/src/load-server.ts`'s serial contextualization path, compute the current `parentContext` from the completed predecessor and assign `match.context = {...parentContext, ...match.__routeContext}` before calling or awaiting a functional `resolveSsr`. -2. Coordinate the ordering with P11: seed/resolve the route's effective SSR policy only after the base context exists; if selection succeeds, continue through validation and the current route's `beforeLoad`, then extend context with that accepted `__beforeLoadContext` exactly once. -3. If the selector throws synchronously or rejects asynchronously, preserve the pre-selector context on the selected terminal match. Do not rerun the route `context` function, do not run current `beforeLoad`, and do not overwrite the context again during reduction/projection. -4. Keep completed ancestor context immutable/request-local. A descendant selector failure must not erase or mutate ancestor matches, and concurrent server requests must never share a context object. -5. Ensure terminal `head`, headers/scripts, eager or lazy error/not-found boundaries, and public route-context hooks all observe the same selected match context. P11 still owns loading a lazy terminal boundary; N07 owns what that boundary reads. - -#### Tests and acceptance criteria - -1. Make both sync and async N07 cases in `packages/react-router/tests/pr-7805-review-server-context-frontier.test.tsx` pass unchanged: status 500, exact selector error, router/layout/completed-ancestor-beforeLoad/failing-route static context present, and failing-route beforeLoad exactly zero calls. -2. Add a nested case whose ancestor beforeLoad is async and completes before the child selector fails; its context must be present. Add a root-selector failure where parent context is only router context. -3. Add a failing route whose `context` function itself throws as a separate planning-failure control; do not accidentally classify it as an SSR-selector failure or fabricate its context. -4. Add valid selector-failure controls: a synchronously thrown and asynchronously rejected ordinary error must select the ordinary error boundary, while supported thrown/rejected redirect and not-found sentinels must retain their existing terminal control-flow semantics. Do not add returned redirect/cancellation cases: the functional `ssr()` selector's return contract is only `undefined | SSROption`, so those would test an API the router does not provide. None of these failure controls may execute the current route's `beforeLoad`. -5. After P11 is fixed, repeat the sync/async assertions through a lazy error boundary and both React string/stream server renderers; add Solid/Vue server rendering parity or a framework-neutral core match-context assertion plus one adapter integration. - -### N08 — Rebuild the visible hydration frontier's presentation context - -**Severity:** major hydration consistency defect. **Validated by:** a real server-load/dehydrate/client-hydrate failing test plus independent adapters, server/hydration, client-transaction, and root reviews. - -#### Failure mechanism and invariant - -Hydration deliberately adopts only the contiguous server-committed semantic prefix, while `presented` also contains the first unresolved serialized `ssr:false`/pending match so its fallback can hydrate. `hydrate.ts` rebuilds context only for `committed`, after installing serialized `__beforeLoadContext`; the visible frontier keeps its initial client `matchRoutes` context from before that installation. Server markup therefore reads complete parent context while the client fallback begins with a truncated object. - -Do not widen semantic adoption to fix a presentation problem. The invariant is: - -```text -committed prefix: semantic adoption + chunks/head/scripts/data -one included frontier: context projection only -remaining suffix: ordinary client planning/load -``` - -#### Required production changes - -1. In `packages/router-core/src/hydrate.ts`, keep the existing `committed` prefix and all href/key/id/currentness guards unchanged. Rebuild committed context exactly as today. -2. If `presented[committed.length]` is the already-selected serialized frontier, assign only its context from the rebuilt parent plus data already owned by that match: `{...parentContext, ...frontier.__routeContext, ...frontier.__beforeLoadContext}`. For a root frontier, use router options context as the parent. -3. Do not rerun the frontier route `context` function solely for presentation; use its already-planned `__routeContext`. Do not call its beforeLoad/loader/head/headers/scripts or mark it committed/successful. If serialized data legitimately contains its own accepted `b`, include it in the same merge order used on the server. -4. Keep `_committedMatches`, resolved-location adoption, chunk readiness, head/script execution, and initial-load skip decisions capped at `committed`. The context-projected frontier must still be replanned/loaded by the ordinary client lane. -5. Preserve data-only hydration behavior and abort/currentness checks. If the bootstrap is rejected or route IDs/href do not align, do not project stale serialized context into newly matched routes. - -#### Tests and acceptance criteria - -1. Make N08 in `packages/react-router/tests/pr-7805-review-server-context-frontier.test.tsx` pass unchanged. Before mount it must remain `pending`/`ssr:false` while containing `server-authenticated` and its child token; the server child loader remains zero calls. -2. Continue through `hydrateRoot` with the gated client loader and require identical fallback text and no React hydration mismatch diagnostic. Then release the loader, await the real client load, and prove terminal content/current context/idle resolved location. -3. Cover root and nested frontiers; `ssr:false`, serialized `pending`, and a frontier carrying its own serialized `__beforeLoadContext`; parent router/route/beforeLoad merge precedence; and a multi-level suffix proving only the one presented frontier is projected. -4. Add negative controls proving context projection does not execute the frontier loader, beforeLoad, head, scripts, or component preload and does not add the frontier to `_committedMatches`. -5. Cover bootstrap rejection and route-tree/href mismatch so no server context crosses into an unrelated client match. Run React string/stream hydration and a Solid/Vue selective-SSR parity case where their hydration mechanisms consume the same core state. - -### D01 — Make the compile-time environment split actually remove the opposite lane - -**Severity:** verified server-artifact/DCE defect; runtime dispatch remains correct. **Validated by:** a failing Vite/Rolldown SSR bundle-graph test, an esbuild reproduction, and three independent conditional-export/topology reviews. - -#### Observable failure - -`packages/router-core/tests/pr-7805-review-c-server-dce.test.ts` bundles a production Node/SSR consumer that resolves the literal server shim and includes `load-server.js`, but also renders `load-client.js` with `transferMatchResources`, `loadClientRoute`, and `preloadClientRoute` (about 29.6 kB unminified in the measured artifact). Esbuild independently retains the client lane. Browser production correctly prunes the server lane; development intentionally keeps both. - -The root cause is topology, not the constant's value: `packages/router-core/src/router.ts` statically imports client functions directly from `./load-client`. Ordinary consumer bundlers do not propagate the condition-selected `isServer` literal far enough across that module boundary to remove all imported declarations, and `clearCache` unconditionally references a helper from the same large module. - -#### Required implementation - -1. Move environment-specific load dispatch behind the existing condition-selected `@tanstack/router-core/isServer` boundary (or an equivalent new conditional subpath). `router.ts` must not statically import the full client lane in a production server resolution, nor the server lane in a production browser resolution. -2. Give client/server/development condition files a type-compatible dispatch surface for: - - route load; - - preload; - - development HMR refresh; - - match-flight/resource release needed by `clearCache`. -3. Client condition: import/re-export the real client implementations and a non-server load stub only where needed for type compatibility. Production server condition: export literal `isServer = true`, import/re-export the server loader, use server-safe no-ops for client-only preload/refresh/resource-flight work, and never import `load-client.ts`. Development condition: retain both implementations and dispatch through `router.isServer`, because `isServer` intentionally resolves to undefined there. -4. If `transferMatchResources` is genuinely shared, extract only the minimal resource primitive into a small environment-neutral module. Do not keep it in `load-client.ts` and accept the entire lane as the cost of `clearCache`. -5. Remove `process.env.NODE_ENV === 'test' ? undefined : true` from the production server shim; that expression prevents it from being a compile constant and cannot coexist with a server-only dispatcher. Add `src/isServer/test.ts` with the same dual-dispatch surface as development, and add it to router-core's `tanstackViteConfig({entry:[...]})` so ESM, CJS, and declarations actually exist. -6. Put the package export's `test` branch **before every competing environment branch, including `development` and `node`**. Replace router-core's Vitest alias from `development.ts` to `test.ts`; replace React/Solid/Vue client-test `resolve.conditions: ['development']` with `['test']`. Server-only adapter test configurations that intentionally require literal server dispatch remain on the production server branch. Production Node/worker/Deno/Bun resolution, even under incidental `NODE_ENV=test` without the custom condition, must still choose the literal server module. -7. Preserve current runtime behavior and emitted types for Node, browser, worker/workerd, Deno, Bun, import, require, development, and explicit test conditions. Keep `process.env.NODE_ENV` HMR pruning independent from the environment-lane split. Test files that instantiate both `router.isServer = false` and `true` must run only through the explicit dual test condition, not through production server code. -8. Avoid dynamic imports in hot navigation paths unless they are proven not to change synchronous API/lifecycle behavior; condition-selected static modules are the preferred topology. - -#### Tests and acceptance criteria - -1. Make the focused production SSR graph test pass by scanning **all** emitted chunks/modules and finding no client-lane implementation exports or sentinels (`executeClientLane`, `preloadClientRoute`, redirect-cycle client code). -2. Add the inverse production-browser assertion: client lane present, server lane and server-only sentinels absent. -3. Add a development assertion that both lanes remain and runtime `router.isServer` selects correctly. -4. Exercise packaged conditional exports rather than only a source alias for Node/worker/workerd/Deno/Bun/browser and both ESM/CJS where supported. -5. Keep an independent esbuild control beside Vite/Rolldown. Record raw and gzip sizes as diagnostics, but gate on exact module/symbol absence so unrelated minification does not mask the regression. -6. Run client and server lane smoke navigations after the topology change, including server redirects, client preload, clearCache flight release, and HMR refresh in development. -7. Add resolution smoke tests for (a) `node + production`, (b) `node + NODE_ENV=test` without the `test` condition, and (c) explicit `test` condition even when `development` is also active. Inspect the resolver/metafile and assert the exact resolved `server.ts` or `test.ts` module path so the development branch cannot mask the test branch. The first two must resolve literal server-only dispatch and contain no client lane; the third must run one client router and one server router through dual dispatch. Also prove browser production remains literal client-only and the built package contains test ESM/CJS/type artifacts. - -### N01 — Make Vue's global error-boundary reset key reactive - -**Severity:** major same-route recovery failure. **Validated by:** a failing Vue render-recovery test and three independent store/CatchBoundary reviews. - -#### Observable failure - -`packages/vue-router/tests/pr-7805-review-global-boundary-reset.test.tsx` first catches a transient component render error in the global boundary. After the component is made healthy and `router.invalidate()` completes, a control proves root `fetchCount` advanced, but `Recovered page` never appears and the fallback remains. `MatchesInner` computes its reset key through a raw `matchStore.get().fetchCount`; raw TanStack Store reads do not establish Vue reactivity, and the same root match ID leaves the computed cached after the failed child subtree disappears. - -#### Required implementation - -1. Implement N06's core committed-tree revision signal and subscribe to it with Vue's `useStore` in `packages/vue-router/src/Matches.tsx`. Do not read a TanStack `Atom` through raw `.get()` inside `Vue.computed`; the global boundary must own a live subscription even after its child tree has failed. -2. Pass N06's stable scalar `router-instance namespace + committed revision` reset key through `CatchBoundary` unchanged. It must distinguish router replacement and every accepted active match-tree generation, including descendant-only background publications, without relying on a collision-prone bare root `fetchCount`. -3. Keep reset semantics scoped: accepted committed semantic publication resets a captured global error; cache-only/preload/pending/losing transaction changes do not. -4. Keep this private revision separate from P02's restored `loadedAt`. N01 subscribes to the collision-free revision; it must not broaden the public compatibility clock to child-only background publications. - -#### Tests and acceptance criteria - -1. Make the focused same-route invalidate test render `Recovered page` after proving `fetchCount` increments. -2. Add navigation to a different root-match identity with an equal numeric fetch count, repeated same-route invalidations, failed invalidation, and manual boundary-reset controls. -3. Assert the boundary does not reset for cached-route changes or a losing transaction that never publishes. -4. Cover default global fallback and a custom root error component, and ensure no warning/error is emitted after successful recovery. - -### N06 — Reset global boundaries on any accepted committed-tree generation - -**Severity:** major recovery failure in React and structurally all adapters. **Validated by:** a hardened failing React regression and three independent core/adapter reviews. - -#### Observable failure - -`packages/react-router/tests/pr-7805-review-global-boundary-background-reset.test.tsx` latches the global boundary on child revision 1, starts a child-only background reload, and proves revision 2 commits while the exact root object/fetchCount remains unchanged and the child advances once. The router is idle at `/child`, but the global fallback remains because React's key is only root ID/fetchCount. Solid and Vue use the same root-only shape (with Vue additionally affected by N01's non-reactive read). - -#### Required implementation - -1. Add a private per-router instance namespace/token and a monotonic committed-match-tree revision atom/store in router core. The namespace is stable for that Router instance and unique across instances; increment the revision exactly once, in the same batch as each accepted `publishMatches` semantic publication, whether foreground or `runBackground` and whether the changed match is root or a descendant. -2. Do not increment for pending offers (`stores.setMatches` presentation-only snapshots), preload cache publication, cache GC, a losing/stale transaction, a losing background CAS, or decorative store reads. One atomic multi-match publication increments once. -3. Initialize the revision deterministically for client-only startup and hydration. Hydration's accepted server match tree should establish one generation; merely reading/dehydrating state must not advance it. -4. In React, Solid, and Vue `MatchesInner`, subscribe reactively to the core revision and combine it with the router-instance namespace into one stable scalar global `CatchBoundary` reset key (for example an interned/string key). Do not allocate a fresh tuple/object every render, and do not substitute router object equality or root route/match ID: provider router replacement can preserve component/boundary identity and two route trees can share IDs and revision numbers. -5. Retain per-route boundary reset keys based on each route match generation; N06 concerns only the global fallback that can catch errors from any descendant. -6. Do not drive P02's public `loadedAt` from this revision. Preserve `loadedAt` at its base foreground/server on-ready commit boundary; the private revision alone advances for later accepted child/background semantic publications and is the correctness key. Do not use `Date.now()` as the private boundary key. -7. Implement N01's Vue fix with this same reactive signal; it repairs same-root foreground invalidation and descendant-only background recovery without two competing key mechanisms. - -#### Tests and acceptance criteria - -1. Make the hardened React N06 test recover without weakening any root/child identity, fetchCount, location/status, or diagnostic control. -2. Port the controlled scenario to Solid and Vue; each must prove the global rather than route-local boundary owns the error and recovers after child-only background success. -3. Retain N01's same-route Vue invalidation regression and make it pass through the same revision subscription. -4. Add deep-child, child background error -> later success, root identity replacement with equal fetchCounts, one multi-child background publication, and `RouterProvider` replacement between two Router instances at the same revision and same root/route IDs. The equal-revision router replacement must reset once; ordinary rerenders of one instance must not. -5. Add negative controls proving pending offers, valid preloads/cache writes, losing background CAS, and stale transactions do not reset a latched global boundary. - -## Verified test-suite repairs - -These are verified defects in PR-added regression coverage. They do not by themselves establish a production failure, so keep their tests separate from the production regressions above and do not claim a runtime fix until the hardened oracle fails before the corresponding code change and passes afterward. - -### G01/P09 — Retain passing semantic-prefix and redirect-boundary controls - -These two focused tests falsified suspected production defects but cover high-risk boundaries that the PR did not directly pin. Keep them in the eventual test patch: - -1. `packages/router-core/tests/pr-7805-review-c-child-loader-deps-reuse.test.ts` must continue to prove a stable parent preload context is reused while changed child-only `loaderDeps` rerun child beforeLoad/loader and publish fresh child context/data. Harden with explicit different child IDs and unchanged final parent ID; keep call/data assertions as the public contract and private `_preloadContext` checks as diagnostics. -2. `packages/router-core/tests/pr-7805-review-p09-preload-redirect-boundary.test.ts` must continue to prove step 0 -> 20 is exactly twenty followed redirects and step 21 never executes. During P12/N02 redirect refactoring, also assert active `/` location/matches remain untouched and step 21 does not enter cache. -3. Do not add production changes for either passing case. Add thrown/returned, beforeLoad/loader, and reloadDocument variants only where shared redirect/prefix code changes make those controls valuable. - -### T01 — Make the Vue root-pending test observe the pending phase - -**Severity:** confidence gap in changed Vue rendering behavior. **Validated by:** three independent test/source audits. - -#### Current false-positive window - -`packages/vue-router/tests/Matches.test.tsx` names `should show pendingComponent of root route` but waits only for final `root-content`. Neither `root-pending` nor `default-pending` is queried. Its comments describe the deleted thrown-Promise/Suspense model even though this PR directly renders `status === 'pending'`, so removing pending rendering entirely still passes. - -#### Required implementation and acceptance - -1. Replace the 100 ms sleep with a controlled loader promise and set deterministic `defaultPendingMs: 0`/minimum timing. -2. Mount the provider, wait for the root route's `root-pending`, and assert the router is pending and final content is absent before releasing the gate. -3. Require `default-pending` to be absent while `root-pending` is visible. The root route's own `pendingComponent` is the precedence contract this named test must pin; do not retain an alternative expectation branch. -4. Release inside Vue's render flush, await final root content, then assert both pending variants are removed and router status/resolved location are idle/current. -5. Delete the obsolete Suspense comments and add a negative mutation/control proving the test fails if Vue `MatchInner` stops rendering pending matches. - -### T02 — Isolate preload selector notifications from provider startup - -**Severity:** bogus performance/correctness oracle across React, Solid, and Vue. **Validated by:** three independent setup/publication audits. - -#### Current false-positive window - -Each `store-updates-during-navigation.test.tsx` setup renders `RouterProvider` and returns immediately. The `redirection in preload` case snapshots selector calls while the initial router load can still publish, then attributes a rebaselined `+2` to preload. It neither isolates the operation nor proves the active semantic tree stayed unchanged. - -#### Required implementation and acceptance - -1. Make each framework setup asynchronous. Await index content, `router.state.status === 'idle'`, and resolved/current `/` before returning or baselining. -2. Clear the selector spy after initial settlement. Capture active location, resolved location, ordered active match IDs/object identities, status, and rendered UI. -3. Execute and fully await only the redirecting `/posts` preload. Assert the `/posts` loader and redirect each execute exactly once, but the operation does not navigate, replace active semantic matches, change active status/location, or render either redirecting or target route. Subscribe separately to `router.stores.cachedMatches`: require one successful `/other` target match to be published (with the active root excluded), no `/posts` error/redirect match, and no other cache publication. The preload follows the redirect and returns no public redirect object, so do not look for redirect metadata in `RouterState`. -4. After the settled-baseline spy reset, require exactly **zero** notifications from the existing public aggregate-state selector for the redirecting preload in React, Solid, and Vue. This selector reads active router state, not the cache; any nonzero notification is a failure rather than a value to rebaseline. -5. Add a non-redirect preload control and run the identical semantic assertions/counting procedure in React, Solid, and Vue. -6. Prove the hardened case fails if preload mutates active matches/location and remains stable if initial-load scheduling is deliberately delayed. - -### T03 — Make the issue-7120 E2E execute and observe the View Transition path - -**Severity:** merge-confidence gap for a race-specific fix. **Validated by:** three independent audits of the fixture, issue path, and Playwright assertions. - -#### Current false-negative window - -`e2e/react-router/issue-7120/tests/issue-7120.repro.spec.ts` waits for the root pending UI, releases the redirect, and asserts only the final `/posts` presentation and absence of logged errors. It never proves that `document.startViewTransition` existed or ran, and it never records intermediate commits. The test therefore passes if the browser skips the named View Transition path or if stale `Home` content commits briefly before `Posts loaded`. - -#### Required implementation - -1. Install a deterministic `document.startViewTransition` wrapper with `page.addInitScript` before `page.goto`, preserving the browser implementation when available and supplying an API-compatible test shim otherwise. Record invocation count, update-callback start/end, `updateCallbackDone`, and `finished` settlement. -2. Add stable fixture markers for the app/root shell, pending UI, stale Home route, and target Posts route. Start a `MutationObserver` plus requestAnimationFrame/commit log before releasing `redirectGate`; record semantic states rather than raw HTML. -3. Assert exactly one View Transition invocation, exactly one update-callback start/end pair, and successful settlement of both `updateCallbackDone` and `finished`. Do not permit a fixture-dependent alternative count. -4. Assert the presentation sequence contains pending followed by target, and contains neither stale Home nor an empty/unknown app state after the gate release. Keep final URL/content and page/console-error assertions as controls. -5. Make the instrumentation self-cleaning and diagnostic: on failure, include the ordered timestamped state/transition log, not a polling timeout alone. - -#### Tests and acceptance criteria - -1. Prove the hardened test fails when `startViewTransition` is disabled/bypassed and when a deliberate stale-Home commit is inserted into the fixture. -2. Prove it passes with native Chromium View Transitions and with the deterministic shim used in CI. -3. Avoid screenshot-only timing assertions; the semantic mutation/commit log must be the gating oracle. - -### T04 — Observe every presentation between issue-7457 pending and target - -**Severity:** merge-confidence gap for a transient blank-screen fix. **Validated by:** three independent audits of the E2E timeline and assertions. - -#### Current false-negative window - -`e2e/react-router/issue-7457/tests/issue-7457.repro.spec.ts` establishes only that pending appeared sometime (`__pendingSeen`) and that `/another` eventually rendered. A blank app root or transient index route between those endpoints satisfies all assertions. - -#### Required implementation - -1. Give the app shell, pending component, index route, and `/another` target stable semantic markers. Install a MutationObserver before router startup (prefer `page.addInitScript` plus an app-owned log hook) and record every coalesced commit/presentation state. -2. Begin the gating interval when pending first appears and end it only when the target has committed. For every observation in that interval, require the shell to contain pending or target; explicitly reject an empty shell, index-route content, simultaneous incompatible routes, and an unknown state. -3. Include a requestAnimationFrame sample after each mutation so an empty state lasting a render frame is observable while harmless same-task DOM replacement does not become flaky. -4. Keep `pageerror`, console error, final URL, target uniqueness, and pending disappearance assertions. Report the full ordered state log if the invariant fails. - -#### Tests and acceptance criteria - -1. Insert a controlled one-frame blank and a controlled one-frame index commit in a negative fixture/mutation; each must fail the hardened oracle. -2. Run the real auto-code-splitting reproduction repeatedly under CI scheduling without fixed sleeps. -3. Ensure the observer starts before the first route presentation and is removed after the terminal assertion. - -### T05 — Assert Solid issue-7283's configured pending minimum - -**Severity:** merge-confidence gap for selective-SSR hydration timing. **Validated by:** three independent audits of the route configuration and lifecycle log. - -#### Current false-negative window - -`e2e/solid-start/selective-ssr/src/routes/ssr-false-pending-min.tsx` configures `pendingMinMs = 1500` and stores timestamped lifecycle events. `issue-7283-dev-hydration.spec.ts` maps each event to `type` and discards `t`, so a 50 ms pending flash passes the same order assertion as a compliant 1500 ms presentation. - -#### Required implementation - -1. Return the full `{type, t}` records from `page.evaluate`. Select the final complete `pending-mounted -> pending-unmounted -> target-mounted` cycle by index rather than slicing types independently. -2. Measure page-side monotonic `performance.now()` timestamps and require `pending-unmounted.t - pending-mounted.t >= 1400` ms for the configured 1500 ms minimum. The fixed 100 ms tolerance covers scheduling/clock sampling only. Do not add an upper-duration correctness assertion; use Playwright's bounded test/expect timeout solely as the liveness guard for a fallback that never settles. -3. Assert loader completion precedes or coincides with the terminal transition as intended by the fixture, and `target-mounted` does not precede `pending-unmounted`. -4. Keep the development-mode hydration mismatch collection, final target visibility, pending detachment, and data-only control. -5. Export/expose the fixture's `pendingMinMs` to the test or record it in the event log so the test does not silently drift from the route constant. - -#### Tests and acceptance criteria - -1. Temporarily lower/disable the router's pending minimum in a negative fixture and prove the duration assertion fails. -2. Run under the dedicated Vite dev server because Solid's development hydration checks are part of the original contract. -3. Use monotonic page-side timestamps (`performance.now`) for differences and print the full lifecycle log on failure. - -### T07 — Add a deterministic settles-during-mount transition regression - -**Severity:** explicit unit-coverage gap for a known liveness race. **Validated by:** three independent reviews of the current test and original interleaving. - -#### Current limitation - -`packages/react-router/tests/preloaded-mount-resolution.test.tsx` is valuable and should remain: it verifies a completely settled pre-mount load emits `onRendered` after provider mount. Its own comment correctly says JSDOM does not deterministically reproduce the original case where loading flips/settles during the mount/effect batch. A benchmark is not a focused unit oracle for that interleaving. - -#### Required implementation and acceptance - -1. Retain the existing settled-before-mount test unchanged as one contract case. -2. Put the deterministic case in a new isolated `packages/react-router/tests/pr-7805-review-t07-mount-batch.test.tsx`; do not add its hoisted mock to `preloaded-mount-resolution.test.tsx`, because that would also withhold the effects on which the retained settled-before-mount control depends. In the dedicated file, partially `vi.mock('../src/utils')` with `importOriginal`. Keep every actual export except `useLayoutEffect`; implement that named export with native `React.useLayoutEffect`, but have its wrapper enqueue `{ordinal, callback, active, ran, cleanup}` instead of running the adapter callback. Use `vi.hoisted` state plus an async mock factory (`await import('react')`) so module hoisting is deterministic. The native wrapper cleanup must mark its queued entry inactive even if it never ran, and invoke a retained production cleanup exactly once if it did run. This intercepts only the adapter helper imported by `Transitioner.tsx` and `Matches.tsx` in this isolated module graph, not native React effects, and changes no shipping source. -3. Configure `router.options.InnerWrap` as a `CommitProbe` around the complete `Matches` inner tree. `CommitProbe` uses native `React.useLayoutEffect` to record each real React commit. Render an **unresolved** router through raw `createRoot` with the act-environment flag disabled. At the first commit, require exactly three active queued entries in source order: Transitioner callback installation, Transitioner mount reconciliation, then the initial MatchesInner acknowledgement. Capture their identities/ordinals and prove no loader, route event, or resolved location exists yet. -4. Run the three initial entries synchronously in their real layout-effect order, before yielding to any microtask. Entry 1 must install `router.startTransition`/`router._rendered`. Entry 2 must take the unresolved-location branch and start the real initial `router.load()`; wrap/spy that method before render to retain the exact returned `Promise` without substituting its implementation, and require one call. Entry 3 then calls the installed `_rendered` while no final transition acknowledgement exists yet, so it must emit nothing and settle nothing. This third call is required for scheduler fidelity: React runs every layout effect in the commit before loader microtasks. Configure no pending component/offer, await the gated loader's start through microtasks, and release it immediately in that same host task before yielding to a React render task. Do not use `act`/`flushSync` between loader start and release, because that would manufacture an intermediate presentation commit. -5. Let the accepted match publication cause the next real commit. The already-run initial MatchesInner wrapper must be cleaned and marked inactive; exactly one new active MatchesInner acknowledgement entry must be appended for the final match snapshot, while the two Transitioner entries remain the already-run originals. Before running the new entry, require Home committed in the DOM and exactly one `onLoad`/`onBeforeRouteMount`, but an unsettled captured load promise, pending router status, undefined resolved location, and zero `onResolved`/`onRendered`. Run only that current acknowledgement entry, then drain microtasks: it must resolve the real transition acknowledgement and the captured `router.load()` promise with `undefined`, producing exactly one `onResolved` and one `onRendered`, idle status, and current resolved `/`. Because this harness starts a direct load rather than `commitLocation`, assert `router.commitLocationPromise` remains `undefined` throughout and no orphan commit promise appears. Invoking or draining an inactive entry must be a test failure, not a way to complete the load. -6. Add an unmount/remount variant so P03's teardown repair cannot mask the mount-time race. In `finally`, release the loader if needed, run retained production cleanups for active entries, unmount, and boundedly drain the captured load; assert no queued callback or signal survives cleanup. -7. Prove the oracle is diagnostic with source-local negative mutations: deleting Transitioner's unresolved mount-load branch must leave the loader unstarted, while deleting the final MatchesInner `_rendered` acknowledgement must leave the DOM committed but the public load promise unsettled and `onRendered` at zero. Restore each mutation after the negative run. Keep a bounded timeout only on these liveness waits, never as the scheduler. - -### T08 — Fill pending replacement/stale-content parity across adapters - -**Severity:** cross-framework parity gap. **Validated by:** three independent test-matrix inventories. - -#### Current gap - -React and Solid cover both root and child continuously visible fallback replacement; Vue covers root only. Solid alone has a direct same-route stale-content/no-fallback case. These omissions do not prove adapter failures, but leave shared core behavior capable of regressing selectively through framework scheduling. - -#### Required implementation and acceptance - -1. Build a table-equivalent scenario matrix for all three adapters: - - root fallback promise replacement; - - child fallback promise replacement; - - same-route stale content before `pendingMs` when no usable fallback exists; - - `forcePending` with `pendingMinMs` across a replacement; - - supersession before the first and after the second fallback acknowledgement. -2. Use shared conceptual gates/deadlines and adapter-specific flush helpers. Assert semantic events, visible content, exact fallback mount/unmount counts, and final idle/location rather than matching implementation render counts. -3. Preserve the original pending-min deadline across same-boundary replacement and prove P08's updated snapshot fields belong to the successor. -4. Drain both predecessor and successor navigation promises and assert no post-unmount acknowledgement/onRendered event, tying the matrix to P03/P05. -5. Keep framework-specific tests where needed, but use identical case names and expected state timelines so future parity audits are mechanical. - -### T09 — Remove accidental transaction overlap and prove predecessor settlement in issue 7051 - -**Severity:** false-positive/liveness gap in two React regressions. **Validated by:** three independent setup and promise-ownership audits. - -#### Current false-positive windows - -`packages/react-router/tests/issue-7051-force-pending-suspense.test.tsx` mounts `RouterProvider` and immediately invokes `router.load()` itself. The provider effect can already own an initial same-location load, so the test's baseline may exercise supersession, joining, or cache adoption rather than the ordinary provider-only initial load it claims to establish. In the regular-navigation case, the `/first` navigation is intentionally started with `void`; only `/second` is retained. A regression that aborts `/first` but never settles its public promise therefore passes every current assertion and can leak into test cleanup. - -#### Required implementation - -1. In the `forcePending` case, remove the explicit `router.load()`. Mount the provider, await the route content, then wait until status is `idle`, current/resolved location is `/force-pending`, `router._pending === undefined`, and a settlement observer attached to the retained current `router._tx.done` has already fulfilled with `undefined`. Do **not** require `_tx === undefined` or infer liveness from its controller signal; this PR intentionally retains the settled current transaction pointer. Record the initial loader call count so invalidation is proven to be the next and only operation. -2. Start `invalidate({forcePending: true})` only after that baseline. Keep the controlled reload gate, assert pending UI/status and no error boundary before release, then await the invalidation and final idle state. Require exactly one additional loader call and drain cleanup in `finally` if an assertion fails. -3. In the `/first` -> `/second` case, capture both returned navigation promises. Attach explicit settlement observers before superseding so a rejected promise cannot become an unhandled rejection and a hanging promise is visible. -4. After `/second` starts and `/first`'s signal aborts, assert the `/first` `Promise` is still unsettled while the current successor is pending. This pins the existing `awaitCurrent` contract: a superseded public load waits for the current winning transaction rather than rejecting or reporting an independent success. Require no `/first` `onResolved`/`onRendered` event and keep the visible predecessor fallback only while the successor owns pending presentation. -5. Release the second loader and record `/second` commit/events before settlement. Require both public navigation promises to **fulfill with `undefined`** only after `/second` commits (neither rejects and `/first` cannot remain pending); no relative microtask order between the two fulfillments is part of the contract. Then require idle `/second`, resolved/current location agreement, second content, no first pending/error content, no error-boundary call, and no unhandled rejection. - -#### Tests and acceptance criteria - -1. Run each case alone and together; neither may depend on provider effect timing or prior cache state. -2. Demonstrate the second test fails under a negative mutation that leaves the superseded navigation promise unresolved even though `/second` renders. -3. Preserve the original issue-7051 force-pending presentation assertions; the hardening changes ownership/setup observability, not the expected runtime UI. - -### T10 — Prove the throwing onLoad listener executes and is isolated - -**Severity:** bogus oracle for the event-emitter catch-and-continue path. **Validated by:** three independent emitter/test audits. - -#### Current false-positive window - -`packages/react-router/tests/transitioner-listener-errors.test.tsx` registers a first `onLoad` subscriber that throws for `/first`, but never records that subscriber or the caught exception. Route hooks, the later subscriber, and both route UIs still satisfy all assertions if the throwing subscriber is skipped entirely. The production contract at `Router.emit` is explicit: invoke matching subscribers in registration order, catch each exception, report it with `console.error`, then continue iterating. - -#### Required implementation - -1. Define a spied first listener that records the event pathname and throws the exact `listenerError` only for `/first`; keep its registration before the later listener. -2. Spy `console.error` before navigation and restore it in cleanup. After `/first`, assert the first listener ran exactly once with an `onLoad` event whose `toLocation.pathname` is `/first`, and `console.error` received the exact error object exactly once. -3. Require the exact ordered log `throwing listener -> console.error(listenerError) -> later listener` for the same `/first` `onLoad` event. `Router.emit` is synchronous and registration-ordered, so no weaker order/count branch is acceptable. -4. Unsubscribe the throwing listener, navigate to `/second`, and prove it receives no second event or report while the later subscriber and `onEnter` hooks continue exactly once per route. -5. Retain final UI, loaded-path, and cleanup assertions. Fail on any additional console error so unrelated render/router errors cannot hide behind the deliberate diagnostic. - -#### Tests and acceptance criteria - -1. The hardened test must fail if the first subscriber is deleted/skipped, if the emitter stops after it throws, or if the error is swallowed without the documented report. -2. Keep a separate non-throwing multiple-listener control if exact callback order becomes relied upon elsewhere; do not overfit this regression to React render counts. - -### T11 — Replace the Vue abort test's real-time polling with owned gates and exact lifecycle oracles - -**Severity:** slow and non-diagnostic navigation-abort coverage. **Validated by:** three independent timing, signal, and settlement audits. - -#### Current false-positive window - -`packages/vue-router/tests/loaders.test.tsx`, `navigating away from pending UI aborts its loader`, waits `30 * WAIT_TIME` (roughly three seconds) so a `pendingMs = 20 * WAIT_TIME` fallback appears while the loader timer is `40 * WAIT_TIME`. It then checks only that the pending component and abort callback ran at least once and that Bar eventually appears. Duplicate loaders/aborts, the wrong signal being aborted, a hung `/foo` navigation, stale Foo/pending UI, or a non-idle final router all pass. - -#### Required implementation - -1. Start from a fully settled `/` provider baseline. Replace the Foo loader timer with controlled `fooStarted` and `fooGate` promises, capture its exact `AbortSignal`, and attach one `{once:true}` abort handler that records/settles an `fooAborted` gate. Configure `pendingMs: 0` (and deterministic `pendingMinMs`) so no wall-clock sleep is needed. -2. Invoke `router.navigate({to:'/foo'})` directly and retain that returned public promise; require exactly one Foo loader invocation and one pending mount, the signal initially live, pending visible, Foo absent, and router pending at `/foo`. -3. Capture the `/bar` navigation promise, await the exact abort/start transition, and assert the captured Foo signal—not merely any callback—became aborted exactly once. Assert no error component/event was published for `AbortError`. -4. Resolve any loader gates needed for deterministic cleanup, then await both predecessor and successor navigation promises with a bounded liveness helper. Require idle current/resolved `/bar`, Bar present exactly once, and Pending/Foo absent; require exact loader, abort, pending mount/unmount, and route hook counts. -5. Put gate resolution and both promise drains in `finally` so an early assertion never leaves a live timer, signal listener, or navigation. Prefer controlled promises; use fake time only for a separate pending-threshold/minimum case. - -#### Tests and acceptance criteria - -1. The case must complete without multi-second sleeps and fail if the wrong loader is aborted, abort fires twice, Foo settles visibly after Bar, or either public navigation never settles. -2. Add an adjacent ownership control where Foo completes before Bar navigation: prove its public navigation promise is fulfilled before starting Bar and its captured signal remains live while the committed Foo match owns the flight. When Bar unloads Foo and releases the final lease, require that exact signal to abort exactly once, without publishing an `AbortError` component/event. This deliberately follows P04/N05's lease contract; completion alone does not detach a committed match from its flight. -3. Add the same direct-`router.navigate` owned-signal case in React and Solid as well as Vue, with identical signal, promise-settlement, final-state, and semantic UI assertions. T08's presentation matrix does not substitute for this abort-ownership oracle. - -### T12 — Replace the context-insensitive pending-preload reuse oracle - -**Severity:** bogus oracle in a PR-added core contract test. **Validated by:** N10's failing context-sensitive reproduction and four independent test/source reviews. - -#### Current false-positive window - -`packages/router-core/tests/preload-beforeload-reuse.test.ts`, `keeps beforeLoad independent while joining a pending preload loader`, expects two beforeLoad calls and one loader call, but its loader ignores public `context` and returns a shared string. It therefore passes when navigation reruns version-2 beforeLoad yet joins loader data computed under version 1. The newly added preload documentation says a pending preload does not donate beforeLoad context, while the loader contract says loader context includes the accepted route/beforeLoad context; the existing expectation combines those promises inconsistently. - -#### Required implementation and acceptance - -1. Replace the context-independent loader return with a snapshot containing the exact route-context and beforeLoad-context generation received by each invocation. Gate preload version 1 and navigation version 2 independently and retain both public promises. -2. For the pending-preload case, require two beforeLoad calls, two loader calls, and final navigation context/data both from version 2. Assert the version-1 result may settle only for the preload's own lineage and cannot enter the active match/cache as version 2. -3. Split safe coalescing into its own positive case: establish an explicit completed donor or identical already-established input-generation token, then require one loader and coherent donated context/data. Do not preserve “one loader” merely because route ID/path/loaderDeps match. -4. Put all gate releases, promise drains, signal/lease assertions, and cache cleanup in `finally`. Run the hardened incompatible case against the current PR head before the production fix and prove it fails for N10's exact context/data split; run the compatible control and prove it stays green. -5. Add negative mutations for (a) ID-only flight lookup and (b) grafting a flight result into a differently contextualized match. Each must fail the hardened incompatible oracle, while disabling compatible coalescing must fail the positive control. - -## Final implementation sequencing - -1. **Land diagnostic test hardening first.** Implement T01, T02, T03, T04, T05, T07, T08, T09, T10, T11, and T12 without production changes. T07's deterministic scheduler lives entirely in its test-time partial mock. Run each hardened oracle once against an intentional negative mutation (or the known broken interleaving) so it is proven diagnostic, then restore the mutation. Retain G01 and P09 as passing controls. T12's incompatible case is already red through N10; its safe-donor control must remain green. This prevents later production edits from appearing correct only because an existing PR test is non-diagnostic. -2. **Restore the compatibility/publication foundation.** Implement P02's stores and aggregate state first. Write public `loadedAt = Date.now()` exactly once at the accepted foreground/server on-ready presentation commit and never for a later background publication. Add N06's separate private monotonic committed-tree revision at accepted foreground publications and additionally at accepted child/background semantic publications, then wire N01/N06's reactive global-boundary keys in React, Solid, and Vue. Gate on P02, N01, and N06 focused tests plus losing/pending/preload negative controls before touching transaction algorithms. -3. **Repair framework transition ownership.** Introduce one stable owner-safe non-rendering fallback, then implement P03 in React and P05 in Solid/Vue. Only Vue owns writes to P02's compatibility `isTransitioning` store; React keeps transition state local and Solid preserves the public store's base false value. Run mounted, unmount-during-flight, post-unmount navigation, StrictMode/remount, false-acknowledgement, and pending-min tests for all three adapters. -4. **Make client transaction resources and projection private.** Implement N05's explicit transaction resource bag/transfer/release helpers, then P04's private asset-projection lane on top of that ownership model. Prove every stale/pre-commit/view-transition/error exit releases exactly once and that losing projections cannot mutate or notify committed matches. -5. **Repair pending-session presentation.** Implement P08's same-boundary owner transfer and successor snapshot republish without restarting the original pending minimum. Re-run the T08 cross-adapter replacement matrix and T09 predecessor-settlement case so lifecycle changes cannot hide a stuck superseded load. -6. **Unify complete loader-input lineage.** Implement P10, N03, and N10 together: one semantic parent descriptor for hook context and one post-contextualization input-generation token for loader execution, cache reuse, and flight identity. Include both parent lineage and the route's own route/beforeLoad context; keep incompatible same-ID flights independently owned while compatible generations coalesce. Run P10/N03/N10 failures, T12's rewritten cases, and G01's stable-parent/changed-child passing control after each substep. -7. **Replace redirect authority atomically.** Implement P12's exact one-shot redirect handoff, then have N02 planning failures consume/count the same chain depth before transaction creation. Run primed/fresh, returned/thrown, beforeLoad/loader/planning, unrelated-navigation, self/cycle, and P09 exact-boundary controls; step 0 -> 20 must remain accepted and step 21 must remain excluded. -8. **Separate obsolete chunk waits from shared chunk work.** Implement N04's lane-local abort race without aborting the shared dynamic import or changing terminal chunk error selection. Then implement P06's React attempt-local reload latch reset. Run normal/pending/error/not-found chunk race matrices and recognized/generic/concurrent lazy retry cases. -9. **Repair HMR importer provenance.** Implement H01's source-owned versus generator-owned lazy importer metadata and transfer/removal rules. Update both Vite and Webpack handler snapshots, run explicit source add/change/remove cases and generated lazy-route preservation, and prove an obsolete import cannot install after `_lazy` ownership is cleared. -10. **Repair server contextualization and boundary readiness as one ordered phase.** Implement N07's pre-selector context materialization and P11's pre-selector local fallback computation in the same `load-server.ts` pass. Do not publish that fallback into the selector's `matches` snapshot unless the selector fails. Keep current-route beforeLoad absent on selector failure, preserve inherited `true`/`false`/`data-only`/shell semantics, and load only the selected terminal boundary. Run the eager N07 sync/async cases first, then P11 lazy-boundary cases and policy/not-found/redirect matrices. -11. **Repair hydration presentation without widening adoption.** Implement N08's one-frontier context projection after the committed prefix is rebuilt. Run the full server render/dehydrate/core hydrate/`hydrateRoot` regression through terminal client settlement and assert no frontier loader/head/chunk work occurs during projection. -12. **Restore generic redirect HTTP status.** Implement P07 in every string/stream response-construction branch after server result selection is stable. Run returned/thrown redirects from each phase and React/Solid/Vue renderer status/header/cleanup matrices; do not change request-handler callback/dehydration sequencing as part of this fix. -13. **Change conditional-import topology last.** Implement D01 only after lane APIs and resource helpers have their final shapes. Run production server, production browser, and development conditional graph assertions, client/server smoke navigation, clearCache/HMR, package builds, and the measured `react-router.minimal`, `solid-router.minimal`, and `vue-router.minimal` emitted bundles. Gate on symbol/module absence, with gzip/raw sizes recorded as diagnostics. -14. **Final acceptance.** Run every focused production regression independently so a shared failure cannot mask another; then router-core and React/Solid/Vue unit, type, and lint targets; generic SSR string/stream integration; router-plugin HMR tests/snapshots; package builds; hardened issue-7120/7457/selective-SSR E2E; conditional-export/DCE checks; and the full bundle-size matrix. All intentionally failing review tests must be green without weakened assertions, G01/P09 must remain green, and P01/N09 must receive no production change. - -This sequencing covers every verified production and test-suite finding in `ISSUES.md`. Rejected P01, P09-as-a-defect, and N09 remain documented controls/caveats only and are deliberately absent from production work. diff --git a/README.md b/README.md index 8dd7deef41..736715b12a 100644 --- a/README.md +++ b/README.md @@ -4,10 +4,20 @@ - + + + + TanStack Router + ## TanStack Router @@ -23,10 +33,20 @@ A modern router designed for type safety, data‑driven navigation, and seamless - + + + + TanStack Start + ## TanStack Start diff --git a/_artifacts/domain_map.yaml b/_artifacts/domain_map.yaml index 4b5d6f8386..0b2672f0c6 100644 --- a/_artifacts/domain_map.yaml +++ b/_artifacts/domain_map.yaml @@ -147,13 +147,15 @@ skills: context types to not flow into loader. wrong_pattern: | createFileRoute('/posts')({ - loader: ({ context }) => context.queryClient.ensureQueryData(postsQuery), + loader: ({ context }) => + context.queryClient.query({ ...postsQuery, staleTime: 'static' }), beforeLoad: ({ context }) => ({ queryClient: context.queryClient }), }) correct_pattern: | createFileRoute('/posts')({ beforeLoad: ({ context }) => ({ queryClient: context.queryClient }), - loader: ({ context }) => context.queryClient.ensureQueryData(postsQuery), + loader: ({ context }) => + context.queryClient.query({ ...postsQuery, staleTime: 'static' }), }) source: 'docs/router/eslint/create-route-property-order.md' priority: HIGH @@ -536,7 +538,7 @@ skills: - '@tanstack/react-router-ssr-query' covers: - External cache coordination pattern - - queryClient.ensureQueryData in loader + - "queryClient.query with staleTime: 'static' in loader" - useSuspenseQuery in components - setupRouterSsrQueryIntegration - defaultPreloadStaleTime @@ -579,11 +581,11 @@ skills: priority: HIGH status: active - - mistake: 'Awaiting prefetchQuery in loader blocks rendering' + - mistake: 'Awaiting a fire-and-forget query in loader blocks rendering' mechanism: >- - For streaming/deferred patterns, prefetchQuery should NOT - be awaited in the loader — it starts fetching on server - and streams without blocking. Awaiting defeats the purpose. + For streaming/deferred patterns, start a query without awaiting + it and handle failures with catch(noop) — it starts fetching on + the server and streams without blocking. Awaiting defeats the purpose. source: 'docs/router/integrations/query.md' priority: MEDIUM status: active diff --git a/_artifacts/skill_spec.md b/_artifacts/skill_spec.md index 4503afb48a..7eb9554a42 100644 --- a/_artifacts/skill_spec.md +++ b/_artifacts/skill_spec.md @@ -83,11 +83,11 @@ TanStack Router is a type-safe router for React and Solid applications with buil ### external-data-loading (3 failure modes) -| # | Mistake | Priority | Source | Cross-skill? | -| --- | ------------------------------------------------- | -------- | -------------------------------- | ------------ | -| 1 | Not setting defaultPreloadStaleTime to 0 | HIGH | docs/guide/external-data-loading | — | -| 2 | Creating QueryClient outside createRouter for SSR | HIGH | docs/guide/external-data-loading | — | -| 3 | Awaiting prefetchQuery in loader blocks rendering | MEDIUM | docs/integrations/query | — | +| # | Mistake | Priority | Source | Cross-skill? | +| --- | ----------------------------------------------------------- | -------- | -------------------------------- | ------------ | +| 1 | Not setting defaultPreloadStaleTime to 0 | HIGH | docs/guide/external-data-loading | — | +| 2 | Creating QueryClient outside createRouter for SSR | HIGH | docs/guide/external-data-loading | — | +| 3 | Awaiting a fire-and-forget query in loader blocks rendering | MEDIUM | docs/integrations/query | — | ### auth-and-guards (3 failure modes) diff --git a/_artifacts/skill_tree.yaml b/_artifacts/skill_tree.yaml index b5ce76f547..6f7c4c8742 100644 --- a/_artifacts/skill_tree.yaml +++ b/_artifacts/skill_tree.yaml @@ -135,7 +135,6 @@ skills: for auth state. requires: - 'router-core' - - 'router-core/data-loading' sources: - 'TanStack/router:docs/router/guide/authenticated-routes.md' - 'TanStack/router:docs/router/how-to/setup-authentication.md' @@ -247,7 +246,7 @@ skills: package: 'packages/react-router' description: >- Integrating TanStack Router with TanStack Query: queryClient - in router context, ensureQueryData/prefetchQuery in loaders, + in router context, static queries and fire-and-forget queries in loaders, useSuspenseQuery in components, defaultPreloadStaleTime: 0, setupRouterSsrQueryIntegration for SSR dehydration/hydration and streaming, per-request QueryClient isolation. diff --git a/benchmarks/AGENTS.md b/benchmarks/AGENTS.md new file mode 100644 index 0000000000..9d56a2411a --- /dev/null +++ b/benchmarks/AGENTS.md @@ -0,0 +1,15 @@ +# Benchmarks + +Read the relevant README before running benchmarks. Compare baseline and candidate with the same workload and production builds; add a focused case when existing scenarios miss the changed mechanism. Keep workloads and benchmark names stable for historical comparisons. + +| Changed behavior | Guide | Nx project | +| ------------------------------------------ | ---------------------------------- | -------------------------------------------------------- | +| Standalone Router navigation/rendering CPU | [client-nav](client-nav/README.md) | `@benchmarks/client-nav` | +| Start request/SSR CPU | [ssr](ssr/README.md) | `@benchmarks/ssr` | +| Client/server retention and allocations | [memory](memory/README.md) | `@benchmarks/memory-client`, `@benchmarks/memory-server` | + +Use `test:perf:` through Nx. Plain memory runs only smoke-test; memory metrics require CodSpeed. Client navigation benchmarks do not cover Start hydration or client server-function calls. + +Run `vitest bench` directly only with `--mode benchmark`, as the Nx targets do. Vitest 5 otherwise uses Vite's `test` mode, where vite-plugin-solid injects a jest-dom setup file that benchmark packages cannot resolve. + +For bundle-size work, follow the full optimization skill required by the root guide. Full API fixtures are maintained manually: when public hooks/components change, update matching `bundle-size/scenarios/*-full/src/routes/__root.tsx` fixtures. Save baseline results separately because each run overwrites `bundle-size/results/current.json`; report final gzip deltas and explain remaining growth. diff --git a/benchmarks/README.md b/benchmarks/README.md new file mode 100644 index 0000000000..94d2f31802 --- /dev/null +++ b/benchmarks/README.md @@ -0,0 +1,88 @@ +# CPU simulation benchmarks + +`client-nav` measures navigation, mounting, and React/Solid hydration in +Node/jsdom; `ssr` measures server requests. +Both suites run through the CodSpeed Vitest integration in CPU simulation mode. + +## Worker runtime + +Every CPU benchmark project includes `cpuSimulationExecArgv()` from +[`cpu-simulation.ts`](./cpu-simulation.ts). It augments CodSpeed's worker flags +only during CPU simulation, including the legacy `instrumentation` mode. + +The pinned CodSpeed integration supplies `--no-opt`. In Node 24 this is an alias +for `--no-turbofan`, so Maglev can still optimize and inline hot functions. The +additional `--no-maglev` keeps the optimizing compiler out of the simulation. +`--always-sparkplug` compiles baseline code on first use, so warmup does not leave +functions approaching a later tier-up or batch-compilation threshold. The worker +regression test checks that even a once-called function receives baseline code. +The integration also omits the old `--no-scavenge-task` flag on Node 20 and +newer, where V8 renamed it to `--no-minor-gc-task`. Supplying the renamed flag +keeps minor GC tied to allocation pressure instead of scheduled foreground +tasks. Both flags follow the fixes in +[CodSpeed's Node 24 support](https://github.com/CodSpeedHQ/codspeed-node/commit/e3224e7872). + +`--initial-old-space-size=512` fixes the initial/minimum old-generation +allocation budget at 512 MiB. Removing only this override after worker isolation +left two Vue SSR scenarios with same-commit spreads above 2% in five full-suite +repetitions. The paired default-heap comparison with stock incremental-marking +tasks also exceeded 2%. Runtime comparisons and tested alternatives are recorded in +[PR #8248](https://github.com/TanStack/router/pull/8248). + +This is a GC-policy tradeoff. Minor collections and allocation work remain +measured, and CodSpeed still explicitly collects before measurement. However, +V8 can skip automatic full collections below this old-generation budget, so the +benchmark can omit some eventual full-GC CPU cost from increased object +retention. Repeatability does not establish representative production GC +frequency. The flag does not preallocate 512 MiB; the existing 4096 MiB maximum +remains. See [V8's initial/minimum heap configuration](https://github.com/nodejs/node/blob/v24.8.0/deps/v8/src/heap/heap.cc#L5071). + +The configuration preserves CodSpeed's incremental-marking task settings; the +additional `--no-incremental-marking-task` from the initial stabilization proposal +has been removed. + +The flags are intentionally absent from ordinary Vitest timing and walltime runs. + +Changing simulation compiler settings changes the measurement baseline. Compare +repeatability within each configuration before interpreting performance changes +between configurations as router improvements or regressions. + +## Worker isolation + +Keep one SSR workload in each `speed*.bench.ts` file. These projects explicitly +enable Vitest isolation; CodSpeed uses the forks pool, so every file receives a +fresh worker. Multiple workloads in one file share the worker's runtime state, +even though CodSpeed collects before each measurement. Later control cases +remained noisy after the runtime flag corrections. Running the React plain +dehydration and linked-CSS controls alone reduced their observed three-run spreads +to 0.09% and 0.02% respectively. + +Variant files keep their workload names, request counts, concurrency, payloads +and assertions. CodSpeed includes the file path in a benchmark's identity, so +moved variants start a new history. The first workload keeps `speed.bench.ts`; +the additional variants have descriptive file names alongside it. Type-check +includes cover all of these files. + +## Streaming workload + +Deferred payloads in the SSR streaming scenario resolve after two task turns on +Node. A real 1 ms timer lets elapsed host time decide which concurrent requests +resolve together. Counted turns preserve the initial loading render and deferred +payloads; the existing HTML assertions check both. These benchmarks execute in +Node and use `setImmediate` directly. + +## Repeatability checks + +Dispatch the existing `Benchmarks` workflow against an unchanged branch: + +```sh +gh workflow run benchmarks.yml --ref +``` + +Wait for each workflow run to finish before dispatching the next repetition at +the same commit. The workflow also runs memory benchmarks; exclude those results +when assessing CPU repeatability. Check that every repetition has all expected +CPU results (currently 134), rather than inherited results from an earlier run. +Compare each benchmark's minimum and maximum across repetitions; keep input data, +navigation/request counts, builds, dependencies and Node version fixed when +testing runtime configuration changes. diff --git a/benchmarks/bundle-size/.gitignore b/benchmarks/bundle-size/.gitignore index d5ced39aa3..bd05a98cee 100644 --- a/benchmarks/bundle-size/.gitignore +++ b/benchmarks/bundle-size/.gitignore @@ -6,4 +6,6 @@ scenarios/*/src/routeTree.gen.ts results/*.json results/*.md results/*.js +results/*.log +results/runs/ !results/.gitkeep diff --git a/benchmarks/bundle-size/README.md b/benchmarks/bundle-size/README.md index 4d4d3dc2d3..2185d6b43f 100644 --- a/benchmarks/bundle-size/README.md +++ b/benchmarks/bundle-size/README.md @@ -29,29 +29,102 @@ Each package has `minimal` and `full` scenarios: ## Local Run ```bash -pnpm nx run @benchmarks/bundle-size:build +pnpm benchmark:bundle-size:run ``` Run one or more scenarios during local optimization: ```bash -pnpm nx run @benchmarks/bundle-size:build -- --scenario react-router.minimal -pnpm nx run @benchmarks/bundle-size:build -- --scenario react-router.minimal,react-router.full +pnpm benchmark:bundle-size:run --scenario react-router.minimal +pnpm benchmark:bundle-size:run --scenario react-router.minimal,react-router.full ``` -Filtered runs build only the package projects needed by selected scenarios. Full runs build all package projects needed by all scenarios. If the required packages are already built and unchanged, skip that step: +The runner calls `measure.mjs`, which builds the selected package projects through Nx. Full runs build the package projects for all scenarios. +`pnpm benchmark:bundle-size` uses the Nx build cache for the full benchmark, then generates `current.json` with the current commit, branch, dirty status, and report timestamp. CI uses this command as well. + +Nx caches the bundles, `measurements.json`, and `benchmark-action.json`. Git metadata does not affect the build cache. The report preserves the original `measuredAt` and build duration when measurements come from cache; `generatedAt` records when the report was generated. Running `pnpm nx run @benchmarks/bundle-size:measure` directly produces only the cacheable outputs; run `node scripts/benchmarks/bundle-size/report.mjs` afterward to refresh `current.json`. + +If the required packages are already built and unchanged, skip that step: ```bash -pnpm nx run @benchmarks/bundle-size:build -- --scenario react-router.minimal --skip-package-builds +pnpm benchmark:bundle-size:run --scenario react-router.minimal --skip-package-builds ``` This writes: +- `benchmarks/bundle-size/results/measurements.json` - `benchmarks/bundle-size/results/current.json` - `benchmarks/bundle-size/results/benchmark-action.json` +- `benchmarks/bundle-size/results/measure.log` `current.json` includes run status, selected package build projects, per-scenario totals, per-file sizes, and the emitted JS files used for measurement. Dist paths use `scenarioDir`/`outDir`, e.g. `react-router.minimal` maps to `benchmarks/bundle-size/dist/react-router-minimal/`. +The runner sets `CI=1` and `NX_DAEMON=false`. Successful runs print log locations and the existing `query` or `diff` summary. +If a step fails, the runner stops with a nonzero exit code. It prints the last 40 log lines, limited to 8,000 characters. +Full stdout and stderr stay in the log files. A positive bundle-size delta does not cause failure. + +For agent runs, use `pnpm --silent benchmark:bundle-size:run ...` to omit the package-manager command echo. + +### Phase Timings + +To diagnose measurement time, request a fresh run: + +```bash +pnpm benchmark:bundle-size:run --scenario react-router.minimal --analysis --timings +``` + +The runner directly executes `measure.mjs` on every invocation, rebuilding the selected scenarios and recording fresh timings in `measure.log`. Its package-build step still uses Nx and may restore cached packages. Use `--skip-package-builds` only when those packages are already built and unchanged. + +`measure.mjs` also accepts `--timings` directly. Alternatively, set `BUNDLE_SIZE_TIMINGS=1`. Timing lines go to stderr with the prefix `[bundle-size:timing]` followed by JSON containing `phase`, `durationMs`, and, for scenario phases, `scenario`. They are diagnostics only and do not add fields to the size metrics. + +The cached `pnpm benchmark:bundle-size` / Nx build path can replay terminal output from an earlier execution, including old timing lines. Setting `BUNDLE_SIZE_TIMINGS=1` does not invalidate that cache or guarantee fresh timings. Use the direct runner above for timing investigations; refreshing `current.json` after a cache hit does not remeasure build time. + +- `package-builds`: elapsed time for the package-build invocation, including Nx startup/cache handling; omitted when package builds are skipped. +- `scenario-build`: elapsed time for each scenario's build and cleanup. +- `manifest-resolution`: manifest discovery, parsing, entry selection, and collection of all/initial JS file lists. +- `gzip` / `brotli`: accumulated codec time across distinct files for each scenario, using Node's default compression settings. File reads and summation are excluded; initial files reuse already measured sizes. +- `analysis`: source attribution, when `--analysis` is enabled. +- `overall`: measurement execution through report/history writing. Module imports, process startup, and the outer runner's tests/report command are excluded. + +Phases that start also report elapsed work on failure; compression reports partial accumulated times before propagating the error. Timing records alone do not indicate success. `overall` contains the other phases, so nested timings must not be added to it. The phase breakdown also excludes overhead such as file reads and result writing, so its sum is not expected to equal `overall`. + +## Compare Optimization Candidates + +Before you change the implementation, save a named baseline: + +```bash +pnpm benchmark:bundle-size:run --name baseline --scenario react-router.minimal,react-router.full +``` + +After you change the implementation, compare a candidate against that baseline: + +```bash +pnpm benchmark:bundle-size:run --name candidate --baseline baseline \ + --scenario react-router.minimal,react-router.full \ + --test-projects @tanstack/router-core,@tanstack/react-router \ + -- tests/path.test.ts tests/link.test.tsx +``` + +`--test-projects` runs the selected Nx unit-test targets before measurement. Arguments after `--` go only to those tests. +Tests and measurement run sequentially. Failed tests stop the runner before measurement, so old results cannot produce a misleading diff. +Without `--test-projects`, the runner only measures bundles. Type tests, performance benchmarks, and e2e tests remain separate commands. + +Named runs store their metrics and logs in `benchmarks/bundle-size/results/runs//`. Existing named results cannot be overwritten. +Without `--name`, runs replace `current.json` and the logs for the steps they run. +Emitted bundles still use the shared `dist/` directory. To retain emitted bundles for a candidate, pass a separate `--dist-dir`. + +`--baseline` accepts a run name or a JSON file path, such as `--baseline ./baseline.json`. +With `--scenario`, the comparison reports only the scenarios measured in the current run, even when the baseline contains more scenarios. Selected scenarios missing from the baseline remain visible with `n/a` for their baseline and deltas. +Without `--scenario`, comparisons include scenarios from either result file. +`--results-dir ` changes the results root, including the location of named runs. +Use the same scenario selection and measurement flags for the baseline and candidate. + +For command reference, run: + +```bash +pnpm benchmark:bundle-size:run --help +``` + ## Local Query Tools ```bash @@ -60,18 +133,22 @@ pnpm benchmark:bundle-size:diff --baseline /tmp/base-current.json --id react-rou pnpm benchmark:bundle-size:history --id react-router.minimal --top-deltas 20 ``` +Use `pnpm benchmark:bundle-size:diff --baseline /tmp/base-current.json --current-only` to compare only scenarios present in the current results. This applies to both text and `--json` output; an explicit `--id` takes precedence. + For source attribution, run an analysis build. This uses hidden source maps and writes source estimates into `current.json`; those estimates are for investigation only, not tracking. ```bash -pnpm nx run @benchmarks/bundle-size:build -- --scenario react-router.minimal --analysis +pnpm benchmark:bundle-size:run --scenario react-router.minimal --analysis pnpm benchmark:bundle-size:analyze --id react-router.minimal --top-sources 30 ``` +For a named run, pass `--current benchmarks/bundle-size/results/runs//current.json` to `query`, `diff`, or `analyze`. + ## CI Reporting - PR workflow generates a sticky comment with: - - current gzip values - - baseline delta + - current gzip, initial gzip, raw, and Brotli values + - per-metric deltas from the `main` baseline - inline sparkline trend - Pushes to `main` publish historical chart data to GitHub Pages via `benchmark-action/github-action-benchmark`. diff --git a/benchmarks/bundle-size/package.json b/benchmarks/bundle-size/package.json index 8cd8f73f41..ca34cd6cd7 100644 --- a/benchmarks/bundle-size/package.json +++ b/benchmarks/bundle-size/package.json @@ -3,16 +3,35 @@ "private": true, "type": "module", "scripts": { - "build": "node ../../scripts/benchmarks/bundle-size/measure.mjs --skip-package-builds" + "measure": "node ../../scripts/benchmarks/bundle-size/measure.mjs --skip-package-builds --measurements-only", + "test:unit": "node --test ../../scripts/benchmarks/bundle-size/pr-report.test.mjs ../../scripts/benchmarks/bundle-size/run.test.mjs ../../scripts/benchmarks/bundle-size/report.test.mjs ../../scripts/benchmarks/bundle-size/build.test.mjs ../../scripts/benchmarks/bundle-size/compress.test.mjs ../../scripts/benchmarks/bundle-size/timings.test.mjs" }, "nx": { "targets": { - "build": { - "cache": false, + "measure": { + "cache": true, + "inputs": [ + "buildProduction", + "^buildProduction", + "dependentTaskOutputs", + "{workspaceRoot}/scripts/benchmarks/bundle-size/measure.mjs", + "{workspaceRoot}/scripts/benchmarks/bundle-size/compress.mjs", + "{workspaceRoot}/scripts/benchmarks/bundle-size/timings.mjs", + "{workspaceRoot}/scripts/benchmarks/bundle-size/report.mjs", + { + "runtime": "node --version" + } + ], + "outputs": [ + "{projectRoot}/dist", + "{projectRoot}/results/measurements.json", + "{projectRoot}/results/benchmark-action.json" + ], "dependsOn": [ { "projects": [ "@tanstack/react-router", + "@tanstack/react-router-ssr-query", "@tanstack/react-start", "@tanstack/router-plugin", "@tanstack/solid-router", @@ -23,23 +42,33 @@ "target": "build" } ] + }, + "test:unit": { + "dependsOn": [], + "inputs": [ + "default", + "^production", + "{workspaceRoot}/scripts/benchmarks/bundle-size/*.mjs" + ] } } }, "dependencies": { "@tanstack/react-router": "workspace:^", + "@tanstack/react-router-ssr-query": "workspace:^", "@tanstack/solid-router": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/react-start": "workspace:^", "@tanstack/solid-start": "workspace:^", "@tanstack/vue-start": "workspace:^", + "@tanstack/react-query": "catalog:", "react": "^19.0.0", "react-dom": "^19.0.0", "solid-js": "^1.9.10", "vue": "^3.5.16" }, "devDependencies": { - "@rsbuild/core": "^2.0.11", + "@rsbuild/core": "^2.3.1", "@rsbuild/plugin-react": "^2.0.0", "@tanstack/router-plugin": "workspace:^", "@types/react": "^19.0.8", @@ -47,7 +76,8 @@ "@vitejs/plugin-react": "^6.0.1", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/benchmarks/bundle-size/scenarios/react-start-full/rsbuild.config.ts b/benchmarks/bundle-size/scenarios/react-start-full/rsbuild.config.ts index 641de56234..349e11bec1 100644 --- a/benchmarks/bundle-size/scenarios/react-start-full/rsbuild.config.ts +++ b/benchmarks/bundle-size/scenarios/react-start-full/rsbuild.config.ts @@ -6,7 +6,7 @@ const outDir = process.env.BUNDLE_SIZE_DIST_DIR ?? 'dist-rsbuild' export default defineConfig({ logLevel: 'silent', - plugins: [pluginReact({ splitChunks: false }), tanstackStart()], + plugins: [pluginReact(), tanstackStart()], output: { distPath: { root: outDir, diff --git a/benchmarks/bundle-size/scenarios/react-start-minimal/rsbuild.config.ts b/benchmarks/bundle-size/scenarios/react-start-minimal/rsbuild.config.ts index 78752d0190..7d27421d4d 100644 --- a/benchmarks/bundle-size/scenarios/react-start-minimal/rsbuild.config.ts +++ b/benchmarks/bundle-size/scenarios/react-start-minimal/rsbuild.config.ts @@ -16,7 +16,7 @@ const startOptions = clientOutput export default defineConfig({ logLevel: 'silent', - plugins: [pluginReact({ splitChunks: false }), tanstackStart(startOptions)], + plugins: [pluginReact(), tanstackStart(startOptions)], output: { distPath: { root: outDir, diff --git a/benchmarks/bundle-size/scenarios/react-start-query-integration/src/router.tsx b/benchmarks/bundle-size/scenarios/react-start-query-integration/src/router.tsx new file mode 100644 index 0000000000..93b95f3148 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-query-integration/src/router.tsx @@ -0,0 +1,17 @@ +import { QueryClient } from '@tanstack/react-query' +import { createRouter } from '@tanstack/react-router' +import { setupRouterSsrQueryIntegration } from '@tanstack/react-router-ssr-query' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + const queryClient = new QueryClient() + const router = createRouter({ + routeTree, + context: { queryClient }, + scrollRestoration: true, + }) + + setupRouterSsrQueryIntegration({ router, queryClient }) + + return router +} diff --git a/benchmarks/bundle-size/scenarios/react-start-query-integration/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/react-start-query-integration/src/routes/__root.tsx new file mode 100644 index 0000000000..ff1da4c304 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-query-integration/src/routes/__root.tsx @@ -0,0 +1,24 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/benchmarks/bundle-size/scenarios/react-start-query-integration/src/routes/index.tsx b/benchmarks/bundle-size/scenarios/react-start-query-integration/src/routes/index.tsx new file mode 100644 index 0000000000..76fb363538 --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-query-integration/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: IndexComponent, +}) + +function IndexComponent() { + return
hello world
+} diff --git a/benchmarks/bundle-size/scenarios/react-start-query-integration/vite.config.ts b/benchmarks/bundle-size/scenarios/react-start-query-integration/vite.config.ts new file mode 100644 index 0000000000..d4e4cd980d --- /dev/null +++ b/benchmarks/bundle-size/scenarios/react-start-query-integration/vite.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'vite' +import viteReact from '@vitejs/plugin-react' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' + +export default defineConfig({ + plugins: [tanstackStart(), viteReact()], +}) diff --git a/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/__root.tsx index d696063083..0ff40aebfc 100644 --- a/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/__root.tsx +++ b/benchmarks/bundle-size/scenarios/vue-router-full/src/routes/__root.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { Asset, Await, @@ -45,143 +46,151 @@ import { useTags, } from '@tanstack/vue-router' +const RootComponent = defineComponent({ + setup() { + const router = useRouter() + const [awaited] = useAwaited({ promise: Promise.resolve('ready') }) + const linkProps = useLinkProps({ to: '/' } as any) + const matchRoute = useMatchRoute() + const matches = useMatches() + const parentMatches = useParentMatches() + const childMatches = useChildMatches() + const match = useMatch({ strict: false, shouldThrow: false } as any) + const loaderDeps = useLoaderDeps({ strict: false } as any) + const loaderData = useLoaderData({ strict: false } as any) + const params = useParams({ strict: false } as any) + const search = useSearch({ strict: false } as any) + const routeContext = useRouteContext({ strict: false } as any) + const routerState = useRouterState({ + select: (state) => state.status, + } as any) + const location = useLocation() + const canGoBack = useCanGoBack() + const navigate = useNavigate() + const scrollEntry = useElementScrollRestoration({ id: 'root-scroll' }) + const tags = useTags() + + useBlocker({ + shouldBlockFn: () => false, + disabled: true, + withResolver: false, + }) + + const linkFactoryResult = linkOptions({ to: '/' } as any) + const routeMatchResult = matchRoute({ to: '/' } as any) + const SvgLink = createLink('svg') + + const hooksAndComponents = [ + useAwaited, + useLinkProps, + useMatchRoute, + useMatches, + useParentMatches, + useChildMatches, + useMatch, + useLoaderDeps, + useLoaderData, + useBlocker, + useNavigate, + useParams, + useSearch, + useRouteContext, + useRouter, + useRouterState, + useLocation, + useCanGoBack, + useElementScrollRestoration, + useTags, + Await, + CatchBoundary, + CatchNotFound, + ClientOnly, + DefaultGlobalNotFound, + ErrorComponent, + Link, + Match, + MatchRoute, + Matches, + Navigate, + Outlet, + RouterContextProvider, + ScrollRestoration, + Block, + ScriptOnce, + Asset, + HeadContent, + Scripts, + Body, + Html, + ] + + ;(globalThis as any).__TANSTACK_BUNDLE_SIZE_KEEP__ = { + hooksAndComponents, + } + + return () => { + void awaited + void linkFactoryResult + void matches.value + void parentMatches.value + void childMatches.value + void match.value + void loaderDeps.value + void loaderData.value + void params.value + void search.value + void routeContext.value + void routerState.value + void location.value + void canGoBack.value + void navigate + void scrollEntry + void tags() + void routeMatchResult.value + + return ( + <> + + {'window.__tsr_bundle_size = true'} + + home + + + + + {() => } + + }> + + + } + /> + false} disabled withResolver={false}> + {() => } + + }> + + + + + + + + +
+
hello world
+
+ + ) + } + }, +}) + export const Route = createRootRoute({ component: RootComponent, }) - -function RootComponent() { - const router = useRouter() - const [awaited] = useAwaited({ promise: Promise.resolve('ready') }) - const linkProps = useLinkProps({ to: '/' } as any) - const matchRoute = useMatchRoute() - const matches = useMatches() - const parentMatches = useParentMatches() - const childMatches = useChildMatches() - const match = useMatch({ strict: false, shouldThrow: false } as any) - const loaderDeps = useLoaderDeps({ strict: false } as any) - const loaderData = useLoaderData({ strict: false } as any) - const params = useParams({ strict: false } as any) - const search = useSearch({ strict: false } as any) - const routeContext = useRouteContext({ strict: false } as any) - const routerState = useRouterState({ select: (state) => state.status } as any) - const location = useLocation() - const canGoBack = useCanGoBack() - const navigate = useNavigate() - const scrollEntry = useElementScrollRestoration({ id: 'root-scroll' }) - const tags = useTags() - - useBlocker({ - shouldBlockFn: () => false, - disabled: true, - withResolver: false, - }) - - const linkFactoryResult = linkOptions({ to: '/' } as any) - const routeMatchResult = matchRoute({ to: '/' } as any) - const SvgLink = createLink('svg') - - const hooksAndComponents = [ - useAwaited, - useLinkProps, - useMatchRoute, - useMatches, - useParentMatches, - useChildMatches, - useMatch, - useLoaderDeps, - useLoaderData, - useBlocker, - useNavigate, - useParams, - useSearch, - useRouteContext, - useRouter, - useRouterState, - useLocation, - useCanGoBack, - useElementScrollRestoration, - useTags, - Await, - CatchBoundary, - CatchNotFound, - ClientOnly, - DefaultGlobalNotFound, - ErrorComponent, - Link, - Match, - MatchRoute, - Matches, - Navigate, - Outlet, - RouterContextProvider, - ScrollRestoration, - Block, - ScriptOnce, - Asset, - HeadContent, - Scripts, - Body, - Html, - ] - - ;(globalThis as any).__TANSTACK_BUNDLE_SIZE_KEEP__ = { - hooksAndComponents, - } - - void awaited - void linkFactoryResult - void matches.value - void parentMatches.value - void childMatches.value - void match.value - void loaderDeps.value - void loaderData.value - void params.value - void search.value - void routeContext.value - void routerState.value - void location.value - void canGoBack.value - void navigate - void scrollEntry - void tags() - void routeMatchResult.value - - return ( - <> - - {'window.__tsr_bundle_size = true'} - - home - - - - {() => } - }> - - - } - /> - false} disabled withResolver={false}> - {() => } - - }> - - - - - - - - -
-
hello world
-
- - ) -} diff --git a/benchmarks/bundle-size/scenarios/vue-start-full/src/routes/__root.tsx b/benchmarks/bundle-size/scenarios/vue-start-full/src/routes/__root.tsx index aa0539fa1a..8e8870a2ce 100644 --- a/benchmarks/bundle-size/scenarios/vue-start-full/src/routes/__root.tsx +++ b/benchmarks/bundle-size/scenarios/vue-start-full/src/routes/__root.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { Asset, Await, @@ -68,151 +69,159 @@ const helloServerFn = createServerFn({ method: 'GET' }) return 'hello from server fn' }) +const RootComponent = defineComponent({ + setup() { + const router = useRouter() + const [awaited] = useAwaited({ promise: Promise.resolve('ready') }) + const linkProps = useLinkProps({ to: '/' } as any) + const matchRoute = useMatchRoute() + const matches = useMatches() + const parentMatches = useParentMatches() + const childMatches = useChildMatches() + const match = useMatch({ strict: false, shouldThrow: false } as any) + const loaderDeps = useLoaderDeps({ strict: false } as any) + const loaderData = useLoaderData({ strict: false } as any) + const params = useParams({ strict: false } as any) + const search = useSearch({ strict: false } as any) + const routeContext = useRouteContext({ strict: false } as any) + const routerState = useRouterState({ + select: (state) => state.status, + } as any) + const location = useLocation() + const canGoBack = useCanGoBack() + const navigate = useNavigate() + const scrollEntry = useElementScrollRestoration({ id: 'root-scroll' }) + const tags = useTags() + const invokeServerFn = useServerFn(helloServerFn) + + useBlocker({ + shouldBlockFn: () => false, + disabled: true, + withResolver: false, + }) + + const linkFactoryResult = linkOptions({ to: '/' } as any) + const routeMatchResult = matchRoute({ to: '/' } as any) + const SvgLink = createLink('svg') + + const startSurface = [createMiddleware, createServerFn, useServerFn] + const hooksAndComponents = [ + useAwaited, + useLinkProps, + useMatchRoute, + useMatches, + useParentMatches, + useChildMatches, + useMatch, + useLoaderDeps, + useLoaderData, + useBlocker, + useNavigate, + useParams, + useSearch, + useRouteContext, + useRouter, + useRouterState, + useLocation, + useCanGoBack, + useElementScrollRestoration, + useTags, + Await, + CatchBoundary, + CatchNotFound, + ClientOnly, + DefaultGlobalNotFound, + ErrorComponent, + Link, + Match, + MatchRoute, + Matches, + Navigate, + Outlet, + RouterContextProvider, + ScrollRestoration, + Block, + ScriptOnce, + Asset, + HeadContent, + Scripts, + Body, + Html, + ] + + ;(globalThis as any).__TANSTACK_BUNDLE_SIZE_KEEP__ = { + hooksAndComponents, + startSurface, + } + + return () => { + void awaited + void linkFactoryResult + void matches.value + void parentMatches.value + void childMatches.value + void match.value + void loaderDeps.value + void loaderData.value + void params.value + void search.value + void routeContext.value + void routerState.value + void location.value + void canGoBack.value + void navigate + void scrollEntry + void tags() + void routeMatchResult.value + void invokeServerFn + + return ( + + + + + + {'window.__tsr_bundle_size = true'} + + home + + + + + {() => } + + }> + + + } + /> + false} disabled withResolver={false}> + {() => } + + }> + + + + + + + + +
+
hello world
+
+ + + ) + } + }, +}) + export const Route = createRootRoute({ component: RootComponent, }) - -function RootComponent() { - const router = useRouter() - const [awaited] = useAwaited({ promise: Promise.resolve('ready') }) - const linkProps = useLinkProps({ to: '/' } as any) - const matchRoute = useMatchRoute() - const matches = useMatches() - const parentMatches = useParentMatches() - const childMatches = useChildMatches() - const match = useMatch({ strict: false, shouldThrow: false } as any) - const loaderDeps = useLoaderDeps({ strict: false } as any) - const loaderData = useLoaderData({ strict: false } as any) - const params = useParams({ strict: false } as any) - const search = useSearch({ strict: false } as any) - const routeContext = useRouteContext({ strict: false } as any) - const routerState = useRouterState({ select: (state) => state.status } as any) - const location = useLocation() - const canGoBack = useCanGoBack() - const navigate = useNavigate() - const scrollEntry = useElementScrollRestoration({ id: 'root-scroll' }) - const tags = useTags() - const invokeServerFn = useServerFn(helloServerFn) - - useBlocker({ - shouldBlockFn: () => false, - disabled: true, - withResolver: false, - }) - - const linkFactoryResult = linkOptions({ to: '/' } as any) - const routeMatchResult = matchRoute({ to: '/' } as any) - const SvgLink = createLink('svg') - - const startSurface = [createMiddleware, createServerFn, useServerFn] - const hooksAndComponents = [ - useAwaited, - useLinkProps, - useMatchRoute, - useMatches, - useParentMatches, - useChildMatches, - useMatch, - useLoaderDeps, - useLoaderData, - useBlocker, - useNavigate, - useParams, - useSearch, - useRouteContext, - useRouter, - useRouterState, - useLocation, - useCanGoBack, - useElementScrollRestoration, - useTags, - Await, - CatchBoundary, - CatchNotFound, - ClientOnly, - DefaultGlobalNotFound, - ErrorComponent, - Link, - Match, - MatchRoute, - Matches, - Navigate, - Outlet, - RouterContextProvider, - ScrollRestoration, - Block, - ScriptOnce, - Asset, - HeadContent, - Scripts, - Body, - Html, - ] - - ;(globalThis as any).__TANSTACK_BUNDLE_SIZE_KEEP__ = { - hooksAndComponents, - startSurface, - } - - void awaited - void linkFactoryResult - void matches.value - void parentMatches.value - void childMatches.value - void match.value - void loaderDeps.value - void loaderData.value - void params.value - void search.value - void routeContext.value - void routerState.value - void location.value - void canGoBack.value - void navigate - void scrollEntry - void tags() - void routeMatchResult.value - void invokeServerFn - - return ( - - - - - - {'window.__tsr_bundle_size = true'} - - home - - - - {() => } - }> - - - } - /> - false} disabled withResolver={false}> - {() => } - - }> - - - - - - - - -
-
hello world
-
- - - ) -} diff --git a/benchmarks/client-nav/README.md b/benchmarks/client-nav/README.md index 6179c7f0b8..ec34ecc0c1 100644 --- a/benchmarks/client-nav/README.md +++ b/benchmarks/client-nav/README.md @@ -9,10 +9,11 @@ Cross-framework client-side CPU benchmarks for: The benchmarks run in jsdom against production builds of real apps, and are tracked in CI by CodSpeed (simulation mode). -> **Scope:** these benchmarks cover the standalone client router only. The -> client side of TanStack Start (hydration of a server-rendered document, -> streamed payload consumption, server-function calls from the client, ...) is -> not covered here; the server side of Start is covered by `benchmarks/ssr`. +> **Scope:** these benchmarks cover the client router. The hydration +> scenarios also cover DOM hydration and the Router state-restoration path +> used by Start. Start-specific entry-point initialization, streamed payload +> arrival and client server-function calls are not included. Server request work +> is covered by `benchmarks/ssr`. ## Layout @@ -38,7 +39,7 @@ scenarios/// routes/ ``` -Scenario apps use file-based routing (`@tanstack/router-plugin`) with a +Navigation scenario apps use file-based routing (`@tanstack/router-plugin`) with a generated `routeTree.gen.ts`, like a regular user app. Each scenario uses one app per framework instead of sharing routes in the baseline app. This keeps route-tree size and router options isolated so one scenario cannot shift @@ -57,9 +58,11 @@ be attributed to a specific feature area. | `control-flow` | Loader-thrown `redirect` (including a 2-hop chain), `notFound()` with `notFoundComponent`, loader errors with `errorComponent`, and boundary reset on recovery navigation. | | `head` | `HeadContent` per-navigation work: nested route `head()` evaluation, title/meta/link dedupe across matches, and head tag DOM updates during navigation. | | `history` | History push/replace/back/forward traversal, location masking, registered-but-never-blocking `useBlocker`, and `useCanGoBack`/`useLocation` subscriptions. | +| `hydration` | Initial DOM hydration: execute the SSR payload, restore `beforeLoad` context and loader data, and hydrate 192 ordinary and eight hash-sensitive Links through their follow-up effects in React and Solid. | +| `link-churn` | Links that depart, stay and mount: 30 `/hub` layout Links stay while 100 `/hub/list` leaf Links leave (alone, or with the layout to `/other`) and remount on return; a search-only change rebuilds updater and `to="."` Links. Unlike `links`, whose root-layout Links never depart. | | `links` | Per-navigation cost of ~200 mounted ``s: link prop building, active-state recompute across `activeOptions` variants, `activeProps` swaps, and `useMatchRoute` probes (the `MatchRoute` component is avoided: vue-router's implementation leaks one subscription per render). | | `loaders` | Client loader dispatch: always-stale re-runs (`staleTime: 0`), cached revisits (re-run once per lap by the `invalidate` step), `loaderDeps`-keyed caching, `router.invalidate()`, and `useLoaderData` selectors. | -| `mount` | Cold start: `createRouter` (route-tree processing) + first render + initial `router.load()` + unmount, with a fresh router per mount. The only scenario measuring router creation. | +| `mount` | Cold start: `createRouter` (route-tree processing) + first render + initial `router.load()` + unmount, with a fresh router per mount. | | `nested-params` | Deep nesting (8 dynamic levels): per-level `params.parse`/`stringify`, `beforeLoad` context accumulation across matches, and per-level `useParams`/`useRouteContext` subscriptions. Param values include characters requiring percent-encoding (as do `route-tree-scale`'s), so segment encode/decode paths run on every navigation. | | `preload` | Intent preloading from hover events, programmatic `router.preloadRoute`, deterministic preload cache behavior (`defaultPreloadStaleTime: 0`), and commit-time cache maintenance. | | `rewrites` | Composed client-side location rewrites: router `basepath` plus a locale input/output rewrite pair, running on every href build and location parse (the client analog of the SSR `rewrites` scenario). | @@ -68,10 +71,14 @@ be attributed to a specific feature area. ## Conventions +The hydration scenario has the separate lifecycle described below. The other +scenarios follow these navigation/mount conventions: + - Apps are built with `NODE_ENV=production` (`minify: false`) into `dist/app.js`; benches import the built bundle, so production package builds and production JSX output are measured, not dev transforms. - Scenarios behave like a real user app: navigation happens through `` clicks dispatched on real anchor elements (unless a scenario specifically measures the imperative API), the router uses the default browser history, and `scrollRestoration` is enabled. - Each benchmark iteration advances a fixed, circular sequence of steps; every step awaits the router's `onRendered` event, so render work is included and steps cannot overlap. No two consecutive steps may target the same location, and the sequence ends back on the initial route. - Setup runs one warm-up lap through the sequence and asserts each step's observable output (e.g. `document.title`), so a scenario that silently stops doing its work fails instead of reporting a fast time. +- Apps are mounted and disposed outside timing by `benchLifecycle` (`benchmarks/cpu-simulation.ts`): CodSpeed measures a single invocation, so every invocation gets a freshly mounted app; plain `vitest bench` keeps one app per warmup/run phase. Bench functions must be `async` functions, because CodSpeed's Vitest 5 provider awaits only `AsyncFunction`s. - Determinism: no wall-clock timers (async work is resolved promises or counted `setTimeout(0)` hops), `staleTime`/`gcTime` only ever `0` or effectively-infinite, no `Math.random`/`Date.now` in the measured loop. Scroll restoration uses `getScrollRestorationKey: (location) => location.pathname` so its cache stays bounded (the default random per-entry key grows one cache entry per push navigation). The `mount` scenario opts out of `scrollRestoration` entirely and destroys its history on unmount — both register page-lifetime globals that would leak across its mount/unmount loop. - Push-only step laps grow jsdom's session-history entry list over a run (jsdom never truncates entries behind the current index). Per-push cost stays O(1) so timings are unaffected; only the `history` scenario needs — and has — a lap that is depth-stationary. - Calibration: pick per-iteration step counts so a bench's `vitest bench` run stays roughly between 8 and 30 seconds (long enough to average out, short enough for CI). @@ -96,7 +103,7 @@ Run a single scenario app manually (after building it through Nx): ```bash CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav--:build:client --outputStyle=stream --skipRemoteCache -cd benchmarks/client-nav && NODE_ENV=production vitest bench --config ./scenarios///vite.config.ts +cd benchmarks/client-nav && NODE_ENV=production vitest bench --mode benchmark --config ./scenarios///vite.config.ts ``` Run framework-specific flame benchmarks (10 second loop, profiled with `@platformatic/flame`, forced to `NODE_ENV=production`): @@ -115,3 +122,186 @@ Typecheck benchmark sources (baseline + scenarios): ```bash CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:types --outputStyle=stream --skipRemoteCache ``` + +## Hydration + +`scenarios/hydration/{react,solid}` provide the same initial-hydration +workload: 192 ordinary Links, eight hash-sensitive Links, and three matched +routes with three `beforeLoad` contexts and two loader results. The server URL +has no fragment; the client URL has `#details`, matching half of the hash-sensitive Links. + +```bash +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav-hydration-react:test:perf --outputStyle=stream --skipRemoteCache +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav-hydration-react:test:unit --outputStyle=stream --skipRemoteCache +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav-hydration-react:test:types:client --outputStyle=stream --skipRemoteCache +``` + +Replace `react` with `solid` to run the other adapter. + +The build generates static HTML and its real Router SSR bootstrap scripts once +with `createRequestHandler` and the adapter's streaming renderer. Generation +fully consumes the response and runs outside the CodSpeed action. The measured +worker only reads these artifacts; it does not import a server renderer or start a server. + +Each invocation uses a fresh jsdom window and a fresh evaluation of the complete +production client bundle in that window's realm. HTML parsing, bundle evaluation, +and the initial document lifecycle finish in untimed setup. This resets module +state as well as the DOM, avoiding cached hydration promises and cross-realm +payload objects. The bundle and bootstrap scripts are compiled once, so this +measures a fresh application with warm code, not JavaScript download/parse cost. + +The timed region executes the serialized payload, creates the router and its +small code-based route tree, calls the public client `hydrate` API, and hydrates +the existing DOM with the framework's native renderer: + +- **React:** a separate completion component signals from its post-hydration + effect, after the same snapshot transition as hash-sensitive Links. The harness + awaits that signal and two idle React scheduler turns, then checks the expected + active links. The window's `performance.now()` is frozen, so React's + scheduler yields only to paint after commits, not after 5 ms of wall time, which CPU + instrumentation stretches by a runner-dependent factor. Each sample therefore + uses the same number of scheduler tasks. `Date.now()` is unchanged. A + 60-second watchdog fails a sample that never settles. +- **Solid:** execute the native hydration bootstrap and retain the server's + component/key hierarchy. Wait for mount, the router's rendered event, active-link + effects, and two idle turns. DOM identity assertions include every workload + element so template fallback cannot silently replace server nodes. + +Solid bounds settlement to 100 turns. Ending at the hydration call or the +first mount would miss post-hydration Link updates. +Timer turns use `setImmediate`; scrolling is a no-op +because this is CPU simulation rather than browser layout/paint measurement. + +Untimed assertions verify restored contexts and every loader row, zero client +`beforeLoad`/loader calls, expected hrefs/active state, original DOM-node identity, +working event handlers, and absence of hydration errors. Root unmount, pending +task cancellation, and window disposal also run outside measurement. Diagnostic +tests count Link renders or reactive evaluations and check they stop before the +measured region ends; counting is disabled in the timed workload. + +The bench's own `beforeEach`/`afterEach` hooks prepare and dispose every +sample outside timing, in both CodSpeed and ordinary Vitest runs. Per-phase +setup would let later iterations reuse an already hydrated document. The +hydration unit tests cover repeated fresh-state setup. + +Each scenario is included in its framework's aggregate build and CodSpeed run. +Land the benchmark independently to establish main's baseline before comparing a +hydration optimization. Regenerate each revision's artifacts with identical +fixture data and dependencies; do not pin an old hydration wire format forever. + +## Isolated route-tree construction + +`scenarios/route-tree-scale` measures navigation over an existing tree, not +construction. `scenarios/mount` includes construction but also rendering and +loading. To isolate initialization, use the core construction benchmark: + +```bash +CI=1 NX_DAEMON=false pnpm nx run @tanstack/router-core:test:unit --outputStyle=stream --skipRemoteCache -- bench tests/route-tree-construction.bench.ts --run --testNamePattern=1000.routes --reporter=json --outputFile=/tmp/route-tree-construction.json +``` + +It covers 100, 1,000, and 10,000 static, dynamic, nested, or mixed routes. +The processing-only case creates fresh route objects in an untimed +`beforeEach`, then measures `processRouteTree` and `route.init`. A separate +case includes route-object creation. Neither case measures first interpolation +or navigation. Remove the name filter to run all sizes. Compare identical +benchmark sources in separate checkouts and repeat fresh processes; a cached +router or repeatedly initialized tree is not a construction baseline. + +## Opt-in React Link performance suite + +`link-performance/` contains additional client-navigation and SSR workloads for +focused Link work. They are **not included** in the regular client-nav/SSR +aggregate projects or their CodSpeed build dependencies; they only run through +the dedicated `@benchmarks/react-link-performance` targets below. Use `-t` to +narrow a run to specific cases. + +```bash +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:perf:client --outputStyle=stream --skipRemoteCache -- --run +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:perf:ssr --outputStyle=stream --skipRemoteCache -- --run + +# Select a feature and save the normal Vitest JSON report. +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:perf:client --outputStyle=stream --skipRemoteCache -- --run -t "updater|optional|splat" --reporter=json --outputFile=/tmp/link-perf.json +``` + +The cases cover repeated versus unique destination params, updater functions, +relative/inherited values, search middleware chains, param stringification, +optional and splat segments, encoding, masks, basepath/rewrites, and active +props with structured search. These exercise different costs: cache hits and +misses, parameter cloning, callbacks, middleware traversal, URI encoding, +building masked/public locations, active-state comparisons, and prop merging. +Existing preload, mount, and route-tree-scale scenarios remain responsible for +those separate workloads. + +- **Client:** 200 persistent measured Links, four control Links, and eight + completed navigations per timed batch. The existing client harness checks + hrefs and active state during its untimed warm-up lap. Control navigations + replace the history entry, keeping history size constant. Post-measurement + assertions also check that the measured anchors stayed mounted. +- **SSR:** four fresh-router requests per timed batch, each rendering 200 + measured Links through `RouterProvider` and `renderToString`. Router creation, + `router.load()`, rendering, and history cleanup are included. This isolates + Router SSR Link work, not Start HTTP handling, dehydration, or streaming. + HTML assertions run outside the timed batch. +- Both use the same code-based workload definitions and production JSX/library + builds. The regular Vitest entry points use at least 100 warm-up iterations, + one second of warm-up time, and five-second measurement windows. The client + and server bundles assert their resolved `isServer` environment. React and + React DOM remain external so comparisons can share the same renderer runtime. + These bundles are Node-hosted (jsdom for client mode), not browser deployments. + +Run the gate tests and typecheck separately: + +```bash +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:unit --outputStyle=stream --skipRemoteCache +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:types --outputStyle=stream --skipRemoteCache +``` + +For before/after comparisons, use identical benchmark files and dependencies +on both refs, build each ref through its Nx targets, and alternate fresh +Vitest processes. Report the actual refs, per-case means and relative margins +of error; rerun noisy or borderline results with `-t` rather than interpreting +a small difference as a proven speedup. Client and SSR times have different +batch units and should not be compared directly. + +### Stable paired comparisons + +For regression decisions, prefer the paired runner over a whole-file Vitest +run. It starts a fresh process for every case and repetition, avoiding JIT +feedback from earlier cases. Inside each process, both revisions share the +same production React installation but have separate router/app modules and +router instances. Initialization order alternates between repetitions. +Built snapshots are staged under `node_modules/.cache` so the TypeScript +harness loader does not transpile their emitted JavaScript a second time. + +```bash +# Build the baseline using these same benchmark sources in its own checkout. +# --baseline points to that checkout's link-performance/dist directory. +pnpm nx run @benchmarks/react-link-performance:test:perf:stable -- \ + --baseline /path/to/baseline/benchmarks/client-nav/link-performance/dist \ + --outputJson /tmp/paired-links.json + +# Narrow a comparison, or increase independent process repetitions. +pnpm nx run @benchmarks/react-link-performance:test:perf:stable -- \ + --baseline /path/to/baseline/benchmarks/client-nav/link-performance/dist \ + --mode ssr -t "middleware|unique-params" --repeats 6 \ + --outputJson /tmp/paired-links-ssr.json +``` + +The runner requires Node with `process.threadCpuUsage` (Node 24 works). +It fixes V8 random/hash seeds, warms each variant for at least two seconds +and 100 batches, then alternates ABBA/BAAB blocks calibrated to roughly 500 ms. +Both variants do exactly the same number of batches per block. It records +main-thread CPU time, wall time, and whole-process CPU time; GC during +measurement is not disabled or discarded. + +The default is four independent process repetitions. Reported 95% intervals +use their paired log-ratios, not the many correlated batches as independent +samples. A faster/slower verdict requires CPU and wall intervals to agree. +Intervals overlapping zero or disagreeing metrics are inconclusive; narrow +intervals entirely inside +/-2% are reported separately. + +An A/A calibration uses the current `dist` directory as `--baseline`. Its +intervals should contain zero before trusting similarly sized A/B differences. +Shared-machine contention can still make small changes unresolved. Do not +interpret a point estimate alone, or an inconclusive result, as proof that +a workload is unchanged. diff --git a/benchmarks/client-nav/link-performance/cases.ts b/benchmarks/client-nav/link-performance/cases.ts new file mode 100644 index 0000000000..a25eac563b --- /dev/null +++ b/benchmarks/client-nav/link-performance/cases.ts @@ -0,0 +1,360 @@ +export const LINK_CASES = [ + { + id: 'shared-params', + label: 'Shared string params', + description: '200 persistent Links reuse 40 string parameter values.', + }, + { + id: 'unique-params', + label: 'Unique string params', + description: '200 distinct parameter values exceed the 128-result cache.', + }, + { + id: 'param-updaters', + label: 'Parameter updaters', + description: 'Parameter functions derive destinations from current params.', + }, + { + id: 'location-updaters', + label: 'Search, hash and state updaters', + description: + 'Functions derive search, hash and history state from the source.', + }, + { + id: 'relative', + label: 'Relative targets', + description: 'Parent and child targets inherit current params and search.', + }, + { + id: 'middleware', + label: 'Search middleware chain', + description: + 'Retain a tenant, strip a default page and normalize a filter.', + }, + { + id: 'numeric-params', + label: 'Numeric params', + description: 'Parse numbers, update them numerically and stringify them.', + }, + { + id: 'optional-params', + label: 'Optional segments', + description: 'Set, inherit and explicitly clear an optional path segment.', + }, + { + id: 'splats', + label: 'Splat params', + description: 'Empty, multi-segment and encoded splat values.', + }, + { + id: 'encoding', + label: 'Allowed path characters', + description: 'Preserve allowed @, : and + while encoding other characters.', + }, + { + id: 'masks', + label: 'Explicit route masks', + description: + 'Build a different public path and search for each destination.', + }, + { + id: 'rewrites', + label: 'Basepath and rewrites', + description: 'Compose /app with input/output locale path rewrites.', + }, + { + id: 'active', + label: 'Active props and structured search', + description: + 'Exact, fuzzy and search matching with props and render children.', + }, +] as const + +export type LinkCaseId = (typeof LINK_CASES)[number]['id'] + +export const LINK_COUNT = 200 +export const NAVIGATION_STATES = [1, 2, 3, 0] as const +export const LOCALES = ['en', 'fr', 'de', 'es'] as const + +export interface Filter { + tag: string + flags: { open: boolean } + tags: Array +} + +export interface LinkSearch { + page?: number + tenant?: string + filter?: Filter +} + +export function sourceFilter(index: number): Filter { + return { + tag: `group-${index}`, + flags: { open: index % 2 === 0 }, + tags: ['links', `state-${index}`], + } +} + +export function sourceSearch( + caseId: LinkCaseId, + stateIndex: number, +): Partial { + switch (caseId) { + case 'location-updaters': + case 'relative': + case 'middleware': + case 'active': + return { + page: stateIndex + 1, + tenant: `tenant-${stateIndex}`, + filter: sourceFilter(stateIndex), + } + case 'rewrites': + return { tenant: LOCALES[stateIndex] } + default: + return {} + } +} + +export function optionalCategory(stateIndex: number) { + return stateIndex % 2 === 0 ? `category-${stateIndex}` : undefined +} + +export function splatValue(index: number) { + switch (index % 4) { + case 0: + return '' + case 1: + return `folder/sub/file-${index % 40}` + case 2: + return 'a b/100%/caf\u00e9?#' + default: + return 'literal%2F/\u{1f680}' + } +} + +export function encodedValue(index: number) { + return `user-${index % 40}@mail.test:tag+value /?#% caf\u00e9` +} + +function url(pathname: string, search: Partial = {}, hash = '') { + const result = new URL(pathname, 'http://localhost') + for (const [key, value] of Object.entries( + search, + )) { + if (value !== undefined) { + result.searchParams.set( + key, + typeof value === 'object' ? JSON.stringify(value) : String(value), + ) + } + } + result.hash = hash + return result.pathname + result.search + result.hash +} + +function sourcePath(caseId: LinkCaseId, stateIndex: number) { + switch (caseId) { + case 'relative': + return `/teams/team-${stateIndex}/item-${stateIndex}` + case 'numeric-params': + return `/numbers/${stateIndex}` + case 'optional-params': { + const category = optionalCategory(stateIndex) + return `/optional/${category ? `${category}/` : ''}item-${stateIndex}` + } + case 'splats': + return `/files/source/state-${stateIndex}` + case 'encoding': + return `/encoded/source-${stateIndex}` + case 'active': + return `/items/item-${stateIndex}/details` + default: + return `/items/item-${stateIndex}` + } +} + +export function getSourceUrl(caseId: LinkCaseId, stateIndex: number): string { + if (!Number.isInteger(stateIndex) || stateIndex < 0 || stateIndex > 3) { + throw new Error(`Invalid Link performance state: ${stateIndex}`) + } + const pathname = sourcePath(caseId, stateIndex) + if (caseId === 'rewrites') { + return `/app/${LOCALES[stateIndex]}${pathname}` + } + return url( + pathname, + sourceSearch(caseId, stateIndex), + caseId === 'location-updaters' ? `source-${stateIndex}` : '', + ) +} + +// These expectations use fixture values and platform encoding, not router APIs. +function expectedHref(caseId: LinkCaseId, stateIndex: number, index: number) { + const itemId = `item-${index % 40}` + switch (caseId) { + case 'shared-params': + return `/items/${itemId}` + case 'unique-params': + return `/items/item-${index}` + case 'param-updaters': + return `/items/item-${stateIndex}-related-${index % 40}` + case 'location-updaters': + return url( + `/items/item-${stateIndex}`, + { + ...sourceSearch(caseId, stateIndex), + page: stateIndex + 2 + (index % 5), + }, + `source-${stateIndex}-link-${index % 5}`, + ) + case 'relative': + return url( + index % 2 === 0 + ? `/teams/team-${stateIndex}` + : `/teams/team-${stateIndex}/item-${stateIndex}/details`, + sourceSearch(caseId, stateIndex), + ) + case 'middleware': + return url(`/filtered/${itemId}`, { + tenant: `tenant-${stateIndex}`, + page: index % 2 === 0 ? undefined : 2, + filter: { ...sourceFilter(index % 4), tag: `LABEL-${index % 40}` }, + }) + case 'numeric-params': + return `/numbers/${stateIndex + (index % 40)}` + case 'optional-params': { + const category = + index % 3 === 0 + ? 'fixed' + : index % 3 === 1 + ? optionalCategory(stateIndex) + : undefined + return `/optional/${category ? `${category}/` : ''}${itemId}` + } + case 'splats': { + const value = splatValue(index) + return `/files${value ? `/${value.split('/').map(encodeURIComponent).join('/')}` : ''}` + } + case 'encoding': { + const value = encodeURIComponent(encodedValue(index)) + .replaceAll('%40', '@') + .replaceAll('%3A', ':') + .replaceAll('%2B', '+') + return `/encoded/${value}` + } + case 'masks': + return url(`/public/display-${index % 40}`, { + tenant: `mask-${index % 4}`, + }) + case 'rewrites': + return url(`/app/${LOCALES[index % 4]}/items/${itemId}`, { + page: (index % 3) + 1, + }) + case 'active': { + const item = Math.floor(index / 5) + const variant = index % 5 + const search = + variant < 3 + ? { filter: sourceFilter(item % 4) } + : { + ...sourceSearch('active', item % 4), + ...(variant === 4 ? { filter: undefined } : {}), + } + return url(`/items/item-${item}${variant < 2 ? '' : '/details'}`, search) + } + } +} + +function assertUrl( + actualHref: string | null, + expectedHref: string, + label: string, +) { + if (actualHref === null) { + throw new Error(`${label}: missing href`) + } + const actual = new URL(actualHref, 'http://localhost') + const expected = new URL(expectedHref, 'http://localhost') + // Query ordering and the platform's '+' versus '%20' are immaterial here. + const query = (value: URL) => + JSON.stringify([...value.searchParams.entries()].sort()) + if ( + actual.origin !== expected.origin || + actual.pathname !== expected.pathname || + actual.hash !== expected.hash || + query(actual) !== query(expected) + ) { + throw new Error( + `${label}: expected ${expectedHref}, received ${actualHref}`, + ) + } +} + +export function assertScenario( + caseId: LinkCaseId, + stateIndex: number, + root: ParentNode, +): void { + const source = root.querySelector('[data-testid="source-path"]') + if (source?.textContent !== sourcePath(caseId, stateIndex)) { + throw new Error( + `${caseId}/${stateIndex}: unexpected source path ${source?.textContent}`, + ) + } + const links = root.querySelectorAll('a[data-perf-link]') + if (links.length !== LINK_COUNT) { + throw new Error( + `${caseId}: expected ${LINK_COUNT} Links, got ${links.length}`, + ) + } + for (const [index, link] of links.entries()) { + const label = `${caseId}/${stateIndex}/link-${index}` + if (link.getAttribute('data-perf-link') !== String(index)) { + throw new Error(`${label}: unexpected Link order`) + } + assertUrl( + link.getAttribute('href'), + expectedHref(caseId, stateIndex, index), + label, + ) + let active: boolean | undefined + if (caseId === 'shared-params') { + active = index % 40 === stateIndex + } else if (caseId === 'unique-params') { + active = index === stateIndex + } else if (caseId === 'active') { + active = + Math.floor(index / 5) === stateIndex && [0, 2, 3].includes(index % 5) + if ( + link.textContent !== `${index}:${active ? 'active' : 'inactive'}` || + link.getAttribute('title') !== (active ? 'active' : 'inactive') || + !link.classList.contains(active ? 'perf-active' : 'perf-inactive') || + link.style.color !== (active ? 'green' : 'gray') || + link.style.opacity !== '0.8' + ) { + throw new Error( + `${label}: active props or render children are incorrect`, + ) + } + } + if ( + active !== undefined && + (link.getAttribute('data-status') === 'active') !== active + ) { + throw new Error(`${label}: expected active=${active}`) + } + } + for (let state = 0; state < 4; state++) { + const control = root.querySelector(`[data-testid="go-state-${state}"]`) + if (!control || control.hasAttribute('data-perf-link')) { + throw new Error(`${caseId}: missing or measured control Link ${state}`) + } + assertUrl( + control.getAttribute('href'), + getSourceUrl(caseId, state), + `${caseId}/control-${state}`, + ) + } +} diff --git a/benchmarks/client-nav/link-performance/client.bench.ts b/benchmarks/client-nav/link-performance/client.bench.ts new file mode 100644 index 0000000000..f819fab52b --- /dev/null +++ b/benchmarks/client-nav/link-performance/client.bench.ts @@ -0,0 +1,30 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../cpu-simulation' +import { LINK_CASES } from './cases' +import { createClientScenario, samplingOptions } from './scenario' +import type * as App from './src/client' + +const appModulePath = './dist/client/app.js' +const app: typeof App = await import(/* @vite-ignore */ appModulePath) +if (app.serverEnvironment !== false) { + throw new Error('Link client benchmarks must use the production client build') +} + +for (const { id, label } of LINK_CASES) { + test(label, async ({ bench }) => { + const scenario = createClientScenario(app, id) + function finish() { + try { + scenario.check() + } finally { + scenario.teardown() + } + } + + await bench( + `client Links: ${id}`, + benchLifecycle({ before: scenario.setup, after: finish }), + scenario.batch, + ).run(samplingOptions) + }) +} diff --git a/benchmarks/client-nav/link-performance/config.test.ts b/benchmarks/client-nav/link-performance/config.test.ts new file mode 100644 index 0000000000..1a468a3169 --- /dev/null +++ b/benchmarks/client-nav/link-performance/config.test.ts @@ -0,0 +1,42 @@ +import { afterEach, describe, expect, test, vi } from 'vitest' +import { createLinkPerformanceConfig } from './config' + +afterEach(() => vi.unstubAllEnvs()) + +describe.each(['client', 'ssr'] as const)('%s configuration', (target) => { + test('discovers only the requested suite', () => { + const config = createLinkPerformanceConfig(target) + expect(config.test?.benchmark?.include).toEqual([`${target}.bench.ts`]) + }) + + test('builds production code for the correct environment', () => { + const config = createLinkPerformanceConfig(target) + expect(config.define?.['process.env.NODE_ENV']).toBe('"production"') + expect(config.resolve?.conditions).toContain( + target === 'ssr' ? 'node' : 'browser', + ) + expect(config.build?.ssr).toBe(target === 'ssr') + expect(config.build?.outDir).toBe(`./dist/${target}`) + expect(config.build?.rolldownOptions?.platform).toBe('node') + expect(config.build?.rolldownOptions?.external).toEqual([ + 'node:module', + 'module', + /^react(?:\/|$)/, + /^react-dom(?:\/|$)/, + ]) + }) + + test('does not retransform built bundles in the test environment', () => { + vi.stubEnv('VITEST', 'true') + const config = createLinkPerformanceConfig(target) + expect(config.ssr?.noExternal).toBeUndefined() + expect(config.test?.server?.deps?.external).toEqual([ + /\/link-performance\/dist\//, + ]) + }) + + test('bundles router dependencies when building app snapshots', () => { + vi.stubEnv('VITEST', undefined) + expect(createLinkPerformanceConfig(target).ssr?.noExternal).toBe(true) + }) +}) diff --git a/benchmarks/client-nav/link-performance/config.ts b/benchmarks/client-nav/link-performance/config.ts new file mode 100644 index 0000000000..416b027057 --- /dev/null +++ b/benchmarks/client-nav/link-performance/config.ts @@ -0,0 +1,69 @@ +import { fileURLToPath } from 'node:url' +import react from '@vitejs/plugin-react' +import codspeedPlugin from '@codspeed/vitest-plugin' +import type { UserConfig } from 'vite' + +const root = fileURLToPath(new URL('.', import.meta.url)) + +export function createLinkPerformanceConfig( + target: 'client' | 'ssr', +): UserConfig { + const server = target === 'ssr' + + return { + root, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + react(), + ], + resolve: { + conditions: [server ? 'node' : 'browser', 'production'], + }, + ssr: { + noExternal: process.env.VITEST ? undefined : true, + resolve: { + conditions: ['node', 'production'], + }, + }, + build: { + outDir: `./dist/${target}`, + emptyOutDir: true, + minify: false, + ssr: server, + lib: { + entry: `${root}src/${target}.tsx`, + formats: ['es'], + fileName: 'app', + }, + rolldownOptions: { + platform: 'node', + external: [ + 'node:module', + 'module', + /^react(?:\/|$)/, + /^react-dom(?:\/|$)/, + ], + output: { entryFileNames: 'app.js' }, + }, + }, + test: { + name: `react-link-performance-${target}`, + watch: false, + environment: server ? 'node' : 'jsdom', + setupFiles: server ? [] : ['../vitest.setup.ts'], + server: { + deps: { + external: [/\/link-performance\/dist\//], + }, + }, + include: [], + benchmark: { + include: [`${target}.bench.ts`], + }, + }, + } +} diff --git a/benchmarks/client-nav/link-performance/project.json b/benchmarks/client-nav/link-performance/project.json new file mode 100644 index 0000000000..fd1751c081 --- /dev/null +++ b/benchmarks/client-nav/link-performance/project.json @@ -0,0 +1,103 @@ +{ + "name": "@benchmarks/react-link-performance", + "projectType": "application", + "tags": ["optional-benchmark"], + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config ./link-performance/vite.client.config.ts", + "cwd": "benchmarks/client-nav" + } + }, + "build:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config ./link-performance/vite.ssr.config.ts", + "cwd": "benchmarks/client-nav" + } + }, + "test:perf:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./link-performance/vite.client.config.ts", + "cwd": "benchmarks/client-nav" + } + }, + "test:perf:ssr": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:ssr"], + "options": { + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./link-performance/vite.ssr.config.ts", + "cwd": "benchmarks/client-nav" + } + }, + "test:perf:stable": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client", "build:ssr"], + "options": { + "command": "NODE_ENV=production node --import=@swc-node/register/esm-register benchmarks/client-nav/link-performance/stable-runner.ts" + } + }, + "test:unit": { + "executor": "nx:run-commands", + "inputs": [ + "...", + "{workspaceRoot}/benchmarks/client-nav/scenarios/harness.ts", + "{workspaceRoot}/benchmarks/client-nav/scenarios/links/shared.ts", + "{workspaceRoot}/benchmarks/client-nav/setup-helpers.ts", + "{workspaceRoot}/benchmarks/client-nav/tsconfig.json" + ], + "dependsOn": [ + { + "projects": ["@tanstack/history"], + "target": "build" + } + ], + "options": { + "command": "vitest run --config ./link-performance/vitest.config.ts", + "cwd": "benchmarks/client-nav" + } + }, + "test:types": { + "executor": "nx:run-commands", + "inputs": [ + "...", + "{workspaceRoot}/benchmarks/client-nav/jsdom.ts", + "{workspaceRoot}/benchmarks/client-nav/scenarios/harness.ts", + "{workspaceRoot}/benchmarks/client-nav/scenarios/links/shared.ts", + "{workspaceRoot}/benchmarks/client-nav/setup-helpers.ts", + "{workspaceRoot}/benchmarks/client-nav/tsconfig.json", + "{workspaceRoot}/benchmarks/client-nav/vitest.setup.ts" + ], + "dependsOn": [ + { + "projects": ["@tanstack/react-router"], + "target": "build" + } + ], + "options": { + "command": "tsc -p ./link-performance/tsconfig.json --noEmit", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/link-performance/scenario.ts b/benchmarks/client-nav/link-performance/scenario.ts new file mode 100644 index 0000000000..f1a3fb6df7 --- /dev/null +++ b/benchmarks/client-nav/link-performance/scenario.ts @@ -0,0 +1,114 @@ +import { JSDOM } from 'jsdom' +import { createScenarioSetup } from '../scenarios/harness' +import { ticksPerIteration } from '../scenarios/links/shared' +import { NAVIGATION_STATES, assertScenario, getSourceUrl } from './cases' +import type { LinkCaseId } from './cases' +import type * as ClientApp from './src/client' +import type * as SsrApp from './src/ssr' + +export interface LinkScenario { + setup: () => Promise + batch: () => Promise + check: () => void + teardown: () => void +} + +export const samplingOptions = { + warmupIterations: 100, + warmupTime: 1_000, + time: 5_000, + throws: true, +} + +export function createClientScenario( + app: typeof ClientApp, + id: LinkCaseId, +): LinkScenario { + let mounted: ReturnType | undefined + let container: HTMLElement | undefined + let anchors: Array = [] + const test = createScenarioSetup({ + frameworkLabel: 'React', + mount: (element, history) => { + container = element + mounted = app.mountTestApp(element, history, id) + return mounted + }, + initialUrl: getSourceUrl(id, 0), + steps: NAVIGATION_STATES.map((state) => `go-state-${state}`), + assertAfterStep: (index, element) => { + assertScenario(id, NAVIGATION_STATES[index]!, element) + if (!mounted) { + throw new Error('Link benchmark app was not mounted') + } + mounted.assertStateUpdates() + }, + }) + + return { + async setup() { + await test.before() + if (!container) { + throw new Error('Link benchmark container was not created') + } + anchors = [...container.querySelectorAll('a[data-perf-link]')] + }, + async batch() { + for (let index = 0; index < ticksPerIteration; index++) { + await test.tick() + } + await test.finishBatch() + }, + check() { + if (!container || !mounted) { + throw new Error('Link benchmark app was not mounted') + } + assertScenario(id, 0, container) + mounted.assertStateUpdates() + if (mounted.router.history.length !== 1) { + throw new Error('Link benchmark history must remain bounded') + } + const current = container.querySelectorAll('a[data-perf-link]') + if (anchors.some((anchor, index) => current[index] !== anchor)) { + throw new Error('Measured Links must stay mounted across navigations') + } + }, + teardown: test.after, + } +} + +export function createSsrScenario( + app: typeof SsrApp, + id: LinkCaseId, +): LinkScenario { + let html = '' + let state = 0 + function check() { + const dom = new JSDOM(html) + try { + assertScenario(id, state, dom.window.document) + } finally { + dom.window.close() + } + } + + return { + async setup() { + for (const nextState of NAVIGATION_STATES) { + state = nextState + html = await app.renderScenario(id, state, true) + check() + } + }, + async batch() { + for (const nextState of NAVIGATION_STATES) { + state = nextState + html = await app.renderScenario(id, state) + } + }, + check, + teardown() { + html = '' + }, + } +} diff --git a/benchmarks/client-nav/link-performance/src/client.tsx b/benchmarks/client-nav/link-performance/src/client.tsx new file mode 100644 index 0000000000..a187ee8c15 --- /dev/null +++ b/benchmarks/client-nav/link-performance/src/client.tsx @@ -0,0 +1,29 @@ +import { RouterProvider } from '@tanstack/react-router' +import { isServer } from '@tanstack/router-core/isServer' +import { createRoot } from 'react-dom/client' +import { assertStateUpdates, createLinkRouter } from './workload' +import type { LinkRouter } from './workload' +import type { RouterHistory } from '@tanstack/history' +import type { LinkCaseId } from '../cases' + +export const serverEnvironment: boolean | undefined = isServer + +export function mountTestApp( + container: HTMLElement, + history: RouterHistory, + caseId: LinkCaseId, +): { + router: LinkRouter + unmount: () => void + assertStateUpdates: () => void +} { + const router = createLinkRouter(caseId, history, false) + const root = createRoot(container) + root.render() + + return { + router, + unmount: () => root.unmount(), + assertStateUpdates: () => assertStateUpdates(router), + } +} diff --git a/benchmarks/client-nav/link-performance/src/ssr.tsx b/benchmarks/client-nav/link-performance/src/ssr.tsx new file mode 100644 index 0000000000..491191b1f9 --- /dev/null +++ b/benchmarks/client-nav/link-performance/src/ssr.tsx @@ -0,0 +1,29 @@ +import { RouterProvider, createMemoryHistory } from '@tanstack/react-router' +import { isServer } from '@tanstack/router-core/isServer' +import { renderToString } from 'react-dom/server' +import { getSourceUrl } from '../cases' +import { assertStateUpdates, createLinkRouter } from './workload' +import type { LinkCaseId } from '../cases' + +export const serverEnvironment: boolean | undefined = isServer + +export async function renderScenario( + caseId: LinkCaseId, + stateIndex: number, + verify = false, +) { + const history = createMemoryHistory({ + initialEntries: [getSourceUrl(caseId, stateIndex)], + }) + const router = createLinkRouter(caseId, history, true) + try { + await router.load() + const html = renderToString() + if (verify) { + assertStateUpdates(router) + } + return html + } finally { + history.destroy() + } +} diff --git a/benchmarks/client-nav/link-performance/src/workload.tsx b/benchmarks/client-nav/link-performance/src/workload.tsx new file mode 100644 index 0000000000..8315b85b8b --- /dev/null +++ b/benchmarks/client-nav/link-performance/src/workload.tsx @@ -0,0 +1,506 @@ +import { + Link, + Outlet, + createRootRouteWithContext, + createRoute, + createRouter, + linkOptions, + retainSearchParams, + stripSearchParams, + useLocation, +} from '@tanstack/react-router' +import { + LINK_COUNT, + LOCALES, + encodedValue, + optionalCategory, + sourceFilter, + sourceSearch, + splatValue, +} from '../cases' +import type { RouterHistory } from '@tanstack/history' +import type { SearchSchemaInput } from '@tanstack/react-router' +import type { Filter, LinkCaseId, LinkSearch } from '../cases' + +interface StateUpdates { + calls: number + verifiedCalls: number + input: number + output: number + offset: number +} + +interface WorkloadContext { + caseId: LinkCaseId + stateUpdates: StateUpdates +} + +function isFilter(value: unknown): value is Filter { + return ( + typeof value === 'object' && + value !== null && + 'tag' in value && + typeof value.tag === 'string' && + 'flags' in value && + typeof value.flags === 'object' && + value.flags !== null && + 'open' in value.flags && + typeof value.flags.open === 'boolean' && + 'tags' in value && + Array.isArray(value.tags) && + value.tags.every((tag: unknown) => typeof tag === 'string') + ) +} + +const rootRoute = createRootRouteWithContext()({ + validateSearch: ( + search: Record & SearchSchemaInput, + ): LinkSearch => ({ + page: typeof search.page === 'number' ? search.page : undefined, + tenant: typeof search.tenant === 'string' ? search.tenant : undefined, + filter: isFilter(search.filter) ? search.filter : undefined, + }), + component: RootLayout, +}) + +const itemsRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'items/$itemId', +}) +const detailsRoute = createRoute({ + getParentRoute: () => itemsRoute, + path: 'details', +}) +const teamRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'teams/$teamId', +}) +const teamItemRoute = createRoute({ + getParentRoute: () => teamRoute, + path: '$itemId', +}) +const teamDetailsRoute = createRoute({ + getParentRoute: () => teamItemRoute, + path: 'details', +}) +const filteredRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'filtered/$itemId', + search: { + middlewares: [ + retainSearchParams(['tenant']), + stripSearchParams({ page: 1 }), + ({ search, next }) => { + const result = next(search) + return { + ...result, + filter: result.filter + ? { ...result.filter, tag: result.filter.tag.trim().toUpperCase() } + : undefined, + } + }, + ], + }, +}) +const numericRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'numbers/$number', + params: { + parse: ({ number }) => { + const value = Number(number) + if (!Number.isFinite(value)) { + throw new Error(`Invalid number: ${number}`) + } + return { number: value } + }, + stringify: ({ number }) => ({ number: String(number) }), + }, +}) +const optionalRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'optional/{-$category}/$itemId', +}) +const splatRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'files/$', +}) +const encodedRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'encoded/$value', +}) +const publicRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'public/$itemId', +}) + +const routeTree = rootRoute.addChildren([ + itemsRoute.addChildren([detailsRoute]), + teamRoute.addChildren([teamItemRoute.addChildren([teamDetailsRoute])]), + filteredRoute, + numericRoute, + optionalRoute, + splatRoute, + encodedRoute, + publicRoute, +]) + +const localeRewrite = { + input: ({ url }: { url: URL }) => { + const match = /^\/(en|fr|de|es)(\/.*)$/.exec(url.pathname) + if (match) { + url.pathname = match[2]! + url.searchParams.set('tenant', match[1]!) + } + return url + }, + output: ({ url }: { url: URL }) => { + const locale = url.searchParams.get('tenant') + if (locale) { + url.searchParams.delete('tenant') + url.pathname = `/${locale}${url.pathname}` + } + return url + }, +} + +export function createLinkRouter( + caseId: LinkCaseId, + history: RouterHistory, + isServer: boolean, +) { + const context: WorkloadContext = { + caseId, + stateUpdates: { + calls: 0, + verifiedCalls: 0, + input: 0, + output: 0, + offset: 0, + }, + } + return createRouter({ + routeTree, + history, + isServer, + context, + scrollRestoration: false, + defaultPreload: false, + trailingSlash: 'never', + pathParamsAllowedCharacters: + caseId === 'encoding' ? ['@', ':', '+'] : undefined, + ...(caseId === 'rewrites' + ? { basepath: '/app', rewrite: localeRewrite } + : {}), + }) +} + +export type LinkRouter = ReturnType + +declare module '@tanstack/react-router' { + interface Register { + router: LinkRouter + } +} + +declare module '@tanstack/history' { + interface HistoryState { + linkPerfState?: number + } +} + +// Call alongside DOM assertions, outside the timed loop, after each sample. +export function assertStateUpdates(router: LinkRouter): void { + const { caseId, stateUpdates } = router.options.context + if (caseId !== 'location-updaters') { + return + } + const input = router.state.location.state.linkPerfState ?? 0 + if ( + stateUpdates.calls - stateUpdates.verifiedCalls < LINK_COUNT || + stateUpdates.input !== input || + stateUpdates.output !== input + stateUpdates.offset || + stateUpdates.offset < 1 || + stateUpdates.offset > 40 + ) { + throw new Error( + 'Link history-state updaters did not run with current state', + ) + } + stateUpdates.verifiedCalls = stateUpdates.calls +} + +function sourceOptions(caseId: LinkCaseId, stateIndex: number) { + const itemId = `item-${stateIndex}` + const common = { + search: sourceSearch(caseId, stateIndex), + hash: caseId === 'location-updaters' ? `source-${stateIndex}` : '', + state: { linkPerfState: stateIndex + 10 }, + } + switch (caseId) { + case 'relative': + return linkOptions({ + ...common, + to: '/teams/$teamId/$itemId', + params: { teamId: `team-${stateIndex}`, itemId }, + }) + case 'numeric-params': + return linkOptions({ + ...common, + to: '/numbers/$number', + params: { number: stateIndex }, + }) + case 'optional-params': + return linkOptions({ + ...common, + to: '/optional/{-$category}/$itemId', + params: { category: optionalCategory(stateIndex), itemId }, + }) + case 'splats': + return linkOptions({ + ...common, + to: '/files/$', + params: { _splat: `source/state-${stateIndex}` }, + }) + case 'encoding': + return linkOptions({ + ...common, + to: '/encoded/$value', + params: { value: `source-${stateIndex}` }, + }) + case 'active': + return linkOptions({ + ...common, + to: '/items/$itemId/details', + params: { itemId }, + }) + default: + return linkOptions({ + ...common, + to: '/items/$itemId', + params: { itemId }, + }) + } +} + +const indexes = Array.from({ length: LINK_COUNT }, (_, index) => index) +const controls = [0, 1, 2, 3] as const + +function SourcePath() { + const pathname = useLocation({ select: (location) => location.pathname }) + return {pathname} +} + +function RootLayout() { + const context = rootRoute.useRouteContext() + return ( + <> + + +
+ {indexes.map((index) => measuredLink(context, index))} +
+ + + ) +} + +function measuredLink( + { caseId, stateUpdates }: WorkloadContext, + index: number, +) { + const common = { + key: index, + 'data-perf-link': index, + preload: false, + children: `Link ${index}`, + } as const + const itemId = `item-${index % 40}` + switch (caseId) { + case 'shared-params': + case 'unique-params': + return ( + + ) + case 'param-updaters': + return ( + ({ + itemId: `${previous.itemId}-related-${index % 40}`, + })} + /> + ) + case 'location-updaters': + return ( + ({ + ...previous, + page: (previous.page ?? 1) + 1 + (index % 5), + })} + hash={(previous) => `${previous}-link-${index % 5}`} + state={(previous) => { + const input = previous.linkPerfState ?? 0 + const offset = (index % 40) + 1 + const output = input + offset + stateUpdates.calls++ + stateUpdates.input = input + stateUpdates.output = output + stateUpdates.offset = offset + return { ...previous, linkPerfState: output } + }} + /> + ) + case 'relative': + return ( + + ) + case 'middleware': + return ( + + ) + case 'numeric-params': + return ( + ({ number: previous.number + (index % 40) })} + /> + ) + case 'optional-params': + return ( + + ) + case 'splats': + return ( + + ) + case 'encoding': + return ( + + ) + case 'masks': + return ( + + ) + case 'rewrites': + return ( + + ) + case 'active': { + const item = Math.floor(index / 5) + const variant = index % 5 + return ( + ({ + className: 'perf-active', + title: 'active', + style: { color: 'green' }, + })} + inactiveProps={() => ({ + className: 'perf-inactive', + title: 'inactive', + style: { color: 'gray' }, + })} + > + {({ isActive }) => `${index}:${isActive ? 'active' : 'inactive'}`} + + ) + } + } +} diff --git a/benchmarks/client-nav/link-performance/ssr.bench.ts b/benchmarks/client-nav/link-performance/ssr.bench.ts new file mode 100644 index 0000000000..c30084e510 --- /dev/null +++ b/benchmarks/client-nav/link-performance/ssr.bench.ts @@ -0,0 +1,30 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../cpu-simulation' +import { LINK_CASES } from './cases' +import { createSsrScenario, samplingOptions } from './scenario' +import type * as App from './src/ssr' + +const appUrl = new URL('./dist/ssr/app.js', import.meta.url).href +const app: typeof App = await import(/* @vite-ignore */ appUrl) +if (app.serverEnvironment !== true) { + throw new Error('Link SSR benchmarks must use the production server build') +} + +for (const { id, label } of LINK_CASES) { + test(label, async ({ bench }) => { + const scenario = createSsrScenario(app, id) + function finish() { + try { + scenario.check() + } finally { + scenario.teardown() + } + } + + await bench( + `SSR Links: ${id}`, + benchLifecycle({ before: scenario.setup, after: finish }), + scenario.batch, + ).run(samplingOptions) + }) +} diff --git a/benchmarks/client-nav/link-performance/stable-runner.ts b/benchmarks/client-nav/link-performance/stable-runner.ts new file mode 100644 index 0000000000..59ccfa3cb4 --- /dev/null +++ b/benchmarks/client-nav/link-performance/stable-runner.ts @@ -0,0 +1,269 @@ +import { fork } from 'node:child_process' +import { createHash } from 'node:crypto' +import { + copyFileSync, + mkdirSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs' +import { dirname, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { parseArgs } from 'node:util' +import { LINK_CASES } from './cases' +import { createStagingDirectory } from './staging' +import { classify, mean, summarizeRatios } from './statistics' +import type { LinkCaseId } from './cases' +import type { + BlockSample, + Mode, + Variant, + WorkerRequest, + WorkerResponse, +} from './worker-protocol' + +const projectRoot = fileURLToPath(new URL('.', import.meta.url)) +const workspaceRoot = resolve(projectRoot, '../../..') + +function startWorker() { + const child = fork( + fileURLToPath(new URL('./stable-worker.ts', import.meta.url)), + { + cwd: workspaceRoot, + env: { ...process.env, NODE_ENV: 'production' }, + execArgv: [ + '--import=@swc-node/register/esm-register', + '--random-seed=42', + '--hash-seed=42', + ], + stdio: ['ignore', 'ignore', 'pipe', 'ipc'], + }, + ) + let stderr = '' + child.stderr?.on('data', (data: Buffer) => { + stderr = (stderr + data.toString()).slice(-4_096) + }) + + function request(message: WorkerRequest): Promise { + return new Promise((resolveResponse, reject) => { + const timeout = setTimeout(() => { + finish( + new Error(`Sampling worker timed out: ${message.kind}\n${stderr}`), + ) + }, 60_000) + const onExit = (code: number | null) => + finish(new Error(`Sampling worker exited (${code})\n${stderr}`)) + const onError = (error: Error) => finish(error) + const onMessage = (response: WorkerResponse) => { + if (response.kind === 'error') { + finish(new Error(response.message)) + } else { + finish(undefined, response) + } + } + function finish(error?: Error, response?: WorkerResponse) { + clearTimeout(timeout) + child.off('message', onMessage) + child.off('error', onError) + child.off('exit', onExit) + if (error) { + reject(error) + } else if (response) { + resolveResponse(response) + } + } + child.once('message', onMessage) + child.once('error', onError) + child.once('exit', onExit) + child.send(message, (error) => { + if (error) { + finish(error) + } + }) + }) + } + + return { + request, + kill: () => child.kill(), + } +} + +async function sampleReplica( + mode: Mode, + caseId: LinkCaseId, + baseline: string, + current: string, + replica: number, +) { + const worker = startWorker() + const samples: Array> = [[], []] + const ratios: Array<{ cpu: number; wall: number }> = [] + try { + const starts: Array = [] + // Balance module initialization and which variant finishes warming last. + const startupOrder: Array = replica % 2 ? [1, 0] : [0, 1] + for (const index of startupOrder) { + const ready = await worker.request({ + kind: 'init', + mode, + caseId, + bundle: index === 0 ? baseline : current, + variant: index, + }) + if (ready.kind !== 'ready') { + throw new Error('Expected a ready sampling worker') + } + starts[index] = ready.batchMs + } + const iterations = Math.max(1, Math.ceil(500 / Math.min(...starts))) + for (let round = 0; round < 2; round++) { + const block: Array> = [[], []] + const order: Array = + (round + replica) % 2 ? [1, 0, 0, 1] : [0, 1, 1, 0] + for (const index of order) { + const result = await worker.request({ + kind: 'measure', + iterations, + variant: index, + }) + if (result.kind !== 'sample') { + throw new Error('Expected a block measurement') + } + samples[index]!.push(result.sample) + block[index]!.push(result.sample) + } + ratios.push({ + cpu: + mean(block[1]!.map((s) => s.cpuMs)) / + mean(block[0]!.map((s) => s.cpuMs)), + wall: + mean(block[1]!.map((s) => s.wallMs)) / + mean(block[0]!.map((s) => s.wallMs)), + }) + } + const response = await worker.request({ kind: 'stop' }) + if (response.kind !== 'stopped') { + throw new Error('Expected successful post-measurement assertions') + } + return { + iterations, + baseline: samples[0]!, + current: samples[1]!, + cpuRatio: Math.exp(mean(ratios.map((r) => Math.log(r.cpu)))), + wallRatio: Math.exp(mean(ratios.map((r) => Math.log(r.wall)))), + } + } finally { + worker.kill() + } +} + +async function main() { + const { values } = parseArgs({ + options: { + baseline: { type: 'string' }, + current: { type: 'string', default: resolve(projectRoot, 'dist') }, + mode: { type: 'string', default: 'all' }, + repeats: { type: 'string', default: '4' }, + outputJson: { type: 'string' }, + testNamePattern: { type: 'string', short: 't' }, + }, + }) + if (!values.baseline || !values.outputJson) { + throw new Error( + 'Specify --baseline and --outputJson ', + ) + } + const repeats = Number(values.repeats) + if (!Number.isInteger(repeats) || repeats < 3 || repeats > 11) { + throw new Error('--repeats must be an integer between 3 and 11') + } + if (!['all', 'client', 'ssr'].includes(values.mode)) { + throw new Error('--mode must be all, client, or ssr') + } + const modes: Array = + values.mode === 'all' + ? ['client', 'ssr'] + : values.mode === 'client' + ? ['client'] + : ['ssr'] + const pattern = values.testNamePattern + ? new RegExp(values.testNamePattern) + : undefined + const cases = LINK_CASES.filter( + (c) => !pattern || pattern.test(`${c.label} ${c.id}`), + ) + if (!cases.length) { + throw new Error('No Link workloads match the requested pattern') + } + const report: { + protocol: string + node: string + complete: boolean + results: Array<{ + mode: Mode + caseId: LinkCaseId + baselineSha256: string + currentSha256: string + replicas: Array>> + cpu: ReturnType + wall: ReturnType + verdict: ReturnType + }> + } = { + protocol: + 'fresh process per case/replica; shared React runtime; separately loaded router variants; 2 ABBA/BAAB rounds; ~500ms calibrated fixed-work blocks; >=2s/100 batches warmup; main-thread CPU and wall time; fixed V8 random/hash seeds', + node: process.version, + complete: false, + results: [], + } + const output = resolve(values.outputJson) + mkdirSync(dirname(output), { recursive: true }) + const staging = createStagingDirectory() + try { + for (const mode of modes) { + const baselineInput = resolve(values.baseline, mode, 'app.js') + const currentInput = resolve(values.current, mode, 'app.js') + // Both snapshots resolve React from the same package installation. + const baseline = resolve(staging, `baseline-${mode}.mjs`) + const current = resolve(staging, `current-${mode}.mjs`) + copyFileSync(baselineInput, baseline) + copyFileSync(currentInput, current) + const digest = (file: string) => + createHash('sha256').update(readFileSync(file)).digest('hex') + const baselineSha256 = digest(baseline) + const currentSha256 = digest(current) + for (const { id } of cases) { + const replicas = [] + for (let replica = 0; replica < repeats; replica++) { + replicas.push( + await sampleReplica(mode, id, baseline, current, replica), + ) + } + const cpu = summarizeRatios(replicas.map((r) => r.cpuRatio)) + const wall = summarizeRatios(replicas.map((r) => r.wallRatio)) + const verdict = classify(cpu, wall) + report.results.push({ + mode, + caseId: id, + baselineSha256, + currentSha256, + replicas, + cpu, + wall, + verdict, + }) + writeFileSync(output, JSON.stringify(report, null, 2)) + console.log( + `${mode} ${id}: CPU ${cpu.changePercent.toFixed(2)}% [${cpu.low95.toFixed(2)}, ${cpu.high95.toFixed(2)}], wall ${wall.changePercent.toFixed(2)}% [${wall.low95.toFixed(2)}, ${wall.high95.toFixed(2)}] ${verdict}`, + ) + } + } + report.complete = true + writeFileSync(output, JSON.stringify(report, null, 2)) + } finally { + rmSync(staging, { recursive: true }) + } +} + +await main() diff --git a/benchmarks/client-nav/link-performance/stable-worker.test.ts b/benchmarks/client-nav/link-performance/stable-worker.test.ts new file mode 100644 index 0000000000..087b32414a --- /dev/null +++ b/benchmarks/client-nav/link-performance/stable-worker.test.ts @@ -0,0 +1,60 @@ +import { fork } from 'node:child_process' +import { rmdirSync, unlinkSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { expect, test } from 'vitest' +import { createStagingDirectory } from './staging' +import type { WorkerResponse } from './worker-protocol' + +test('loads emitted JavaScript without retranspiling it through SWC', async () => { + const directory = createStagingDirectory() + const bundle = join(directory, 'app.mjs') + const definition = 'function untouched ( ) { return 1 }' + writeFileSync( + bundle, + `${definition}\nawait Promise.resolve()\nthrow new Error(untouched.toString())`, + ) + const worker = fork( + fileURLToPath(new URL('./stable-worker.ts', import.meta.url)), + { + cwd: fileURLToPath(new URL('../../../', import.meta.url)), + execArgv: ['--import=@swc-node/register/esm-register'], + env: { ...process.env, NODE_ENV: 'production' }, + stdio: ['ignore', 'ignore', 'pipe', 'ipc'], + }, + ) + let stderr = '' + worker.stderr?.on('data', (data: Buffer) => { + stderr += data.toString() + }) + let timeout: ReturnType | undefined + try { + const result = new Promise((resolve, reject) => { + worker.once('message', (message: WorkerResponse) => resolve(message)) + worker.once('error', reject) + worker.once('exit', (code) => { + reject(new Error(`Worker exited (${code}): ${stderr}`)) + }) + timeout = setTimeout(() => { + reject(new Error(`Worker timed out: ${stderr}`)) + }, 5_000) + }) + worker.send({ + kind: 'init', + mode: 'ssr', + caseId: 'shared-params', + bundle, + variant: 0, + }) + const response = await result + expect(response.kind).toBe('error') + if (response.kind === 'error') { + expect(response.message).toContain(`Error: ${definition}`) + } + } finally { + clearTimeout(timeout) + worker.kill() + unlinkSync(bundle) + rmdirSync(directory) + } +}) diff --git a/benchmarks/client-nav/link-performance/stable-worker.ts b/benchmarks/client-nav/link-performance/stable-worker.ts new file mode 100644 index 0000000000..d98679dc15 --- /dev/null +++ b/benchmarks/client-nav/link-performance/stable-worker.ts @@ -0,0 +1,112 @@ +import { pathToFileURL } from 'node:url' +import { createClientScenario, createSsrScenario } from './scenario' +import type { LinkScenario } from './scenario' +import type { WorkerRequest, WorkerResponse } from './worker-protocol' +import type * as ClientApp from './src/client' +import type * as SsrApp from './src/ssr' + +const scenarios: Array = [] +const creationOrder: Array = [] +let closeWindow = () => {} + +function reply(response: WorkerResponse) { + if (!process.send) { + throw new Error('The Link sampling worker requires an IPC parent') + } + process.send(response) +} + +async function handle(request: WorkerRequest) { + if (request.kind === 'init') { + if (typeof process.threadCpuUsage !== 'function') { + throw new Error( + 'Stable sampling requires Node.js with process.threadCpuUsage', + ) + } + if (scenarios[request.variant]) { + throw new Error('A worker must only initialize each variant once') + } + let scenario: LinkScenario + const bundleUrl = pathToFileURL(request.bundle) + bundleUrl.searchParams.set('linkPerfVariant', String(request.variant)) + if (request.mode === 'client') { + const { window } = await import('../jsdom') + closeWindow = () => window.close() + const app: typeof ClientApp = await import(bundleUrl.href) + if (app.serverEnvironment !== false) { + throw new Error('Expected a production client bundle') + } + scenario = createClientScenario(app, request.caseId) + } else { + const app: typeof SsrApp = await import(bundleUrl.href) + if (app.serverEnvironment !== true) { + throw new Error('Expected a production SSR bundle') + } + scenario = createSsrScenario(app, request.caseId) + } + scenarios[request.variant] = scenario + creationOrder.push(scenario) + await scenario.setup() + const start = performance.now() + let iterations = 0 + do { + await scenario.batch() + iterations++ + } while (iterations < 100 || performance.now() - start < 2_000) + reply({ + kind: 'ready', + batchMs: (performance.now() - start) / iterations, + }) + return + } + if (request.kind === 'measure') { + const scenario = scenarios[request.variant] + if (!scenario) { + throw new Error('The sampling worker has not been initialized') + } + if (!Number.isInteger(request.iterations) || request.iterations < 1) { + throw new Error('Expected a positive batch count') + } + const cpuStart = process.threadCpuUsage() + const processStart = process.cpuUsage() + const start = performance.now() + for (let index = 0; index < request.iterations; index++) { + await scenario.batch() + } + const wallMs = performance.now() - start + const cpu = process.threadCpuUsage(cpuStart) + const processCpu = process.cpuUsage(processStart) + reply({ + kind: 'sample', + sample: { + iterations: request.iterations, + wallMs: wallMs / request.iterations, + cpuMs: (cpu.user + cpu.system) / 1_000 / request.iterations, + processCpuMs: + (processCpu.user + processCpu.system) / 1_000 / request.iterations, + }, + }) + return + } + try { + for (const scenario of creationOrder) { + scenario.check() + } + } finally { + for (const scenario of creationOrder.reverse()) { + scenario.teardown() + } + closeWindow() + } + reply({ kind: 'stopped' }) +} + +process.on('message', (request: WorkerRequest) => { + void handle(request).catch((error: unknown) => { + reply({ + kind: 'error', + message: + error instanceof Error ? error.stack || error.message : String(error), + }) + }) +}) diff --git a/benchmarks/client-nav/link-performance/staging.ts b/benchmarks/client-nav/link-performance/staging.ts new file mode 100644 index 0000000000..ac07d34c29 --- /dev/null +++ b/benchmarks/client-nav/link-performance/staging.ts @@ -0,0 +1,10 @@ +import { mkdirSync, mkdtempSync } from 'node:fs' +import { resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +export function createStagingDirectory() { + // SWC skips node_modules, leaving the emitted benchmark JavaScript intact. + const root = fileURLToPath(new URL('./node_modules/.cache/', import.meta.url)) + mkdirSync(root, { recursive: true }) + return mkdtempSync(resolve(root, 'link-performance-')) +} diff --git a/benchmarks/client-nav/link-performance/statistics.test.ts b/benchmarks/client-nav/link-performance/statistics.test.ts new file mode 100644 index 0000000000..8f5f37413b --- /dev/null +++ b/benchmarks/client-nav/link-performance/statistics.test.ts @@ -0,0 +1,36 @@ +import { expect, test } from 'vitest' +import { classify, mean, summarizeRatios } from './statistics' + +test('summarizes multiplicative paired changes across process replicas', () => { + const result = summarizeRatios([0.9, 0.9, 0.9, 0.9]) + expect(result.changePercent).toBeCloseTo(-10) + expect(result.low95).toBeCloseTo(-10) + expect(result.high95).toBeCloseTo(-10) + expect(result.replicas).toBe(4) +}) + +test('does not turn opposite noisy runs into a conclusive result', () => { + const result = summarizeRatios([0.9, 1.1, 0.95, 1.05]) + expect(result.low95).toBeLessThan(0) + expect(result.high95).toBeGreaterThan(0) + expect(classify(result, result)).toBe('inconclusive') +}) + +test('requires CPU and wall time to corroborate a direction', () => { + const slower = summarizeRatios([1.08, 1.09, 1.08, 1.09]) + const faster = summarizeRatios([0.9, 0.91, 0.9, 0.91]) + expect(classify(slower, slower)).toBe('slower') + expect(classify(faster, faster)).toBe('faster') + expect(classify(slower, faster)).toBe('inconclusive') + expect(classify(summarizeRatios([1, 1, 1]), summarizeRatios([1, 1, 1]))).toBe( + 'within-2%', + ) +}) + +test('rejects incomplete or invalid sampling data', () => { + expect(() => summarizeRatios([1])).toThrow() + expect(() => summarizeRatios([0, 1])).toThrow() + expect(() => summarizeRatios([NaN, 1])).toThrow() + expect(() => mean([])).toThrow() + expect(() => mean([Infinity])).toThrow() +}) diff --git a/benchmarks/client-nav/link-performance/statistics.ts b/benchmarks/client-nav/link-performance/statistics.ts new file mode 100644 index 0000000000..469bdaf65a --- /dev/null +++ b/benchmarks/client-nav/link-performance/statistics.ts @@ -0,0 +1,57 @@ +const critical95 = [ + 12.7062, 4.3027, 3.1824, 2.7764, 2.5706, 2.4469, 2.3646, 2.306, 2.2622, + 2.2281, +] + +export function mean(values: ReadonlyArray) { + if (!values.length || values.some((value) => !Number.isFinite(value))) { + throw new Error('Expected finite, nonempty samples') + } + return values.reduce((sum, value) => sum + value, 0) / values.length +} + +export function summarizeRatios(ratios: ReadonlyArray) { + if ( + ratios.length < 2 || + ratios.length > 11 || + ratios.some((value) => value <= 0) + ) { + throw new Error('Expected 2-11 independent positive process-replica ratios') + } + const logs = ratios.map(Math.log) + const center = mean(logs) + const variance = + logs.reduce((sum, value) => sum + (value - center) ** 2, 0) / + (logs.length - 1) + // Replicas, not the many correlated batches inside a worker, are the samples. + const margin = + critical95[logs.length - 2]! * Math.sqrt(variance / logs.length) + const percent = (value: number) => (Math.exp(value) - 1) * 100 + return { + changePercent: percent(center), + low95: percent(center - margin), + high95: percent(center + margin), + replicas: ratios.length, + } +} + +export function classify( + cpu: ReturnType, + wall: ReturnType, +) { + if (cpu.low95 > 0 && wall.low95 > 0) { + return 'slower' + } + if (cpu.high95 < 0 && wall.high95 < 0) { + return 'faster' + } + if ( + cpu.low95 >= -2 && + cpu.high95 <= 2 && + wall.low95 >= -2 && + wall.high95 <= 2 + ) { + return 'within-2%' + } + return 'inconclusive' +} diff --git a/benchmarks/client-nav/link-performance/tsconfig.json b/benchmarks/client-nav/link-performance/tsconfig.json new file mode 100644 index 0000000000..fbf230c977 --- /dev/null +++ b/benchmarks/client-nav/link-performance/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "./**/*.ts", + "./**/*.tsx", + "../scenarios/harness.ts", + "../setup-helpers.ts", + "../vitest.setup.ts" + ] +} diff --git a/benchmarks/client-nav/link-performance/vite.client.config.ts b/benchmarks/client-nav/link-performance/vite.client.config.ts new file mode 100644 index 0000000000..1cd45fc45e --- /dev/null +++ b/benchmarks/client-nav/link-performance/vite.client.config.ts @@ -0,0 +1,3 @@ +import { createLinkPerformanceConfig } from './config' + +export default createLinkPerformanceConfig('client') diff --git a/benchmarks/client-nav/link-performance/vite.ssr.config.ts b/benchmarks/client-nav/link-performance/vite.ssr.config.ts new file mode 100644 index 0000000000..f59148eaf6 --- /dev/null +++ b/benchmarks/client-nav/link-performance/vite.ssr.config.ts @@ -0,0 +1,3 @@ +import { createLinkPerformanceConfig } from './config' + +export default createLinkPerformanceConfig('ssr') diff --git a/benchmarks/client-nav/link-performance/vitest.config.ts b/benchmarks/client-nav/link-performance/vitest.config.ts new file mode 100644 index 0000000000..f8454c819d --- /dev/null +++ b/benchmarks/client-nav/link-performance/vitest.config.ts @@ -0,0 +1,11 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + root: fileURLToPath(new URL('.', import.meta.url)), + test: { + watch: false, + environment: 'node', + include: ['*.test.ts'], + }, +}) diff --git a/benchmarks/client-nav/link-performance/worker-protocol.ts b/benchmarks/client-nav/link-performance/worker-protocol.ts new file mode 100644 index 0000000000..474858a529 --- /dev/null +++ b/benchmarks/client-nav/link-performance/worker-protocol.ts @@ -0,0 +1,28 @@ +import type { LinkCaseId } from './cases' + +export type Mode = 'client' | 'ssr' +export type Variant = 0 | 1 + +export type WorkerRequest = + | { + kind: 'init' + mode: Mode + caseId: LinkCaseId + bundle: string + variant: Variant + } + | { kind: 'measure'; iterations: number; variant: Variant } + | { kind: 'stop' } + +export interface BlockSample { + wallMs: number + cpuMs: number + processCpuMs: number + iterations: number +} + +export type WorkerResponse = + | { kind: 'ready'; batchMs: number } + | { kind: 'sample'; sample: BlockSample } + | { kind: 'stopped' } + | { kind: 'error'; message: string } diff --git a/benchmarks/client-nav/package.json b/benchmarks/client-nav/package.json index 701e068b49..1f878adc67 100644 --- a/benchmarks/client-nav/package.json +++ b/benchmarks/client-nav/package.json @@ -9,16 +9,17 @@ "test:flame:react": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./react/speed.flame.ts", "test:flame:solid": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./solid/speed.flame.ts", "test:flame:vue": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./vue/speed.flame.ts", - "test:perf": "NODE_ENV=production vitest bench --config ./vitest.config.ts", - "test:perf:react": "NODE_ENV=production vitest bench --config ./vitest.react.config.ts", - "test:perf:solid": "NODE_ENV=production vitest bench --config ./vitest.solid.config.ts", - "test:perf:vue": "NODE_ENV=production vitest bench --config ./vitest.vue.config.ts", + "test:perf": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.config.ts", + "test:perf:react": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.react.config.ts", + "test:perf:solid": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.solid.config.ts", + "test:perf:vue": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.vue.config.ts", "test:types": "pnpm run test:types:react && pnpm run test:types:solid && pnpm run test:types:vue", "test:types:react": "tsc -p ./react/tsconfig.json --noEmit", "test:types:solid": "tsc -p ./solid/tsconfig.json --noEmit", "test:types:vue": "tsc -p ./vue/tsconfig.json --noEmit" }, "dependencies": { + "@tanstack/history": "workspace:^", "@tanstack/react-router": "workspace:^", "@tanstack/router-core": "workspace:^", "@tanstack/solid-router": "workspace:^", @@ -30,17 +31,21 @@ }, "devDependencies": { "@platformatic/flame": "^1.6.0", - "@codspeed/vitest-plugin": "^5.5.0", + "@codspeed/vitest-plugin": "^6.0.1", "@tanstack/router-plugin": "workspace:^", "@testing-library/react": "^16.2.0", "@vitejs/plugin-react": "^6.0.1", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "@types/jsdom": "28.0.0", - "typescript": "^6.0.2", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@typescript/native": "npm:typescript@^7.0.2", + "jsdom": "^29.1.1", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11", - "vitest": "^4.1.4" + "vitest": "catalog:" }, "nx": { "targets": { @@ -59,6 +64,8 @@ "@benchmarks/client-nav-control-flow-react", "@benchmarks/client-nav-head-react", "@benchmarks/client-nav-history-react", + "@benchmarks/client-nav-hydration-react", + "@benchmarks/client-nav-link-churn-react", "@benchmarks/client-nav-links-react", "@benchmarks/client-nav-loaders-react", "@benchmarks/client-nav-mount-react", @@ -87,6 +94,8 @@ "@benchmarks/client-nav-control-flow-solid", "@benchmarks/client-nav-head-solid", "@benchmarks/client-nav-history-solid", + "@benchmarks/client-nav-hydration-solid", + "@benchmarks/client-nav-link-churn-solid", "@benchmarks/client-nav-links-solid", "@benchmarks/client-nav-loaders-solid", "@benchmarks/client-nav-mount-solid", @@ -115,6 +124,7 @@ "@benchmarks/client-nav-control-flow-vue", "@benchmarks/client-nav-head-vue", "@benchmarks/client-nav-history-vue", + "@benchmarks/client-nav-link-churn-vue", "@benchmarks/client-nav-links-vue", "@benchmarks/client-nav-loaders-vue", "@benchmarks/client-nav-mount-vue", @@ -173,7 +183,13 @@ ] }, "test:types": { - "cache": false, + "inputs": [ + "default", + "^production", + "{workspaceRoot}/eslint.config.js", + "{workspaceRoot}/benchmarks/cpu-simulation.ts", + "dependentTaskOutputs" + ], "dependsOn": [ "^build", { @@ -190,8 +206,13 @@ "@benchmarks/client-nav-history-react", "@benchmarks/client-nav-history-solid", "@benchmarks/client-nav-history-vue", + "@benchmarks/client-nav-hydration-react", + "@benchmarks/client-nav-hydration-solid", + "@benchmarks/client-nav-link-churn-react", "@benchmarks/client-nav-links-react", + "@benchmarks/client-nav-link-churn-solid", "@benchmarks/client-nav-links-solid", + "@benchmarks/client-nav-link-churn-vue", "@benchmarks/client-nav-links-vue", "@benchmarks/client-nav-loaders-react", "@benchmarks/client-nav-loaders-solid", diff --git a/benchmarks/client-nav/react/speed.bench.ts b/benchmarks/client-nav/react/speed.bench.ts index fcc15b5fbc..944f182734 100644 --- a/benchmarks/client-nav/react/speed.bench.ts +++ b/benchmarks/client-nav/react/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' import { setup } from './setup' -describe('client-nav', () => { - const test = setup() +test('client-nav', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-side navigation loop (react)', + { beforeAll: scenario.before, afterAll: scenario.after }, async () => { for (let i = 0; i < 10; i++) { - await test.tick() + await scenario.tick() } }, - { - warmupIterations: 100, - time: 10_000, - setup: test.before, - teardown: test.after, - }, - ) + ).run({ + warmupIterations: 100, + time: 10_000, + }) }) diff --git a/benchmarks/client-nav/react/vite.config.ts b/benchmarks/client-nav/react/vite.config.ts index adc31ddd64..7df3f80e71 100644 --- a/benchmarks/client-nav/react/vite.config.ts +++ b/benchmarks/client-nav/react/vite.config.ts @@ -2,6 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import react from '@vitejs/plugin-react' import codspeedPlugin from '@codspeed/vitest-plugin' +import { cpuSimulationExecArgv } from '../../cpu-simulation' // Anchor the project root to the package directory so this config resolves // identically when run directly and as part of an aggregate `projects` config. @@ -28,9 +29,11 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav (react)', watch: false, environment: 'jsdom', setupFiles: [`${rootDir}vitest.setup.ts`], + benchmark: { include: ['react/speed.bench.ts'] }, }, }) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts b/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts index 68c5f97c2f..65dab0781e 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-async-pipeline', () => { - const test = setup() +test('client-async-pipeline', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-async-pipeline navigation loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/main.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/main.tsx index 4b141859e6..cab86a1272 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/src/main.tsx +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import { RouterProvider, createRouter } from '@tanstack/react-router' import { createRoot } from 'react-dom/client' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -22,8 +24,8 @@ declare module '@tanstack/react-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const reactRoot = createRoot(container) reactRoot.render() diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routeTree.gen.ts index 2b3336859a..9c79bab826 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routeTree.gen.ts @@ -9,25 +9,25 @@ // 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 NestedRouteImport } from './routes/nested' import { Route as IndexRouteImport } from './routes/index' -import { Route as SlowIdRouteImport } from './routes/slow.$id' -import { Route as NestedIdRouteImport } from './routes/nested.$id' +import { Route as NestedRouteImport } from './routes/nested' import { Route as CtxIdRouteImport } from './routes/ctx.$id' +import { Route as NestedIdRouteImport } from './routes/nested.$id' +import { Route as SlowIdRouteImport } from './routes/slow.$id' -const NestedRoute = NestedRouteImport.update({ - id: '/nested', - path: '/nested', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const SlowIdRoute = SlowIdRouteImport.update({ - id: '/slow/$id', - path: '/slow/$id', +const NestedRoute = NestedRouteImport.update({ + id: '/nested', + path: '/nested', + getParentRoute: () => rootRouteImport, +} as any) +const CtxIdRoute = CtxIdRouteImport.update({ + id: '/ctx/$id', + path: '/ctx/$id', getParentRoute: () => rootRouteImport, } as any) const NestedIdRoute = NestedIdRouteImport.update({ @@ -35,9 +35,9 @@ const NestedIdRoute = NestedIdRouteImport.update({ path: '/$id', getParentRoute: () => NestedRoute, } as any) -const CtxIdRoute = CtxIdRouteImport.update({ - id: '/ctx/$id', - path: '/ctx/$id', +const SlowIdRoute = SlowIdRouteImport.update({ + id: '/slow/$id', + path: '/slow/$id', getParentRoute: () => rootRouteImport, } as any) @@ -80,13 +80,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/nested': { - id: '/nested' - path: '/nested' - fullPath: '/nested' - preLoaderRoute: typeof NestedRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -94,11 +87,18 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/slow/$id': { - id: '/slow/$id' - path: '/slow/$id' - fullPath: '/slow/$id' - preLoaderRoute: typeof SlowIdRouteImport + '/nested': { + id: '/nested' + path: '/nested' + fullPath: '/nested' + preLoaderRoute: typeof NestedRouteImport + parentRoute: typeof rootRouteImport + } + '/ctx/$id': { + id: '/ctx/$id' + path: '/ctx/$id' + fullPath: '/ctx/$id' + preLoaderRoute: typeof CtxIdRouteImport parentRoute: typeof rootRouteImport } '/nested/$id': { @@ -108,11 +108,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof NestedIdRouteImport parentRoute: typeof NestedRoute } - '/ctx/$id': { - id: '/ctx/$id' - path: '/ctx/$id' - fullPath: '/ctx/$id' - preLoaderRoute: typeof CtxIdRouteImport + '/slow/$id': { + id: '/slow/$id' + path: '/slow/$id' + fullPath: '/slow/$id' + preLoaderRoute: typeof SlowIdRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/vite.config.ts b/benchmarks/client-nav/scenarios/async-pipeline/react/vite.config.ts index 7161c9a13d..e36a5244b1 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import react from '@vitejs/plugin-react' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -32,6 +33,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav async-pipeline (react)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts index d1f620f447..acef710469 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-async-pipeline', () => { - const test = setup() +test('client-async-pipeline', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-async-pipeline navigation loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/main.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/main.tsx index 92dcc74d0a..4c6d49f501 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/main.tsx +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import { render } from 'solid-js/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -22,8 +24,8 @@ declare module '@tanstack/solid-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const unmount = render(() => , container) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routeTree.gen.ts index 7c15baf4e9..27b9498b11 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routeTree.gen.ts @@ -9,25 +9,25 @@ // 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 NestedRouteImport } from './routes/nested' import { Route as IndexRouteImport } from './routes/index' -import { Route as SlowIdRouteImport } from './routes/slow.$id' -import { Route as NestedIdRouteImport } from './routes/nested.$id' +import { Route as NestedRouteImport } from './routes/nested' import { Route as CtxIdRouteImport } from './routes/ctx.$id' +import { Route as NestedIdRouteImport } from './routes/nested.$id' +import { Route as SlowIdRouteImport } from './routes/slow.$id' -const NestedRoute = NestedRouteImport.update({ - id: '/nested', - path: '/nested', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const SlowIdRoute = SlowIdRouteImport.update({ - id: '/slow/$id', - path: '/slow/$id', +const NestedRoute = NestedRouteImport.update({ + id: '/nested', + path: '/nested', + getParentRoute: () => rootRouteImport, +} as any) +const CtxIdRoute = CtxIdRouteImport.update({ + id: '/ctx/$id', + path: '/ctx/$id', getParentRoute: () => rootRouteImport, } as any) const NestedIdRoute = NestedIdRouteImport.update({ @@ -35,9 +35,9 @@ const NestedIdRoute = NestedIdRouteImport.update({ path: '/$id', getParentRoute: () => NestedRoute, } as any) -const CtxIdRoute = CtxIdRouteImport.update({ - id: '/ctx/$id', - path: '/ctx/$id', +const SlowIdRoute = SlowIdRouteImport.update({ + id: '/slow/$id', + path: '/slow/$id', getParentRoute: () => rootRouteImport, } as any) @@ -80,13 +80,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/nested': { - id: '/nested' - path: '/nested' - fullPath: '/nested' - preLoaderRoute: typeof NestedRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -94,11 +87,18 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/slow/$id': { - id: '/slow/$id' - path: '/slow/$id' - fullPath: '/slow/$id' - preLoaderRoute: typeof SlowIdRouteImport + '/nested': { + id: '/nested' + path: '/nested' + fullPath: '/nested' + preLoaderRoute: typeof NestedRouteImport + parentRoute: typeof rootRouteImport + } + '/ctx/$id': { + id: '/ctx/$id' + path: '/ctx/$id' + fullPath: '/ctx/$id' + preLoaderRoute: typeof CtxIdRouteImport parentRoute: typeof rootRouteImport } '/nested/$id': { @@ -108,11 +108,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof NestedIdRouteImport parentRoute: typeof NestedRoute } - '/ctx/$id': { - id: '/ctx/$id' - path: '/ctx/$id' - fullPath: '/ctx/$id' - preLoaderRoute: typeof CtxIdRouteImport + '/slow/$id': { + id: '/slow/$id' + path: '/slow/$id' + fullPath: '/slow/$id' + preLoaderRoute: typeof SlowIdRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/vite.config.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/vite.config.ts index 5107c1f056..214da8042e 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import solid from 'vite-plugin-solid' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -35,6 +36,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav async-pipeline (solid)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts index eeb568323c..f0fd3e58df 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-async-pipeline', () => { - const test = setup() +test('client-async-pipeline', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-async-pipeline navigation loop (vue)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/main.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/main.tsx index d8e659fb09..e1bfa5965f 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/main.tsx +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import * as Vue from 'vue' import { RouterProvider, createRouter } from '@tanstack/vue-router' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -22,8 +24,8 @@ declare module '@tanstack/vue-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const component = const app = Vue.createApp({ diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routeTree.gen.ts index ce26dc62d1..66b9efd7aa 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routeTree.gen.ts @@ -9,25 +9,25 @@ // 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 NestedRouteImport } from './routes/nested' import { Route as IndexRouteImport } from './routes/index' -import { Route as SlowIdRouteImport } from './routes/slow.$id' -import { Route as NestedIdRouteImport } from './routes/nested.$id' +import { Route as NestedRouteImport } from './routes/nested' import { Route as CtxIdRouteImport } from './routes/ctx.$id' +import { Route as NestedIdRouteImport } from './routes/nested.$id' +import { Route as SlowIdRouteImport } from './routes/slow.$id' -const NestedRoute = NestedRouteImport.update({ - id: '/nested', - path: '/nested', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const SlowIdRoute = SlowIdRouteImport.update({ - id: '/slow/$id', - path: '/slow/$id', +const NestedRoute = NestedRouteImport.update({ + id: '/nested', + path: '/nested', + getParentRoute: () => rootRouteImport, +} as any) +const CtxIdRoute = CtxIdRouteImport.update({ + id: '/ctx/$id', + path: '/ctx/$id', getParentRoute: () => rootRouteImport, } as any) const NestedIdRoute = NestedIdRouteImport.update({ @@ -35,9 +35,9 @@ const NestedIdRoute = NestedIdRouteImport.update({ path: '/$id', getParentRoute: () => NestedRoute, } as any) -const CtxIdRoute = CtxIdRouteImport.update({ - id: '/ctx/$id', - path: '/ctx/$id', +const SlowIdRoute = SlowIdRouteImport.update({ + id: '/slow/$id', + path: '/slow/$id', getParentRoute: () => rootRouteImport, } as any) @@ -80,13 +80,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/nested': { - id: '/nested' - path: '/nested' - fullPath: '/nested' - preLoaderRoute: typeof NestedRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -94,11 +87,18 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/slow/$id': { - id: '/slow/$id' - path: '/slow/$id' - fullPath: '/slow/$id' - preLoaderRoute: typeof SlowIdRouteImport + '/nested': { + id: '/nested' + path: '/nested' + fullPath: '/nested' + preLoaderRoute: typeof NestedRouteImport + parentRoute: typeof rootRouteImport + } + '/ctx/$id': { + id: '/ctx/$id' + path: '/ctx/$id' + fullPath: '/ctx/$id' + preLoaderRoute: typeof CtxIdRouteImport parentRoute: typeof rootRouteImport } '/nested/$id': { @@ -108,11 +108,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof NestedIdRouteImport parentRoute: typeof NestedRoute } - '/ctx/$id': { - id: '/ctx/$id' - path: '/ctx/$id' - fullPath: '/ctx/$id' - preLoaderRoute: typeof CtxIdRouteImport + '/slow/$id': { + id: '/slow/$id' + path: '/slow/$id' + fullPath: '/slow/$id' + preLoaderRoute: typeof SlowIdRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/vite.config.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/vite.config.ts index e16a8ee828..ce4fa7318a 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/vite.config.ts @@ -4,6 +4,7 @@ import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -34,6 +35,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav async-pipeline (vue)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts b/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts index 55a2224d3a..d6f2190be7 100644 --- a/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-control-flow', () => { - const test = setup() +test('client-control-flow', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-control-flow navigation loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/main.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/main.tsx index 9a0c3d3b50..da9e63d293 100644 --- a/benchmarks/client-nav/scenarios/control-flow/react/src/main.tsx +++ b/benchmarks/client-nav/scenarios/control-flow/react/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import { RouterProvider, createRouter } from '@tanstack/react-router' import { createRoot } from 'react-dom/client' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -20,8 +22,8 @@ declare module '@tanstack/react-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) // The scenario intentionally throws loader errors every lap; keep React 19's // default per-caught-error console reporting out of the measured loop. diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/control-flow/react/src/routeTree.gen.ts index 86edcc8472..7b6db9b237 100644 --- a/benchmarks/client-nav/scenarios/control-flow/react/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/control-flow/react/src/routeTree.gen.ts @@ -9,26 +9,16 @@ // 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 TargetRouteImport } from './routes/target' -import { Route as Hop2RouteImport } from './routes/hop2' -import { Route as Hop1RouteImport } from './routes/hop1' -import { Route as BrokenRouteImport } from './routes/broken' import { Route as IndexRouteImport } from './routes/index' +import { Route as BrokenRouteImport } from './routes/broken' +import { Route as Hop1RouteImport } from './routes/hop1' +import { Route as Hop2RouteImport } from './routes/hop2' +import { Route as TargetRouteImport } from './routes/target' import { Route as MissingIdRouteImport } from './routes/missing.$id' -const TargetRoute = TargetRouteImport.update({ - id: '/target', - path: '/target', - getParentRoute: () => rootRouteImport, -} as any) -const Hop2Route = Hop2RouteImport.update({ - id: '/hop2', - path: '/hop2', - getParentRoute: () => rootRouteImport, -} as any) -const Hop1Route = Hop1RouteImport.update({ - id: '/hop1', - path: '/hop1', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const BrokenRoute = BrokenRouteImport.update({ @@ -36,9 +26,19 @@ const BrokenRoute = BrokenRouteImport.update({ path: '/broken', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const Hop1Route = Hop1RouteImport.update({ + id: '/hop1', + path: '/hop1', + getParentRoute: () => rootRouteImport, +} as any) +const Hop2Route = Hop2RouteImport.update({ + id: '/hop2', + path: '/hop2', + getParentRoute: () => rootRouteImport, +} as any) +const TargetRoute = TargetRouteImport.update({ + id: '/target', + path: '/target', getParentRoute: () => rootRouteImport, } as any) const MissingIdRoute = MissingIdRouteImport.update({ @@ -98,25 +98,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/target': { - id: '/target' - path: '/target' - fullPath: '/target' - preLoaderRoute: typeof TargetRouteImport - parentRoute: typeof rootRouteImport - } - '/hop2': { - id: '/hop2' - path: '/hop2' - fullPath: '/hop2' - preLoaderRoute: typeof Hop2RouteImport - parentRoute: typeof rootRouteImport - } - '/hop1': { - id: '/hop1' - path: '/hop1' - fullPath: '/hop1' - preLoaderRoute: typeof Hop1RouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/broken': { @@ -126,11 +112,25 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof BrokenRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/hop1': { + id: '/hop1' + path: '/hop1' + fullPath: '/hop1' + preLoaderRoute: typeof Hop1RouteImport + parentRoute: typeof rootRouteImport + } + '/hop2': { + id: '/hop2' + path: '/hop2' + fullPath: '/hop2' + preLoaderRoute: typeof Hop2RouteImport + parentRoute: typeof rootRouteImport + } + '/target': { + id: '/target' + path: '/target' + fullPath: '/target' + preLoaderRoute: typeof TargetRouteImport parentRoute: typeof rootRouteImport } '/missing/$id': { diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/broken.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/broken.tsx index 2dc4a26486..b11bb845bc 100644 --- a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/broken.tsx +++ b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/broken.tsx @@ -12,5 +12,9 @@ export const Route = createFileRoute('/broken')({ }) function BrokenError(props: ErrorComponentProps) { - return
{props.error.message}
+ return ( +
+ {props.error instanceof Error ? props.error.message : String(props.error)} +
+ ) } diff --git a/benchmarks/client-nav/scenarios/control-flow/react/vite.config.ts b/benchmarks/client-nav/scenarios/control-flow/react/vite.config.ts index 1aa2c1fa35..1eefca0fc3 100644 --- a/benchmarks/client-nav/scenarios/control-flow/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/control-flow/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import react from '@vitejs/plugin-react' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -32,6 +33,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav control-flow (react)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts index abbb85a575..d803d2a313 100644 --- a/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-control-flow', () => { - const test = setup() +test('client-control-flow', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-control-flow navigation loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/main.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/main.tsx index 817045bd02..fa9d239418 100644 --- a/benchmarks/client-nav/scenarios/control-flow/solid/src/main.tsx +++ b/benchmarks/client-nav/scenarios/control-flow/solid/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import { render } from 'solid-js/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -20,8 +22,8 @@ declare module '@tanstack/solid-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const unmount = render(() => , container) diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts index 44d88e9f8d..cd84f99d5d 100644 --- a/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts @@ -9,26 +9,16 @@ // 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 TargetRouteImport } from './routes/target' -import { Route as Hop2RouteImport } from './routes/hop2' -import { Route as Hop1RouteImport } from './routes/hop1' -import { Route as BrokenRouteImport } from './routes/broken' import { Route as IndexRouteImport } from './routes/index' +import { Route as BrokenRouteImport } from './routes/broken' +import { Route as Hop1RouteImport } from './routes/hop1' +import { Route as Hop2RouteImport } from './routes/hop2' +import { Route as TargetRouteImport } from './routes/target' import { Route as MissingIdRouteImport } from './routes/missing.$id' -const TargetRoute = TargetRouteImport.update({ - id: '/target', - path: '/target', - getParentRoute: () => rootRouteImport, -} as any) -const Hop2Route = Hop2RouteImport.update({ - id: '/hop2', - path: '/hop2', - getParentRoute: () => rootRouteImport, -} as any) -const Hop1Route = Hop1RouteImport.update({ - id: '/hop1', - path: '/hop1', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const BrokenRoute = BrokenRouteImport.update({ @@ -36,9 +26,19 @@ const BrokenRoute = BrokenRouteImport.update({ path: '/broken', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const Hop1Route = Hop1RouteImport.update({ + id: '/hop1', + path: '/hop1', + getParentRoute: () => rootRouteImport, +} as any) +const Hop2Route = Hop2RouteImport.update({ + id: '/hop2', + path: '/hop2', + getParentRoute: () => rootRouteImport, +} as any) +const TargetRoute = TargetRouteImport.update({ + id: '/target', + path: '/target', getParentRoute: () => rootRouteImport, } as any) const MissingIdRoute = MissingIdRouteImport.update({ @@ -98,25 +98,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/target': { - id: '/target' - path: '/target' - fullPath: '/target' - preLoaderRoute: typeof TargetRouteImport - parentRoute: typeof rootRouteImport - } - '/hop2': { - id: '/hop2' - path: '/hop2' - fullPath: '/hop2' - preLoaderRoute: typeof Hop2RouteImport - parentRoute: typeof rootRouteImport - } - '/hop1': { - id: '/hop1' - path: '/hop1' - fullPath: '/hop1' - preLoaderRoute: typeof Hop1RouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/broken': { @@ -126,11 +112,25 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof BrokenRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/hop1': { + id: '/hop1' + path: '/hop1' + fullPath: '/hop1' + preLoaderRoute: typeof Hop1RouteImport + parentRoute: typeof rootRouteImport + } + '/hop2': { + id: '/hop2' + path: '/hop2' + fullPath: '/hop2' + preLoaderRoute: typeof Hop2RouteImport + parentRoute: typeof rootRouteImport + } + '/target': { + id: '/target' + path: '/target' + fullPath: '/target' + preLoaderRoute: typeof TargetRouteImport parentRoute: typeof rootRouteImport } '/missing/$id': { diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/vite.config.ts b/benchmarks/client-nav/scenarios/control-flow/solid/vite.config.ts index 1c6244d3d1..f4fa916154 100644 --- a/benchmarks/client-nav/scenarios/control-flow/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/control-flow/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import solid from 'vite-plugin-solid' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -35,6 +36,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav control-flow (solid)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts index 551b88e68f..8a019945c7 100644 --- a/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-control-flow', () => { - const test = setup() +test('client-control-flow', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-control-flow navigation loop (vue)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/main.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/main.tsx index c96d3f3a2e..cae9b54f1d 100644 --- a/benchmarks/client-nav/scenarios/control-flow/vue/src/main.tsx +++ b/benchmarks/client-nav/scenarios/control-flow/vue/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import * as Vue from 'vue' import { RouterProvider, createRouter } from '@tanstack/vue-router' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -20,8 +22,8 @@ declare module '@tanstack/vue-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const component = const app = Vue.createApp({ diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts index 60fc846f89..6b53a6a203 100644 --- a/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts @@ -9,26 +9,16 @@ // 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 TargetRouteImport } from './routes/target' -import { Route as Hop2RouteImport } from './routes/hop2' -import { Route as Hop1RouteImport } from './routes/hop1' -import { Route as BrokenRouteImport } from './routes/broken' import { Route as IndexRouteImport } from './routes/index' +import { Route as BrokenRouteImport } from './routes/broken' +import { Route as Hop1RouteImport } from './routes/hop1' +import { Route as Hop2RouteImport } from './routes/hop2' +import { Route as TargetRouteImport } from './routes/target' import { Route as MissingIdRouteImport } from './routes/missing.$id' -const TargetRoute = TargetRouteImport.update({ - id: '/target', - path: '/target', - getParentRoute: () => rootRouteImport, -} as any) -const Hop2Route = Hop2RouteImport.update({ - id: '/hop2', - path: '/hop2', - getParentRoute: () => rootRouteImport, -} as any) -const Hop1Route = Hop1RouteImport.update({ - id: '/hop1', - path: '/hop1', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const BrokenRoute = BrokenRouteImport.update({ @@ -36,9 +26,19 @@ const BrokenRoute = BrokenRouteImport.update({ path: '/broken', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const Hop1Route = Hop1RouteImport.update({ + id: '/hop1', + path: '/hop1', + getParentRoute: () => rootRouteImport, +} as any) +const Hop2Route = Hop2RouteImport.update({ + id: '/hop2', + path: '/hop2', + getParentRoute: () => rootRouteImport, +} as any) +const TargetRoute = TargetRouteImport.update({ + id: '/target', + path: '/target', getParentRoute: () => rootRouteImport, } as any) const MissingIdRoute = MissingIdRouteImport.update({ @@ -98,25 +98,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/target': { - id: '/target' - path: '/target' - fullPath: '/target' - preLoaderRoute: typeof TargetRouteImport - parentRoute: typeof rootRouteImport - } - '/hop2': { - id: '/hop2' - path: '/hop2' - fullPath: '/hop2' - preLoaderRoute: typeof Hop2RouteImport - parentRoute: typeof rootRouteImport - } - '/hop1': { - id: '/hop1' - path: '/hop1' - fullPath: '/hop1' - preLoaderRoute: typeof Hop1RouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/broken': { @@ -126,11 +112,25 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof BrokenRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/hop1': { + id: '/hop1' + path: '/hop1' + fullPath: '/hop1' + preLoaderRoute: typeof Hop1RouteImport + parentRoute: typeof rootRouteImport + } + '/hop2': { + id: '/hop2' + path: '/hop2' + fullPath: '/hop2' + preLoaderRoute: typeof Hop2RouteImport + parentRoute: typeof rootRouteImport + } + '/target': { + id: '/target' + path: '/target' + fullPath: '/target' + preLoaderRoute: typeof TargetRouteImport parentRoute: typeof rootRouteImport } '/missing/$id': { diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/vite.config.ts b/benchmarks/client-nav/scenarios/control-flow/vue/vite.config.ts index 4694cf69c8..3c2750d2a6 100644 --- a/benchmarks/client-nav/scenarios/control-flow/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/control-flow/vue/vite.config.ts @@ -4,6 +4,7 @@ import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -34,6 +35,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav control-flow (vue)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/harness.ts b/benchmarks/client-nav/scenarios/harness.ts index 7b993d0ed8..cf3c39c7e6 100644 --- a/benchmarks/client-nav/scenarios/harness.ts +++ b/benchmarks/client-nav/scenarios/harness.ts @@ -1,3 +1,9 @@ +import { + createBrowserHistory, + createMemoryHistory, + type RouterHistory, +} from '@tanstack/history' +import { JSDOM } from 'jsdom' import { getRequiredLink, waitForRequiredLink } from '../setup-helpers' export interface ScenarioRouter { @@ -76,6 +82,16 @@ async function settle(hops: number) { } const MAX_SETTLE_HOPS = 100 +const BATCH_SETTLE_HOPS = 4 + +/** + * Close the batch at a deterministic macrotask boundary. Four fixed hops give + * framework passive effects and scheduler callbacks time to run without + * changing the amount of navigation work in the batch. + */ +async function finishBatch() { + await settle(BATCH_SETTLE_HOPS) +} async function settleUntil(isSettled: () => boolean, label: string) { for (let i = 0; i < MAX_SETTLE_HOPS; i++) { @@ -101,14 +117,19 @@ async function settleUntil(isSettled: () => boolean, label: string) { * conventions already forbid real-delay timers in measured code; non-zero * delays are passed through untouched. */ -function patchZeroDelayTimeouts() { - const originalSetTimeout = window.setTimeout.bind(window) - const originalClearTimeout = window.clearTimeout.bind(window) +interface TimerWindow { + setTimeout: typeof window.setTimeout + clearTimeout: typeof window.clearTimeout +} + +function patchZeroDelayTimeouts(targetWindow: TimerWindow) { + const originalSetTimeout = targetWindow.setTimeout.bind(targetWindow) + const originalClearTimeout = targetWindow.clearTimeout.bind(targetWindow) const immediates = new Map() // Negative ids cannot collide with real jsdom timer ids. let nextImmediateId = -2 - window.setTimeout = (( + targetWindow.setTimeout = (( handler: (...handlerArgs: Array) => void, delay?: number, ...args: Array @@ -125,9 +146,9 @@ function patchZeroDelayTimeouts() { return id } return originalSetTimeout(handler, delay, ...args) - }) as typeof window.setTimeout + }) as typeof targetWindow.setTimeout - window.clearTimeout = ((id: number) => { + targetWindow.clearTimeout = ((id: number) => { const immediate = immediates.get(id) if (immediate) { clearImmediate(immediate) @@ -135,17 +156,119 @@ function patchZeroDelayTimeouts() { return } originalClearTimeout(id) - }) as typeof window.clearTimeout + }) as typeof targetWindow.clearTimeout return () => { - window.setTimeout = originalSetTimeout as typeof window.setTimeout - window.clearTimeout = originalClearTimeout as typeof window.clearTimeout + targetWindow.setTimeout = + originalSetTimeout as typeof targetWindow.setTimeout + targetWindow.clearTimeout = + originalClearTimeout as typeof targetWindow.clearTimeout + } +} + +interface ListenerTarget { + addEventListener: ( + type: string, + listener: EventListenerOrEventListenerObject | null, + options?: boolean | AddEventListenerOptions, + ) => void + removeEventListener: ( + type: string, + listener: EventListenerOrEventListenerObject | null, + options?: boolean | EventListenerOptions, + ) => void +} + +/** + * Scroll restoration installs page-lifetime listeners without a public router + * dispose operation. Capture just those listeners while the router is created + * so per-invocation routers do not remain reachable after teardown. + */ +function captureScrollRestorationListeners() { + const captured: Array<{ + target: ListenerTarget + type: string + listener: EventListenerOrEventListenerObject | null + options?: boolean | AddEventListenerOptions + }> = [] + const patches: Array<{ + target: ListenerTarget + addEventListener: ListenerTarget['addEventListener'] + }> = [] + + const patch = (target: ListenerTarget, capturedType: string) => { + const originalAddEventListener = target.addEventListener + patches.push({ target, addEventListener: originalAddEventListener }) + + target.addEventListener = function (type, listener, options) { + if (type === capturedType) { + captured.push({ target, type, listener, options }) + } + originalAddEventListener.call(target, type, listener, options) + } + } + + patch(document as unknown as ListenerTarget, 'scroll') + patch(globalThis as unknown as ListenerTarget, 'pagehide') + + let stopped = false + const stop = () => { + if (stopped) { + return + } + stopped = true + for (const entry of patches) { + entry.target.addEventListener = entry.addEventListener + } + } + + return { + stop, + cleanup() { + stop() + for (const { target, type, listener, options } of captured) { + target.removeEventListener(type, listener, options) + } + }, + } +} + +interface ScenarioHistoryResource { + history: RouterHistory + timeoutWindow?: TimerWindow + dispose: () => void +} + +function createScenarioHistory( + mode: NonNullable, + initialUrl: string, +): ScenarioHistoryResource { + if (mode === 'browser') { + const dom = new JSDOM('', { + url: new URL(initialUrl, 'http://localhost').href, + }) + const history = createBrowserHistory({ window: dom.window }) + + return { + history, + timeoutWindow: dom.window as unknown as TimerWindow, + dispose() { + history.destroy() + dom.window.close() + }, + } + } + + const history = createMemoryHistory({ initialEntries: [initialUrl] }) + return { + history, + dispose: history.destroy, } } export interface ScenarioSetupOptions { frameworkLabel: string - mount: (container: HTMLElement) => MountedScenarioApp + mount: (container: HTMLElement, history: RouterHistory) => MountedScenarioApp /** * Circular sequence of steps advanced by `tick()`. Link steps must target * links rendered from the start (e.g. in the root layout), no two @@ -156,13 +279,22 @@ export interface ScenarioSetupOptions { */ steps: ReadonlyArray /** Sanity check run once per step during the warm-up lap in `before()`. */ - assertAfterStep?: (stepIndex: number, container: HTMLElement) => void + assertAfterStep?: ( + stepIndex: number, + container: HTMLElement, + history: RouterHistory, + ) => void /** - * URL the window is reset to before mounting (default '/'). Scenarios whose - * router uses a `basepath` or an input rewrite must start on an external - * URL that maps to their initial route. + * URL used to initialize the fresh history before mounting (default '/'). + * Scenarios whose router uses a `basepath` or an input rewrite must start on + * an external URL that maps to their initial route. */ initialUrl?: string + /** + * Browser history is reserved for the scenario that explicitly measures + * browser history traversal. All other scenarios use fresh memory history. + */ + historyMode?: 'memory' | 'browser' } function warnAboutDevMode(frameworkLabel: string) { @@ -185,18 +317,41 @@ export function createScenarioSetup(options: ScenarioSetupOptions) { let unmount: (() => void) | undefined = undefined let unsub = () => {} let restoreTimeouts = () => {} + let cleanupScrollRestorationListeners = () => {} + let historyResource: ScenarioHistoryResource | undefined = undefined let stepIndex = 0 let next: () => Promise = () => Promise.reject(new Error('Benchmark not initialized')) async function before() { stepIndex = 0 - restoreTimeouts = patchZeroDelayTimeouts() - window.history.replaceState(null, '', options.initialUrl ?? '/') + historyResource = createScenarioHistory( + options.historyMode ?? 'memory', + options.initialUrl ?? '/', + ) + + const restoreGlobalTimeouts = patchZeroDelayTimeouts(window) + const restoreHistoryTimeouts = historyResource.timeoutWindow + ? patchZeroDelayTimeouts(historyResource.timeoutWindow) + : () => {} + restoreTimeouts = () => { + restoreHistoryTimeouts() + restoreGlobalTimeouts() + } + container = document.createElement('div') document.body.append(container) - const { router, unmount: dispose } = options.mount(container) + const capturedListeners = captureScrollRestorationListeners() + let mounted: MountedScenarioApp + try { + mounted = options.mount(container, historyResource.history) + } finally { + capturedListeners.stop() + cleanupScrollRestorationListeners = capturedListeners.cleanup + } + + const { router, unmount: dispose } = mounted unmount = dispose let resolveRendered: () => void = () => {} @@ -294,8 +449,9 @@ export function createScenarioSetup(options: ScenarioSetupOptions) { // ending back on the initial route so measurement starts from a known state. for (const [index, step] of options.steps.entries()) { await runStep(step) - options.assertAfterStep?.(index, container) + options.assertAfterStep?.(index, container, historyResource.history) } + await finishBatch() next = () => { const step = options.steps[stepIndex % options.steps.length]! @@ -308,10 +464,14 @@ export function createScenarioSetup(options: ScenarioSetupOptions) { unmount?.() container?.remove() unsub() + cleanupScrollRestorationListeners() restoreTimeouts() + historyResource?.dispose() restoreTimeouts = () => {} + cleanupScrollRestorationListeners = () => {} unmount = undefined container = undefined + historyResource = undefined } function tick() { @@ -321,13 +481,14 @@ export function createScenarioSetup(options: ScenarioSetupOptions) { return { before, tick, + finishBatch, after, } } export interface MountLoopSetupOptions { frameworkLabel: string - mount: (container: HTMLElement) => MountedScenarioApp + mount: (container: HTMLElement, history: RouterHistory) => MountedScenarioApp /** Test id that must appear in the container before a mount counts as done. */ readyTestId: string assertReady?: (container: HTMLElement) => void @@ -342,11 +503,11 @@ export function createMountLoopSetup(options: MountLoopSetupOptions) { warnAboutDevMode(options.frameworkLabel) async function tick() { - window.history.replaceState(null, '', '/') const container = document.createElement('div') document.body.append(container) + const history = createMemoryHistory({ initialEntries: ['/'] }) - const { router, unmount } = options.mount(container) + const { router, unmount } = options.mount(container, history) try { await router.load() @@ -359,6 +520,7 @@ export function createMountLoopSetup(options: MountLoopSetupOptions) { options.assertReady?.(container) } finally { unmount() + history.destroy() container.remove() } } @@ -366,6 +528,7 @@ export function createMountLoopSetup(options: MountLoopSetupOptions) { return { before: async () => {}, tick, + finishBatch, after: () => {}, } } diff --git a/benchmarks/client-nav/scenarios/head/react/speed.bench.ts b/benchmarks/client-nav/scenarios/head/react/speed.bench.ts index c71b426c56..d0d731a09f 100644 --- a/benchmarks/client-nav/scenarios/head/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/head/react/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-head', () => { - const test = setup() +test('client-head', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-head navigation loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/head/react/src/main.tsx b/benchmarks/client-nav/scenarios/head/react/src/main.tsx index ef0b99555c..5febd6f795 100644 --- a/benchmarks/client-nav/scenarios/head/react/src/main.tsx +++ b/benchmarks/client-nav/scenarios/head/react/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import { RouterProvider, createRouter } from '@tanstack/react-router' import { createRoot } from 'react-dom/client' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -20,8 +22,8 @@ declare module '@tanstack/react-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const reactRoot = createRoot(container) reactRoot.render() diff --git a/benchmarks/client-nav/scenarios/head/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/head/react/src/routeTree.gen.ts index 5c80a3104e..88867d9190 100644 --- a/benchmarks/client-nav/scenarios/head/react/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/head/react/src/routeTree.gen.ts @@ -9,15 +9,15 @@ // 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 SettingsRouteImport } from './routes/settings' -import { Route as DocsRouteImport } from './routes/docs' import { Route as IndexRouteImport } from './routes/index' -import { Route as DocsSectionRouteImport } from './routes/docs.$section' +import { Route as DocsRouteImport } from './routes/docs' +import { Route as SettingsRouteImport } from './routes/settings' import { Route as ArticlesIdRouteImport } from './routes/articles.$id' +import { Route as DocsSectionRouteImport } from './routes/docs.$section' -const SettingsRoute = SettingsRouteImport.update({ - id: '/settings', - path: '/settings', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const DocsRoute = DocsRouteImport.update({ @@ -25,9 +25,14 @@ const DocsRoute = DocsRouteImport.update({ path: '/docs', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SettingsRoute = SettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => rootRouteImport, +} as any) +const ArticlesIdRoute = ArticlesIdRouteImport.update({ + id: '/articles/$id', + path: '/articles/$id', getParentRoute: () => rootRouteImport, } as any) const DocsSectionRoute = DocsSectionRouteImport.update({ @@ -35,11 +40,6 @@ const DocsSectionRoute = DocsSectionRouteImport.update({ path: '/$section', getParentRoute: () => DocsRoute, } as any) -const ArticlesIdRoute = ArticlesIdRouteImport.update({ - id: '/articles/$id', - path: '/articles/$id', - getParentRoute: () => rootRouteImport, -} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -86,11 +86,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/settings': { - id: '/settings' - path: '/settings' - fullPath: '/settings' - preLoaderRoute: typeof SettingsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/docs': { @@ -100,11 +100,18 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DocsRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/settings': { + id: '/settings' + path: '/settings' + fullPath: '/settings' + preLoaderRoute: typeof SettingsRouteImport + parentRoute: typeof rootRouteImport + } + '/articles/$id': { + id: '/articles/$id' + path: '/articles/$id' + fullPath: '/articles/$id' + preLoaderRoute: typeof ArticlesIdRouteImport parentRoute: typeof rootRouteImport } '/docs/$section': { @@ -114,13 +121,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DocsSectionRouteImport parentRoute: typeof DocsRoute } - '/articles/$id': { - id: '/articles/$id' - path: '/articles/$id' - fullPath: '/articles/$id' - preLoaderRoute: typeof ArticlesIdRouteImport - parentRoute: typeof rootRouteImport - } } } diff --git a/benchmarks/client-nav/scenarios/head/react/vite.config.ts b/benchmarks/client-nav/scenarios/head/react/vite.config.ts index 086bd60bb4..7c8d6d4c15 100644 --- a/benchmarks/client-nav/scenarios/head/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/head/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import react from '@vitejs/plugin-react' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -32,6 +33,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav head (react)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts index ea0a5ca818..ca156c950b 100644 --- a/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-head', () => { - const test = setup() +test('client-head', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-head navigation loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/head/solid/src/main.tsx b/benchmarks/client-nav/scenarios/head/solid/src/main.tsx index 817045bd02..fa9d239418 100644 --- a/benchmarks/client-nav/scenarios/head/solid/src/main.tsx +++ b/benchmarks/client-nav/scenarios/head/solid/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import { render } from 'solid-js/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -20,8 +22,8 @@ declare module '@tanstack/solid-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const unmount = render(() => , container) diff --git a/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts index ead6a4436a..b6f217e527 100644 --- a/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts @@ -9,15 +9,15 @@ // 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 SettingsRouteImport } from './routes/settings' -import { Route as DocsRouteImport } from './routes/docs' import { Route as IndexRouteImport } from './routes/index' -import { Route as DocsSectionRouteImport } from './routes/docs.$section' +import { Route as DocsRouteImport } from './routes/docs' +import { Route as SettingsRouteImport } from './routes/settings' import { Route as ArticlesIdRouteImport } from './routes/articles.$id' +import { Route as DocsSectionRouteImport } from './routes/docs.$section' -const SettingsRoute = SettingsRouteImport.update({ - id: '/settings', - path: '/settings', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const DocsRoute = DocsRouteImport.update({ @@ -25,9 +25,14 @@ const DocsRoute = DocsRouteImport.update({ path: '/docs', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SettingsRoute = SettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => rootRouteImport, +} as any) +const ArticlesIdRoute = ArticlesIdRouteImport.update({ + id: '/articles/$id', + path: '/articles/$id', getParentRoute: () => rootRouteImport, } as any) const DocsSectionRoute = DocsSectionRouteImport.update({ @@ -35,11 +40,6 @@ const DocsSectionRoute = DocsSectionRouteImport.update({ path: '/$section', getParentRoute: () => DocsRoute, } as any) -const ArticlesIdRoute = ArticlesIdRouteImport.update({ - id: '/articles/$id', - path: '/articles/$id', - getParentRoute: () => rootRouteImport, -} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -86,11 +86,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/settings': { - id: '/settings' - path: '/settings' - fullPath: '/settings' - preLoaderRoute: typeof SettingsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/docs': { @@ -100,11 +100,18 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DocsRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/settings': { + id: '/settings' + path: '/settings' + fullPath: '/settings' + preLoaderRoute: typeof SettingsRouteImport + parentRoute: typeof rootRouteImport + } + '/articles/$id': { + id: '/articles/$id' + path: '/articles/$id' + fullPath: '/articles/$id' + preLoaderRoute: typeof ArticlesIdRouteImport parentRoute: typeof rootRouteImport } '/docs/$section': { @@ -114,13 +121,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DocsSectionRouteImport parentRoute: typeof DocsRoute } - '/articles/$id': { - id: '/articles/$id' - path: '/articles/$id' - fullPath: '/articles/$id' - preLoaderRoute: typeof ArticlesIdRouteImport - parentRoute: typeof rootRouteImport - } } } diff --git a/benchmarks/client-nav/scenarios/head/solid/vite.config.ts b/benchmarks/client-nav/scenarios/head/solid/vite.config.ts index 7b5a1e22b4..986b2de2b0 100644 --- a/benchmarks/client-nav/scenarios/head/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/head/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import solid from 'vite-plugin-solid' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -35,6 +36,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav head (solid)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts index 3630032e44..d188a9dd7a 100644 --- a/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-head', () => { - const test = setup() +test('client-head', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-head navigation loop (vue)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/head/vue/src/main.tsx b/benchmarks/client-nav/scenarios/head/vue/src/main.tsx index c96d3f3a2e..cae9b54f1d 100644 --- a/benchmarks/client-nav/scenarios/head/vue/src/main.tsx +++ b/benchmarks/client-nav/scenarios/head/vue/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import * as Vue from 'vue' import { RouterProvider, createRouter } from '@tanstack/vue-router' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -20,8 +22,8 @@ declare module '@tanstack/vue-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const component = const app = Vue.createApp({ diff --git a/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts index b115854c26..161f99a65c 100644 --- a/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts @@ -9,15 +9,15 @@ // 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 SettingsRouteImport } from './routes/settings' -import { Route as DocsRouteImport } from './routes/docs' import { Route as IndexRouteImport } from './routes/index' -import { Route as DocsSectionRouteImport } from './routes/docs.$section' +import { Route as DocsRouteImport } from './routes/docs' +import { Route as SettingsRouteImport } from './routes/settings' import { Route as ArticlesIdRouteImport } from './routes/articles.$id' +import { Route as DocsSectionRouteImport } from './routes/docs.$section' -const SettingsRoute = SettingsRouteImport.update({ - id: '/settings', - path: '/settings', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const DocsRoute = DocsRouteImport.update({ @@ -25,9 +25,14 @@ const DocsRoute = DocsRouteImport.update({ path: '/docs', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SettingsRoute = SettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => rootRouteImport, +} as any) +const ArticlesIdRoute = ArticlesIdRouteImport.update({ + id: '/articles/$id', + path: '/articles/$id', getParentRoute: () => rootRouteImport, } as any) const DocsSectionRoute = DocsSectionRouteImport.update({ @@ -35,11 +40,6 @@ const DocsSectionRoute = DocsSectionRouteImport.update({ path: '/$section', getParentRoute: () => DocsRoute, } as any) -const ArticlesIdRoute = ArticlesIdRouteImport.update({ - id: '/articles/$id', - path: '/articles/$id', - getParentRoute: () => rootRouteImport, -} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -86,11 +86,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/settings': { - id: '/settings' - path: '/settings' - fullPath: '/settings' - preLoaderRoute: typeof SettingsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/docs': { @@ -100,11 +100,18 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof DocsRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/settings': { + id: '/settings' + path: '/settings' + fullPath: '/settings' + preLoaderRoute: typeof SettingsRouteImport + parentRoute: typeof rootRouteImport + } + '/articles/$id': { + id: '/articles/$id' + path: '/articles/$id' + fullPath: '/articles/$id' + preLoaderRoute: typeof ArticlesIdRouteImport parentRoute: typeof rootRouteImport } '/docs/$section': { @@ -114,13 +121,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof DocsSectionRouteImport parentRoute: typeof DocsRoute } - '/articles/$id': { - id: '/articles/$id' - path: '/articles/$id' - fullPath: '/articles/$id' - preLoaderRoute: typeof ArticlesIdRouteImport - parentRoute: typeof rootRouteImport - } } } diff --git a/benchmarks/client-nav/scenarios/head/vue/vite.config.ts b/benchmarks/client-nav/scenarios/head/vue/vite.config.ts index 0ad2067925..bb1126d85f 100644 --- a/benchmarks/client-nav/scenarios/head/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/head/vue/vite.config.ts @@ -4,6 +4,7 @@ import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -34,6 +35,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav head (vue)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/history/react/setup.ts b/benchmarks/client-nav/scenarios/history/react/setup.ts index 130583b190..c26b7ffd08 100644 --- a/benchmarks/client-nav/scenarios/history/react/setup.ts +++ b/benchmarks/client-nav/scenarios/history/react/setup.ts @@ -11,6 +11,7 @@ export function setup() { return createScenarioSetup({ frameworkLabel: 'React', mount: mountTestApp, + historyMode: 'browser', steps, assertAfterStep: assertStepResult, }) diff --git a/benchmarks/client-nav/scenarios/history/react/speed.bench.ts b/benchmarks/client-nav/scenarios/history/react/speed.bench.ts index df2c951c03..6ec7031857 100644 --- a/benchmarks/client-nav/scenarios/history/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/history/react/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-history', () => { - const test = setup() +test('client-history', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-history navigation loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/history/react/src/main.tsx b/benchmarks/client-nav/scenarios/history/react/src/main.tsx index ef0b99555c..5febd6f795 100644 --- a/benchmarks/client-nav/scenarios/history/react/src/main.tsx +++ b/benchmarks/client-nav/scenarios/history/react/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import { RouterProvider, createRouter } from '@tanstack/react-router' import { createRoot } from 'react-dom/client' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -20,8 +22,8 @@ declare module '@tanstack/react-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const reactRoot = createRoot(container) reactRoot.render() diff --git a/benchmarks/client-nav/scenarios/history/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/history/react/src/routeTree.gen.ts index 61cc83c4c8..21bb12ba35 100644 --- a/benchmarks/client-nav/scenarios/history/react/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/history/react/src/routeTree.gen.ts @@ -9,24 +9,19 @@ // 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 GalleryRouteImport } from './routes/gallery' import { Route as IndexRouteImport } from './routes/index' -import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' +import { Route as GalleryRouteImport } from './routes/gallery' import { Route as PagesNRouteImport } from './routes/pages.$n' +import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' -const GalleryRoute = GalleryRouteImport.update({ - id: '/gallery', - path: '/gallery', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ - id: '/photos/$photoId', - path: '/photos/$photoId', +const GalleryRoute = GalleryRouteImport.update({ + id: '/gallery', + path: '/gallery', getParentRoute: () => rootRouteImport, } as any) const PagesNRoute = PagesNRouteImport.update({ @@ -34,6 +29,11 @@ const PagesNRoute = PagesNRouteImport.update({ path: '/pages/$n', getParentRoute: () => rootRouteImport, } as any) +const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ + id: '/photos/$photoId', + path: '/photos/$photoId', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -71,13 +71,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/gallery': { - id: '/gallery' - path: '/gallery' - fullPath: '/gallery' - preLoaderRoute: typeof GalleryRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -85,11 +78,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/photos/$photoId': { - id: '/photos/$photoId' - path: '/photos/$photoId' - fullPath: '/photos/$photoId' - preLoaderRoute: typeof PhotosPhotoIdRouteImport + '/gallery': { + id: '/gallery' + path: '/gallery' + fullPath: '/gallery' + preLoaderRoute: typeof GalleryRouteImport parentRoute: typeof rootRouteImport } '/pages/$n': { @@ -99,6 +92,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PagesNRouteImport parentRoute: typeof rootRouteImport } + '/photos/$photoId': { + id: '/photos/$photoId' + path: '/photos/$photoId' + fullPath: '/photos/$photoId' + preLoaderRoute: typeof PhotosPhotoIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/history/react/vite.config.ts b/benchmarks/client-nav/scenarios/history/react/vite.config.ts index 61a1b2feef..bdbde9c668 100644 --- a/benchmarks/client-nav/scenarios/history/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/history/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import react from '@vitejs/plugin-react' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -32,6 +33,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav history (react)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/history/shared.ts b/benchmarks/client-nav/scenarios/history/shared.ts index 9ddfa6c104..be6096cea8 100644 --- a/benchmarks/client-nav/scenarios/history/shared.ts +++ b/benchmarks/client-nav/scenarios/history/shared.ts @@ -8,6 +8,7 @@ * forward tail and the session history never grows past 4 entries. */ import type { ScenarioStep } from '../harness' +import type { RouterHistory } from '@tanstack/history' export const pageIds = ['1', '2', '3'] as const export const maskedPhotoId = '42' @@ -27,7 +28,7 @@ interface HistoryStepExpectation { step: ScenarioStep /** Expected router location pathname (the REAL location, even when masked). */ pathname: string - /** Expected window.location pathname when it differs (location masking). */ + /** Expected browser-history pathname when it differs (location masking). */ windowPathname?: string /** Marker test id that must be present in the container after the step. */ marker?: string @@ -52,7 +53,11 @@ export const stepExpectations: ReadonlyArray = [ export const steps = stepExpectations.map((expectation) => expectation.step) -export function assertStepResult(stepIndex: number, container: HTMLElement) { +export function assertStepResult( + stepIndex: number, + container: HTMLElement, + history: RouterHistory, +) { const expected = stepExpectations[stepIndex]! const loc = container.querySelector('[data-testid="loc"]')?.textContent @@ -63,9 +68,9 @@ export function assertStepResult(stepIndex: number, container: HTMLElement) { } const windowPathname = expected.windowPathname ?? expected.pathname - if (window.location.pathname !== windowPathname) { + if (history.location.pathname !== windowPathname) { throw new Error( - `Expected window.location.pathname to be "${windowPathname}" after step ${stepIndex}, received "${window.location.pathname}"`, + `Expected history.location.pathname to be "${windowPathname}" after step ${stepIndex}, received "${history.location.pathname}"`, ) } diff --git a/benchmarks/client-nav/scenarios/history/solid/setup.ts b/benchmarks/client-nav/scenarios/history/solid/setup.ts index 6a46971603..4adf55d6df 100644 --- a/benchmarks/client-nav/scenarios/history/solid/setup.ts +++ b/benchmarks/client-nav/scenarios/history/solid/setup.ts @@ -11,6 +11,7 @@ export function setup() { return createScenarioSetup({ frameworkLabel: 'Solid', mount: mountTestApp, + historyMode: 'browser', steps, assertAfterStep: assertStepResult, }) diff --git a/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts index 8e814bc133..56af035b2b 100644 --- a/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-history', () => { - const test = setup() +test('client-history', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-history navigation loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/history/solid/src/main.tsx b/benchmarks/client-nav/scenarios/history/solid/src/main.tsx index 817045bd02..fa9d239418 100644 --- a/benchmarks/client-nav/scenarios/history/solid/src/main.tsx +++ b/benchmarks/client-nav/scenarios/history/solid/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import { render } from 'solid-js/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -20,8 +22,8 @@ declare module '@tanstack/solid-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const unmount = render(() => , container) diff --git a/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts index a6ab2a4fc8..af253f4a15 100644 --- a/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts @@ -9,24 +9,19 @@ // 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 GalleryRouteImport } from './routes/gallery' import { Route as IndexRouteImport } from './routes/index' -import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' +import { Route as GalleryRouteImport } from './routes/gallery' import { Route as PagesNRouteImport } from './routes/pages.$n' +import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' -const GalleryRoute = GalleryRouteImport.update({ - id: '/gallery', - path: '/gallery', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ - id: '/photos/$photoId', - path: '/photos/$photoId', +const GalleryRoute = GalleryRouteImport.update({ + id: '/gallery', + path: '/gallery', getParentRoute: () => rootRouteImport, } as any) const PagesNRoute = PagesNRouteImport.update({ @@ -34,6 +29,11 @@ const PagesNRoute = PagesNRouteImport.update({ path: '/pages/$n', getParentRoute: () => rootRouteImport, } as any) +const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ + id: '/photos/$photoId', + path: '/photos/$photoId', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -71,13 +71,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/gallery': { - id: '/gallery' - path: '/gallery' - fullPath: '/gallery' - preLoaderRoute: typeof GalleryRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -85,11 +78,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/photos/$photoId': { - id: '/photos/$photoId' - path: '/photos/$photoId' - fullPath: '/photos/$photoId' - preLoaderRoute: typeof PhotosPhotoIdRouteImport + '/gallery': { + id: '/gallery' + path: '/gallery' + fullPath: '/gallery' + preLoaderRoute: typeof GalleryRouteImport parentRoute: typeof rootRouteImport } '/pages/$n': { @@ -99,6 +92,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PagesNRouteImport parentRoute: typeof rootRouteImport } + '/photos/$photoId': { + id: '/photos/$photoId' + path: '/photos/$photoId' + fullPath: '/photos/$photoId' + preLoaderRoute: typeof PhotosPhotoIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/history/solid/vite.config.ts b/benchmarks/client-nav/scenarios/history/solid/vite.config.ts index de0eda543c..4da589ff0e 100644 --- a/benchmarks/client-nav/scenarios/history/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/history/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import solid from 'vite-plugin-solid' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -35,6 +36,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav history (solid)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/history/vue/setup.ts b/benchmarks/client-nav/scenarios/history/vue/setup.ts index 97b74b3892..df689964e4 100644 --- a/benchmarks/client-nav/scenarios/history/vue/setup.ts +++ b/benchmarks/client-nav/scenarios/history/vue/setup.ts @@ -11,6 +11,7 @@ export function setup() { return createScenarioSetup({ frameworkLabel: 'Vue', mount: mountTestApp, + historyMode: 'browser', steps, assertAfterStep: assertStepResult, }) diff --git a/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts index be2956bd85..3d36ac4cfa 100644 --- a/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-history', () => { - const test = setup() +test('client-history', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-history navigation loop (vue)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/history/vue/src/main.tsx b/benchmarks/client-nav/scenarios/history/vue/src/main.tsx index c96d3f3a2e..cae9b54f1d 100644 --- a/benchmarks/client-nav/scenarios/history/vue/src/main.tsx +++ b/benchmarks/client-nav/scenarios/history/vue/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import * as Vue from 'vue' import { RouterProvider, createRouter } from '@tanstack/vue-router' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -20,8 +22,8 @@ declare module '@tanstack/vue-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const component = const app = Vue.createApp({ diff --git a/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts index cee1b68870..519aef7c8f 100644 --- a/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts @@ -9,24 +9,19 @@ // 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 GalleryRouteImport } from './routes/gallery' import { Route as IndexRouteImport } from './routes/index' -import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' +import { Route as GalleryRouteImport } from './routes/gallery' import { Route as PagesNRouteImport } from './routes/pages.$n' +import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' -const GalleryRoute = GalleryRouteImport.update({ - id: '/gallery', - path: '/gallery', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ - id: '/photos/$photoId', - path: '/photos/$photoId', +const GalleryRoute = GalleryRouteImport.update({ + id: '/gallery', + path: '/gallery', getParentRoute: () => rootRouteImport, } as any) const PagesNRoute = PagesNRouteImport.update({ @@ -34,6 +29,11 @@ const PagesNRoute = PagesNRouteImport.update({ path: '/pages/$n', getParentRoute: () => rootRouteImport, } as any) +const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ + id: '/photos/$photoId', + path: '/photos/$photoId', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -71,13 +71,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/gallery': { - id: '/gallery' - path: '/gallery' - fullPath: '/gallery' - preLoaderRoute: typeof GalleryRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -85,11 +78,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/photos/$photoId': { - id: '/photos/$photoId' - path: '/photos/$photoId' - fullPath: '/photos/$photoId' - preLoaderRoute: typeof PhotosPhotoIdRouteImport + '/gallery': { + id: '/gallery' + path: '/gallery' + fullPath: '/gallery' + preLoaderRoute: typeof GalleryRouteImport parentRoute: typeof rootRouteImport } '/pages/$n': { @@ -99,6 +92,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PagesNRouteImport parentRoute: typeof rootRouteImport } + '/photos/$photoId': { + id: '/photos/$photoId' + path: '/photos/$photoId' + fullPath: '/photos/$photoId' + preLoaderRoute: typeof PhotosPhotoIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/history/vue/vite.config.ts b/benchmarks/client-nav/scenarios/history/vue/vite.config.ts index 58986d6526..c5f1ca9807 100644 --- a/benchmarks/client-nav/scenarios/history/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/history/vue/vite.config.ts @@ -4,6 +4,7 @@ import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -34,6 +35,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav history (vue)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/hydration/react/fixture.ts b/benchmarks/client-nav/scenarios/hydration/react/fixture.ts new file mode 100644 index 0000000000..950c870a1c --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/fixture.ts @@ -0,0 +1,31 @@ +export const ordinaryLinkCount = 192 +export const hashLinkCount = 8 +export const serverUrl = '/teams/team-7/items/item-42?view=summary' +export const clientUrl = `${serverUrl}#details` + +export interface Diagnostics { + beforeLoads: number + loaders: number + mounted: boolean + clicks: number + ordinaryRenders: number + hashRenders: number + countRenders: boolean +} + +export function createDiagnostics(countRenders = false): Diagnostics { + return { + beforeLoads: 0, + loaders: 0, + mounted: false, + clicks: 0, + ordinaryRenders: 0, + hashRenders: 0, + countRenders, + } +} + +export interface FixtureArtifact { + html: string + scripts: Array +} diff --git a/benchmarks/client-nav/scenarios/hydration/react/generate-fixture.mjs b/benchmarks/client-nav/scenarios/hydration/react/generate-fixture.mjs new file mode 100644 index 0000000000..fbc67c5a08 --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/generate-fixture.mjs @@ -0,0 +1,23 @@ +import assert from 'node:assert/strict' +import { writeFile } from 'node:fs/promises' +import { JSDOM } from 'jsdom' + +if (process.env.NODE_ENV !== 'production') { + throw new Error('Generate the hydration fixture in production mode') +} +const { renderFixture } = await import('./dist/server/server.js') +const html = await renderFixture() +const dom = new JSDOM(html) +try { + const scriptElements = [...dom.window.document.querySelectorAll('script')] + assert.ok(scriptElements.length > 0) + assert.ok(scriptElements.every((script) => !script.src)) + const scripts = scriptElements.map((script) => script.textContent) + assert.ok(scripts.some((script) => script.includes('$_TSR'))) + await writeFile( + new URL('./dist/fixture.json', import.meta.url), + JSON.stringify({ html, scripts }), + ) +} finally { + dom.window.close() +} diff --git a/benchmarks/client-nav/scenarios/hydration/react/hydration.test.ts b/benchmarks/client-nav/scenarios/hydration/react/hydration.test.ts new file mode 100644 index 0000000000..7e466cbaed --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/hydration.test.ts @@ -0,0 +1,93 @@ +import { expect, test } from 'vitest' +import { hashLinkCount, ordinaryLinkCount } from './fixture' +import { setup } from './setup' +import { settleHydration } from './settle' + +const turn = () => new Promise((resolve) => setImmediate(resolve)) + +test('restores data and context into fresh DOMs and includes follow-up renders', async () => { + const scenario = setup({ countRenders: true }) + const schedulerTasks = new Set() + for (let iteration = 0; iteration < 3; iteration++) { + await scenario.before() + try { + expect(scenario.snapshot().diagnostics.mounted).toBe(false) + expect(scenario.snapshot().matches).toBeUndefined() + await scenario.run() + schedulerTasks.add(scenario.schedulerTasks()) + const completed = scenario.snapshot() + // Supports both main's extra Link update and the optimized snapshot. + expect([ordinaryLinkCount, ordinaryLinkCount * 2]).toContain( + completed.diagnostics.ordinaryRenders, + ) + expect(completed.diagnostics.hashRenders).toBeGreaterThanOrEqual( + hashLinkCount + hashLinkCount / 2, + ) + for (let index = 0; index < 4; index++) { + await turn() + } + expect(scenario.snapshot()).toEqual(completed) + await expect(scenario.run()).rejects.toThrow('newly prepared sample') + } finally { + await scenario.after() + } + } + // React yields on its pinned clock, never on wall time spent hydrating. + expect(schedulerTasks.size).toBe(1) +}) + +test('rejects an empty measurement and still releases its sample', async () => { + const scenario = setup() + await scenario.before() + await expect(scenario.after()).rejects.toThrow( + 'Hydration sample was not completed', + ) + await scenario.before() + try { + await scenario.run() + } finally { + await scenario.after() + } +}) + +test('waits for a commit and scheduler work lasting more than 100 turns', async () => { + let committed = false + const commit = (async () => { + for (let index = 0; index < 150; index++) { + await turn() + } + committed = true + })() + let remainingCallbacks = 150 + await settleHydration( + commit, + () => { + expect(committed).toBe(true) + return remainingCallbacks-- <= 0 + }, + () => 'delayed commit', + ) + expect(remainingCallbacks).toBeLessThan(0) +}) + +test('retains a watchdog for a commit that never completes', async () => { + await expect( + settleHydration( + new Promise(() => {}), + () => true, + () => 'commit pending', + 10, + ), + ).rejects.toThrow('Hydration did not settle within 10ms: commit pending') +}) + +test('retains a watchdog when scheduler work never becomes idle', async () => { + await expect( + settleHydration( + Promise.resolve(), + () => false, + () => 'callbacks pending', + 10, + ), + ).rejects.toThrow('Hydration did not settle within 10ms: callbacks pending') +}) diff --git a/benchmarks/client-nav/scenarios/hydration/react/project.json b/benchmarks/client-nav/scenarios/hydration/react/project.json new file mode 100644 index 0000000000..ca23838c0f --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-hydration-react", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { "projects": ["@tanstack/react-router"], "target": "build" } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.server.config.ts && NODE_ENV=production node {projectRoot}/generate-fixture.mjs && NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:unit": { + "executor": "nx:run-commands", + "dependsOn": ["build:client"], + "options": { + "command": "vitest run --config ./scenarios/hydration/react/vite.config.ts", + "cwd": "benchmarks/client-nav" + } + }, + "test:perf": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production vitest bench --mode benchmark --run --config ./scenarios/hydration/react/vite.config.ts", + "cwd": "benchmarks/client-nav" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { "projects": ["@tanstack/react-router"], "target": "build" } + ], + "options": { "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" } + } + } +} diff --git a/benchmarks/client-nav/scenarios/hydration/react/settle.ts b/benchmarks/client-nav/scenarios/hydration/react/settle.ts new file mode 100644 index 0000000000..cc4c09a72d --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/settle.ts @@ -0,0 +1,35 @@ +const turn = () => new Promise((resolve) => setImmediate(resolve)) + +export async function settleHydration( + committed: Promise, + isIdle: () => boolean, + describeProgress: () => string, + timeoutMs = 60_000, +) { + let timeoutError: Error | undefined + let watchdog: ReturnType | undefined + const timeout = new Promise((_, reject) => { + watchdog = setTimeout(() => { + timeoutError = new Error( + `Hydration did not settle within ${timeoutMs}ms: ${describeProgress()}`, + ) + reject(timeoutError) + }, timeoutMs) + }) + try { + // Concurrent hydration can need many more scheduler turns under CPU + // instrumentation. Await its commit instead of limiting successful work + // to an arbitrary number of event-loop polls. + await Promise.race([committed, timeout]) + let idleTurns = 0 + while (idleTurns < 2) { + await turn() + if (timeoutError) { + throw timeoutError + } + idleTurns = isIdle() ? idleTurns + 1 : 0 + } + } finally { + clearTimeout(watchdog) + } +} diff --git a/benchmarks/client-nav/scenarios/hydration/react/setup.ts b/benchmarks/client-nav/scenarios/hydration/react/setup.ts new file mode 100644 index 0000000000..7c588af3fd --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/setup.ts @@ -0,0 +1,316 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { Script } from 'node:vm' +import { JSDOM, VirtualConsole } from 'jsdom' +import { clientUrl, hashLinkCount, ordinaryLinkCount } from './fixture' +import { settleHydration } from './settle' +import type { FixtureArtifact } from './fixture' +import type * as Client from './src/client' + +type ClientApp = typeof Client +const turn = () => new Promise((resolve) => setImmediate(resolve)) + +// React's scheduler ends a time slice once performance.now() has advanced 5 ms. +// Under CodSpeed's CPU simulation the wall clock advances much further per +// instruction, by a runner-dependent factor, so real time turned identical +// samples into different numbers of yields, scheduler tasks and event-loop +// turns. With a frozen clock React yields only to paint after a commit, as on +// a fast host. 1 s is past React's initial 300 ms fallback throttle. Only the +// window's performance clock is pinned: Date.now(), which the Router uses for +// match timestamps, is unchanged. +const schedulerTime = 1_000 + +export function setup({ countRenders = false } = {}) { + // Compile once, outside measurement. Evaluation below creates fresh objects + // in each window's realm; neither the payload nor module state is reused. + const artifact: FixtureArtifact = JSON.parse( + readFileSync(new URL('./dist/fixture.json', import.meta.url), 'utf8'), + ) + const clientPath = new URL('./dist/client/client.js', import.meta.url) + const clientScript = new Script(readFileSync(clientPath, 'utf8'), { + filename: fileURLToPath(clientPath), + }) + const bootstrapScripts = artifact.scripts.map( + (source, index) => + new Script(source, { + filename: `hydration-bootstrap-${index}.js`, + }), + ) + let current: Awaited> | undefined + + async function prepare() { + const errors: Array = [] + const virtualConsole = new VirtualConsole() + virtualConsole.on('jsdomError', (error) => errors.push(String(error))) + virtualConsole.on('error', (...args) => + errors.push(args.map(String).join(' ')), + ) + const dom = new JSDOM(artifact.html, { + url: `http://localhost${clientUrl}`, + runScripts: 'outside-only', + virtualConsole, + }) + const immediates = new Set() + const scheduler = { tasks: 0 } + try { + Object.assign(dom.window, { + TextEncoder, + TextDecoder, + ReadableStream, + WritableStream, + TransformStream, + // Let React's production scheduler use the same task-turn primitive as + // the existing Node client benchmarks, without a real-delay timer. + setImmediate( + callback: (...args: Array) => void, + ...args: Array + ) { + scheduler.tasks++ + const handle = setImmediate(() => { + immediates.delete(handle) + callback(...args) + }) + immediates.add(handle) + return handle + }, + clearImmediate(handle: NodeJS.Immediate) { + immediates.delete(handle) + clearImmediate(handle) + }, + fetch() { + throw new Error('Hydration attempted a network request') + }, + scrollTo() {}, + }) + dom.window.performance.now = () => schedulerTime + const context = dom.getInternalVMContext() + // jsdom has no layout/scroll implementation; only hydration CPU is measured. + dom.window.HTMLElement.prototype.scrollIntoView = () => {} + clientScript.runInContext(context) + const app = (dom.window as unknown as { HydrationBenchmark: ClientApp }) + .HydrationBenchmark + assert.equal(app.serverEnvironment, false) + const anchors = Array.from(dom.window.document.querySelectorAll('a')) + const scriptElements = Array.from( + dom.window.document.querySelectorAll('script'), + ) + const executingScript = { current: null as HTMLScriptElement | null } + Object.defineProperty(dom.window.document, 'currentScript', { + configurable: true, + get: () => executingScript.current, + }) + assert.equal(anchors.length, ordinaryLinkCount + hashLinkCount) + const content = dom.window.document.getElementById('hydration-content') + assert.ok(content) + // Finish jsdom's initial document lifecycle before opening the measure. + await turn() + assert.equal(dom.window.document.readyState, 'complete') + assert.equal(app.ready(), false) + return { + dom, + context, + app, + anchors, + content, + scriptElements, + executingScript, + immediates, + scheduler, + errors, + started: false, + completed: false, + failed: false, + } + } catch (error) { + for (const handle of immediates) { + clearImmediate(handle) + } + dom.window.close() + throw error + } + } + + async function before() { + if (current) { + throw new Error('Previous hydration sample was not disposed') + } + current = await prepare() + } + + async function run() { + const sample = current + if (!sample || sample.started) { + throw new Error('Hydration requires a newly prepared sample') + } + sample.started = true + try { + // HTML parsing/module evaluation are already done. Payload execution, + // router initialization/restoration and React hydration are measured. + for (let index = 0; index < bootstrapScripts.length; index++) { + // SSR bootstrap scripts remove their own script element after running. + sample.executingScript.current = sample.scriptElements[index]! + try { + bootstrapScripts[index]!.runInContext(sample.context) + } finally { + sample.executingScript.current = null + } + } + await settleHydration( + sample.app.start(countRenders), + () => sample.immediates.size === 0, + () => { + const progress = sample.app.snapshot() + return JSON.stringify({ + diagnostics: progress.diagnostics, + errors: [...sample.errors, ...progress.errors], + restoredMatches: progress.matches?.length, + pendingSchedulerCallbacks: sample.immediates.size, + }) + }, + ) + if (sample.errors.length) { + throw new Error(sample.errors.join('\n')) + } + assert.ok( + sample.app.ready(), + 'Hydration committed without the expected active links', + ) + sample.completed = true + } catch (error) { + sample.failed = true + throw error + } + } + + function snapshot() { + if (!current) { + throw new Error('No hydration sample') + } + // Normalize realm prototypes only for untimed assertions. + return JSON.parse(JSON.stringify(current.app.snapshot())) as ReturnType< + ClientApp['snapshot'] + > + } + + function schedulerTasks() { + if (!current) { + throw new Error('No hydration sample') + } + return current.scheduler.tasks + } + + function validate() { + assert.ok(current?.started) + const { dom, anchors, content, errors } = current + const doc = dom.window.document + const result = snapshot() + assert.deepEqual(errors, []) + assert.deepEqual(result.errors, []) + assert.equal(result.diagnostics.beforeLoads, 0) + assert.equal(result.diagnostics.loaders, 0) + assert.equal(result.diagnostics.mounted, true) + assert.equal(result.location, clientUrl) + assert.equal(result.matches?.length, 3) + for (const match of result.matches) { + assert.equal(match.status, 'success') + assert.deepEqual(match.context.viewer, { + id: 'viewer-3', + name: 'Ada', + role: 'editor', + }) + } + assert.deepEqual(result.matches[1]!.context.team, { + id: 'team-7', + member: 'viewer-3', + }) + assert.deepEqual(result.matches[2]!.context.permissions, { edit: true }) + assert.deepEqual(result.matches[1]!.loaderData, { + title: 'Team team-7', + categories: ['open', 'closed'], + }) + const data = result.matches[2]!.loaderData as { + owner: string + selected: string + rows: Array<{ + id: string + label: string + details: { score: number; open: boolean } + }> + } + assert.equal(data.owner, 'viewer-3') + assert.equal(data.selected, 'item-42') + assert.equal(data.rows.length, ordinaryLinkCount) + assert.equal(doc.getElementById('hydration-content'), content) + assert.equal(doc.querySelectorAll('a').length, anchors.length) + assert.equal(doc.getElementById('viewer')?.textContent, 'Ada') + assert.equal(doc.getElementById('permission')?.textContent, 'Editable') + for (const anchor of anchors) { + assert.equal(doc.getElementById(anchor.id), anchor) + } + for (let index = 0; index < ordinaryLinkCount; index++) { + const anchor = doc.getElementById(`ordinary-item-${index}`)! + assert.equal( + anchor.getAttribute('href'), + `/teams/team-7/items/item-${index}?view=summary`, + ) + assert.equal(anchor.textContent, `Item ${index}`) + assert.equal( + anchor.getAttribute('data-status'), + index === 42 ? 'active' : null, + ) + assert.deepEqual(data.rows[index], { + id: `item-${index}`, + label: `Item ${index}`, + details: { score: index * 3, open: index % 2 === 0 }, + }) + } + for (let index = 0; index < hashLinkCount; index++) { + assert.equal( + doc.getElementById(`hash-${index}`)?.getAttribute('data-status'), + index % 2 === 0 ? 'active' : null, + ) + } + doc + .getElementById('interactive')! + .dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true })) + assert.equal( + current.app.snapshot().diagnostics.clicks, + result.diagnostics.clicks + 1, + ) + } + + async function after() { + const sample = current + if (!sample) { + return + } + try { + if (!sample.failed) { + assert.ok(sample.completed, 'Hydration sample was not completed') + validate() + } + } finally { + current = undefined + try { + sample.app.dispose() + // Unmount work and its scheduled effects stay outside the measure. + await turn() + await turn() + } finally { + for (const handle of sample.immediates) { + clearImmediate(handle) + } + sample.dom.window.close() + } + } + } + + return { + before, + run, + after, + snapshot, + schedulerTasks, + } +} diff --git a/benchmarks/client-nav/scenarios/hydration/react/speed.bench.ts b/benchmarks/client-nav/scenarios/hydration/react/speed.bench.ts new file mode 100644 index 0000000000..643877760e --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { setup } from './setup' + +test('client-hydration', async ({ bench }) => { + const scenario = setup() + + await bench( + 'hydrate restored route state and mixed Links (react)', + { beforeEach: scenario.before, afterEach: scenario.after }, + async () => { + await scenario.run() + }, + ).run({ + time: 5000, + warmupTime: 1000, + warmupIterations: 20, + throws: true, + }) +}) diff --git a/benchmarks/client-nav/scenarios/hydration/react/src/app.tsx b/benchmarks/client-nav/scenarios/hydration/react/src/app.tsx new file mode 100644 index 0000000000..e9797f71fa --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/src/app.tsx @@ -0,0 +1,216 @@ +import { useEffect } from 'react' +import { + HeadContent, + Link, + Outlet, + Scripts, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + useHydrated, +} from '@tanstack/react-router' +import { + clientUrl, + hashLinkCount, + ordinaryLinkCount, + serverUrl, +} from '../fixture' +import type { ReactNode } from 'react' +import type { Diagnostics } from '../fixture' + +export function createFixtureRouter( + server: boolean, + diagnostics: Diagnostics, + onHydrated: () => void = () => {}, +) { + function beforeLoad() { + diagnostics.beforeLoads++ + if (!server) { + throw new Error('Hydration reran beforeLoad instead of restoring context') + } + } + + function loader() { + diagnostics.loaders++ + if (!server) { + throw new Error('Hydration reran a loader instead of restoring data') + } + } + + const root = createRootRoute({ + beforeLoad: () => { + beforeLoad() + return { viewer: { id: 'viewer-3', name: 'Ada', role: 'editor' } } + }, + head: () => ({ + meta: [{ charSet: 'utf-8' }, { title: 'Hydration benchmark' }], + }), + shellComponent: Document, + }) + const team = createRoute({ + getParentRoute: () => root, + path: '/teams/$teamId', + beforeLoad: ({ context, params }) => { + beforeLoad() + return { team: { id: params.teamId, member: context.viewer.id } } + }, + loader: ({ context }) => { + loader() + return { + title: `Team ${context.team.id}`, + categories: ['open', 'closed'], + } + }, + component: Team, + }) + const items = createRoute({ + getParentRoute: () => team, + path: 'items/$itemId', + validateSearch: (search: Record) => ({ + view: search.view === 'details' ? 'details' : 'summary', + }), + beforeLoad: ({ context }) => { + beforeLoad() + return { permissions: { edit: context.viewer.role === 'editor' } } + }, + loader: ({ context, params }) => { + loader() + return { + selected: params.itemId, + owner: context.team.member, + rows: Array.from({ length: ordinaryLinkCount }, (_, index) => ({ + id: `item-${index}`, + label: `Item ${index}`, + details: { score: index * 3, open: index % 2 === 0 }, + })), + } + }, + component: Items, + }) + + function Document({ children }: { children: ReactNode }) { + return ( + + + + + + {children} + + + + ) + } + + function Team() { + const context = team.useRouteContext() + const data = team.useLoaderData() + return ( +
+

{data.title}

+

{context.viewer.name}

+ +
+ ) + } + + function Items() { + const data = items.useLoaderData() + const context = items.useRouteContext() + useEffect(() => { + diagnostics.mounted = true + }, []) + return ( + <> +

+ {context.permissions.edit ? 'Editable' : 'Read only'} +

+ + + + {data.rows.map((row) => ( + + + + + + ))} + +
{row.id}{row.details.score} + + {diagnostics.countRenders + ? () => { + diagnostics.ordinaryRenders++ + return row.label + } + : row.label} + +
+ +
Details
+ + + ) + } + + function HydrationComplete() { + const hydrated = useHydrated() + useEffect(() => { + if (hydrated) { + onHydrated() + } + }, [hydrated]) + return null + } + + return createRouter({ + routeTree: root.addChildren([team.addChildren([items])]), + history: createMemoryHistory({ + initialEntries: [server ? serverUrl : clientUrl], + }), + isServer: server, + scrollRestoration: false, + defaultHashScrollIntoView: false, + defaultPreload: false, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/client-nav/scenarios/hydration/react/src/client.tsx b/benchmarks/client-nav/scenarios/hydration/react/src/client.tsx new file mode 100644 index 0000000000..42c5a5104e --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/src/client.tsx @@ -0,0 +1,83 @@ +import { startTransition } from 'react' +import { hydrateRoot } from 'react-dom/client' +import { RouterProvider } from '@tanstack/react-router' +import { hydrate } from '@tanstack/react-router/ssr/client' +import { isServer } from '@tanstack/router-core/isServer' +import { createDiagnostics, hashLinkCount } from '../fixture' +import { createFixtureRouter } from './app' + +export const serverEnvironment = isServer +let router: ReturnType | undefined +let root: ReturnType | undefined +let diagnostics = createDiagnostics() +const errors: Array = [] + +export async function start(countRenders = false) { + if (router) { + throw new Error('A hydration sample must use a fresh client realm') + } + if (!window.$_TSR?.router) { + throw new Error('Missing SSR hydration payload') + } + diagnostics = createDiagnostics(countRenders) + let resolveHydrated!: () => void + let rejectHydrated!: (error: unknown) => void + const hydrated = new Promise((resolve, reject) => { + resolveHydrated = resolve + rejectHydrated = reject + }) + router = createFixtureRouter(false, diagnostics, resolveHydrated) + // This is the same restoration path used by Start, without a module-cached + // RouterClient/StartClient promise or a live server in the worker. + await hydrate(router) + window.$_TSR.h() + startTransition(() => { + root = hydrateRoot(document, , { + onRecoverableError: (error) => { + errors.push(String(error)) + rejectHydrated(error) + }, + onUncaughtError: (error) => { + errors.push(String(error)) + rejectHydrated(error) + }, + }) + }) + await hydrated +} + +export function ready() { + if (!diagnostics.mounted) { + return false + } + // Matching hash Links only become active in the follow-up hydration commit. + // Ending at the first mount effect would miss the work this scenario targets. + for (let index = 0; index < hashLinkCount; index += 2) { + if ( + document.getElementById(`hash-${index}`)?.getAttribute('data-status') !== + 'active' + ) { + return false + } + } + return true +} + +export function snapshot() { + const matches = router?.stores.matches.get() + return { + diagnostics: { ...diagnostics }, + errors: [...errors], + location: router?.stores.location.get().href, + matches: matches?.map((match) => ({ + status: match.status, + context: match.context, + loaderData: match.loaderData, + })), + } +} + +export function dispose() { + root?.unmount() + router?.history.destroy() +} diff --git a/benchmarks/client-nav/scenarios/hydration/react/src/server.tsx b/benchmarks/client-nav/scenarios/hydration/react/src/server.tsx new file mode 100644 index 0000000000..713b0a77f2 --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/src/server.tsx @@ -0,0 +1,29 @@ +import { + createRequestHandler, + defaultStreamHandler, +} from '@tanstack/react-router/ssr/server' +import { isServer } from '@tanstack/router-core/isServer' +import { createDiagnostics, serverUrl } from '../fixture' +import { createFixtureRouter } from './app' + +export async function renderFixture() { + if ((isServer as boolean | undefined) !== true) { + throw new Error('Fixture generation requires the production server build') + } + const diagnostics = createDiagnostics() + const response = await createRequestHandler({ + createRouter: () => createFixtureRouter(true, diagnostics), + request: new Request(`http://localhost${serverUrl}`), + })(defaultStreamHandler) + const html = await response.text() + if ( + response.status !== 200 || + diagnostics.beforeLoads !== 3 || + diagnostics.loaders !== 2 + ) { + throw new Error( + 'SSR fixture did not execute its beforeLoad and loader functions', + ) + } + return html +} diff --git a/benchmarks/client-nav/scenarios/hydration/react/tsconfig.json b/benchmarks/client-nav/scenarios/hydration/react/tsconfig.json new file mode 100644 index 0000000000..23dd08de8b --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": ["./*.ts", "./src/**/*"] +} diff --git a/benchmarks/client-nav/scenarios/hydration/react/vite.config.ts b/benchmarks/client-nav/scenarios/hydration/react/vite.config.ts new file mode 100644 index 0000000000..62ab87115b --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/vite.config.ts @@ -0,0 +1,36 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import react from '@vitejs/plugin-react' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +export default defineConfig({ + root: fileURLToPath(new URL('.', import.meta.url)), + define: { 'process.env.NODE_ENV': JSON.stringify('production') }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + react(), + ], + resolve: { conditions: ['browser', 'production'] }, + build: { + outDir: './dist/client', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/client.tsx', + name: 'HydrationBenchmark', + formats: ['iife'], + fileName: () => 'client.js', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav hydration (react)', + watch: false, + environment: 'node', + isolate: true, + include: ['hydration.test.ts'], + benchmark: { include: ['speed.bench.ts'] }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/hydration/react/vite.server.config.ts b/benchmarks/client-nav/scenarios/hydration/react/vite.server.config.ts new file mode 100644 index 0000000000..fbf6a149b9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/react/vite.server.config.ts @@ -0,0 +1,26 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' + +export default defineConfig({ + root: fileURLToPath(new URL('.', import.meta.url)), + define: { 'process.env.NODE_ENV': JSON.stringify('production') }, + plugins: [react()], + resolve: { conditions: ['node', 'production'] }, + ssr: { noExternal: true }, + build: { + ssr: true, + outDir: './dist/server', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/server.tsx', + formats: ['es'], + fileName: () => 'server.js', + }, + rolldownOptions: { + platform: 'node', + external: [/^node:/, /^react(?:\/|$)/, /^react-dom(?:\/|$)/], + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/hydration/solid/fixture.ts b/benchmarks/client-nav/scenarios/hydration/solid/fixture.ts new file mode 100644 index 0000000000..4c86d0e2f4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/fixture.ts @@ -0,0 +1,35 @@ +export { + clientUrl, + hashLinkCount, + ordinaryLinkCount, + serverUrl, +} from '../react/fixture' +export type { FixtureArtifact } from '../react/fixture' + +export interface Diagnostics { + beforeLoads: number + loaders: number + mounted: boolean + rendered: number + clicks: number + countUpdates: boolean + ordinaryEvaluations: number + hashEvaluations: number + initialHashStates: Array + hashStates: Array +} + +export function createDiagnostics(countUpdates = false): Diagnostics { + return { + beforeLoads: 0, + loaders: 0, + mounted: false, + rendered: 0, + clicks: 0, + countUpdates, + ordinaryEvaluations: 0, + hashEvaluations: 0, + initialHashStates: [], + hashStates: [], + } +} diff --git a/benchmarks/client-nav/scenarios/hydration/solid/generate-fixture.mjs b/benchmarks/client-nav/scenarios/hydration/solid/generate-fixture.mjs new file mode 100644 index 0000000000..63647e1be7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/generate-fixture.mjs @@ -0,0 +1,30 @@ +import assert from 'node:assert/strict' +import { writeFile } from 'node:fs/promises' +import { JSDOM } from 'jsdom' + +if (process.env.NODE_ENV !== 'production') { + throw new Error('Generate the hydration fixture in production mode') +} +const { renderFixture } = await import('./dist/server/server.js') +const html = await renderFixture() +const dom = new JSDOM(html) +try { + const doc = dom.window.document + const scriptElements = [...doc.querySelectorAll('script')] + assert.ok(scriptElements.length > 0) + assert.ok(scriptElements.every((script) => !script.src)) + const scripts = scriptElements.map((script) => script.textContent) + assert.ok(scripts.some((script) => script.includes('$_TSR'))) + assert.ok(scripts.some((script) => script.includes('_$HY'))) + assert.ok(doc.documentElement.hasAttribute('data-hk')) + assert.ok(doc.getElementById('hydration-content')?.hasAttribute('data-hk')) + assert.ok( + [...doc.querySelectorAll('a')].every((a) => a.hasAttribute('data-hk')), + ) + await writeFile( + new URL('./dist/fixture.json', import.meta.url), + JSON.stringify({ html, scripts }), + ) +} finally { + dom.window.close() +} diff --git a/benchmarks/client-nav/scenarios/hydration/solid/hydration.test.ts b/benchmarks/client-nav/scenarios/hydration/solid/hydration.test.ts new file mode 100644 index 0000000000..4e5f3208ca --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/hydration.test.ts @@ -0,0 +1,81 @@ +import { expect, test } from 'vitest' +import { hashLinkCount, ordinaryLinkCount } from './fixture' +import { setup } from './setup' + +const turn = () => new Promise((resolve) => setImmediate(resolve)) + +test('restores fresh DOMs and route state and completes hash-link reactivity', async () => { + const scenario = setup({ countUpdates: true }) + let previous: ReturnType | undefined + for (let iteration = 0; iteration < 3; iteration++) { + await scenario.before() + try { + const initial = scenario.snapshot() + expect(initial.matches).toBeUndefined() + expect(initial.diagnostics.mounted).toBe(false) + expect(initial.diagnostics.rendered).toBe(0) + expect(initial.diagnostics.clicks).toBe(0) + expect(initial.diagnostics.ordinaryEvaluations).toBe(0) + expect(initial.diagnostics.hashEvaluations).toBe(0) + expect(initial.diagnostics.initialHashStates).toEqual([]) + await scenario.run() + const completed = scenario.snapshot() + expect(completed.diagnostics.ordinaryEvaluations).toBeGreaterThanOrEqual( + ordinaryLinkCount, + ) + expect(completed.diagnostics.initialHashStates).toEqual( + Array.from({ length: hashLinkCount }, () => false), + ) + expect(completed.diagnostics.hashStates).toEqual( + Array.from({ length: hashLinkCount }, (_, index) => index % 2 === 0), + ) + expect(completed.diagnostics.hashEvaluations).toBeGreaterThanOrEqual( + hashLinkCount + hashLinkCount / 2, + ) + expect(completed.hydrating).toBe(false) + for (let index = 0; index < 4; index++) { + await turn() + } + expect(scenario.snapshot()).toEqual(completed) + if (previous) { + expect(completed).toEqual(previous) + } + previous = completed + await expect(scenario.run()).rejects.toThrow('newly prepared sample') + } finally { + // Untimed assertions include DOM identity, all restored data/context, + // native event handling, and the absence of hydration diagnostics. + await scenario.after() + } + } +}) + +test('prepares every sample without counting diagnostics', async () => { + const scenario = setup() + for (let iteration = 0; iteration < 2; iteration++) { + await scenario.before() + try { + expect(scenario.snapshot().diagnostics.mounted).toBe(false) + expect(scenario.snapshot().diagnostics.clicks).toBe(0) + await scenario.run() + expect(scenario.snapshot().diagnostics.hashEvaluations).toBe(0) + } finally { + await scenario.after() + } + } +}) + +test('rejects an empty measurement and still releases its sample', async () => { + const scenario = setup() + await scenario.before() + await expect(scenario.after()).rejects.toThrow( + 'Hydration sample was not completed', + ) + await scenario.before() + try { + await expect(scenario.before()).rejects.toThrow('was not disposed') + await scenario.run() + } finally { + await scenario.after() + } +}) diff --git a/benchmarks/client-nav/scenarios/hydration/solid/project.json b/benchmarks/client-nav/scenarios/hydration/solid/project.json new file mode 100644 index 0000000000..1fa162771b --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-hydration-solid", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { "projects": ["@tanstack/solid-router"], "target": "build" } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.server.config.ts && NODE_ENV=production node {projectRoot}/generate-fixture.mjs && NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:unit": { + "executor": "nx:run-commands", + "dependsOn": ["build:client"], + "options": { + "command": "vitest run --config ./scenarios/hydration/solid/vite.config.ts", + "cwd": "benchmarks/client-nav" + } + }, + "test:perf": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production vitest bench --mode benchmark --run --config ./scenarios/hydration/solid/vite.config.ts", + "cwd": "benchmarks/client-nav" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { "projects": ["@tanstack/solid-router"], "target": "build" } + ], + "options": { "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" } + } + } +} diff --git a/benchmarks/client-nav/scenarios/hydration/solid/setup.ts b/benchmarks/client-nav/scenarios/hydration/solid/setup.ts new file mode 100644 index 0000000000..ebdbc8e9b2 --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/setup.ts @@ -0,0 +1,326 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { Script } from 'node:vm' +import { JSDOM, VirtualConsole } from 'jsdom' +import { clientUrl, hashLinkCount, ordinaryLinkCount } from './fixture' +import type { FixtureArtifact } from './fixture' +import type * as Client from './src/client' + +type ClientApp = typeof Client +const turn = () => new Promise((resolve) => setImmediate(resolve)) +const maxSettleTurns = 100 + +export function setup({ countUpdates = false } = {}) { + // Compile once, outside measurement; evaluate the entire production bundle + // anew in every window, including Solid's module-level hydration state. + const artifact: FixtureArtifact = JSON.parse( + readFileSync(new URL('./dist/fixture.json', import.meta.url), 'utf8'), + ) + const clientPath = new URL('./dist/client/client.js', import.meta.url) + const clientScript = new Script(readFileSync(clientPath, 'utf8'), { + filename: fileURLToPath(clientPath), + }) + const bootstrapScripts = artifact.scripts.map( + (source, index) => + new Script(source, { + filename: `solid-hydration-bootstrap-${index}.js`, + }), + ) + let current: Awaited> | undefined + + async function prepare() { + const errors: Array = [] + const virtualConsole = new VirtualConsole() + virtualConsole.on('jsdomError', (error) => errors.push(String(error))) + for (const event of ['error', 'warn'] as const) { + virtualConsole.on(event, (...args) => + errors.push(args.map(String).join(' ')), + ) + } + const dom = new JSDOM(artifact.html, { + url: `http://localhost${clientUrl}`, + runScripts: 'outside-only', + virtualConsole, + }) + const immediates = new Set() + try { + Object.assign(dom.window, { + TextEncoder, + TextDecoder, + ReadableStream, + WritableStream, + TransformStream, + setImmediate( + callback: (...args: Array) => void, + ...args: Array + ) { + const handle = setImmediate(() => { + immediates.delete(handle) + callback(...args) + }) + immediates.add(handle) + return handle + }, + clearImmediate(handle: NodeJS.Immediate) { + immediates.delete(handle) + clearImmediate(handle) + }, + fetch() { + throw new Error('Hydration attempted a network request') + }, + scrollTo() {}, + }) + dom.window.addEventListener('unhandledrejection', (event) => { + errors.push(String(event.reason)) + }) + dom.window.HTMLElement.prototype.scrollIntoView = () => {} + const context = dom.getInternalVMContext() + clientScript.runInContext(context) + const app = (dom.window as unknown as { HydrationBenchmark: ClientApp }) + .HydrationBenchmark + assert.equal(app.serverEnvironment, false) + assert.equal(app.solidServerEnvironment, false) + const doc = dom.window.document + const anchors = Array.from(doc.querySelectorAll('a')) + const scriptElements = Array.from(doc.querySelectorAll('script')) + assert.equal(scriptElements.length, bootstrapScripts.length) + const executingScript = { current: null as HTMLScriptElement | null } + Object.defineProperty(doc, 'currentScript', { + configurable: true, + get: () => executingScript.current, + }) + assert.equal(anchors.length, ordinaryLinkCount + hashLinkCount) + const content = doc.getElementById('hydration-content') + assert.ok(content) + assert.ok(content.hasAttribute('data-hk')) + assert.ok(anchors.every((anchor) => anchor.hasAttribute('data-hk'))) + for (let index = 0; index < hashLinkCount; index++) { + assert.equal( + doc.getElementById(`hash-${index}`)?.getAttribute('data-status'), + null, + ) + } + // Production Solid can fall back to templates for missing hydration keys. + // Retain every workload element, not only the parent and the anchors. + const elements = Array.from(content.querySelectorAll('*')) + const documentElement = doc.documentElement + await turn() + assert.equal(doc.readyState, 'complete') + assert.equal(app.ready(), false) + assert.deepEqual(errors, []) + return { + dom, + context, + app, + anchors, + content, + elements, + documentElement, + scriptElements, + executingScript, + immediates, + errors, + started: false, + completed: false, + failed: false, + } + } catch (error) { + for (const handle of immediates) { + clearImmediate(handle) + } + dom.window.close() + throw error + } + } + + async function before() { + if (current) { + throw new Error('Previous hydration sample was not disposed') + } + current = await prepare() + } + + async function run() { + const sample = current + if (!sample || sample.started) { + throw new Error('Hydration requires a newly prepared sample') + } + sample.started = true + try { + // Parsing/evaluation are done. Execute both native Solid bootstrap and + // Router payload, then create/restore the router and hydrate the DOM. + for (let index = 0; index < bootstrapScripts.length; index++) { + // Router scripts remove document.currentScript. Keep the original + // script nodes and order, including Solid's bootstrap and markers. + sample.executingScript.current = sample.scriptElements[index]! + try { + bootstrapScripts[index]!.runInContext(sample.context) + } finally { + sample.executingScript.current = null + } + } + await sample.app.start(countUpdates) + let idleTurns = 0 + for (let index = 0; index < maxSettleTurns; index++) { + await turn() + if (sample.errors.length) { + throw new Error(sample.errors.join('\n')) + } + if (sample.app.ready() && sample.immediates.size === 0) { + if (++idleTurns === 2) { + sample.completed = true + return + } + } else { + idleTurns = 0 + } + } + throw new Error( + `Hydration did not settle: ${JSON.stringify(sample.app.snapshot())}`, + ) + } catch (error) { + sample.failed = true + throw error + } + } + + function snapshot() { + if (!current) { + throw new Error('No hydration sample') + } + // Normalize realm prototypes only for untimed assertions. + return JSON.parse(JSON.stringify(current.app.snapshot())) as ReturnType< + ClientApp['snapshot'] + > + } + + function validate() { + assert.ok(current?.started) + const { dom, anchors, content, elements, documentElement, errors } = current + const doc = dom.window.document + const result = snapshot() + assert.deepEqual(errors, []) + assert.equal(result.diagnostics.beforeLoads, 0) + assert.equal(result.diagnostics.loaders, 0) + assert.equal(result.diagnostics.mounted, true) + assert.ok(result.diagnostics.rendered > 0) + assert.equal(result.hydrating, false) + assert.equal(result.location, clientUrl) + assert.equal(result.resolvedLocation, clientUrl) + assert.equal(result.matches?.length, 3) + for (const match of result.matches) { + assert.equal(match.status, 'success') + assert.deepEqual(match.context.viewer, { + id: 'viewer-3', + name: 'Ada', + role: 'editor', + }) + } + const teamContext = { id: 'team-7', member: 'viewer-3' } + assert.deepEqual(result.matches[1]!.context.team, teamContext) + assert.deepEqual(result.matches[2]!.context.team, teamContext) + assert.deepEqual(result.matches[2]!.context.permissions, { edit: true }) + assert.deepEqual(result.matches[1]!.loaderData, { + title: 'Team team-7', + categories: ['open', 'closed'], + }) + const data = result.matches[2]!.loaderData as { + owner: string + selected: string + rows: Array<{ + id: string + label: string + details: { score: number; open: boolean } + }> + } + assert.equal(data.owner, 'viewer-3') + assert.equal(data.selected, 'item-42') + assert.equal(data.rows.length, ordinaryLinkCount) + assert.equal(doc.documentElement, documentElement) + assert.equal(doc.getElementById('hydration-content'), content) + const hydratedElements = Array.from(content.querySelectorAll('*')) + assert.equal(hydratedElements.length, elements.length) + elements.forEach((element, index) => { + assert.equal(hydratedElements[index], element) + }) + assert.equal(doc.querySelectorAll('a').length, anchors.length) + assert.equal(doc.title, 'Hydration benchmark') + assert.equal(content.querySelector('h1')?.textContent, 'Team team-7') + assert.equal(doc.getElementById('viewer')?.textContent, 'Ada') + assert.equal(doc.getElementById('permission')?.textContent, 'Editable') + for (const anchor of anchors) { + assert.equal(doc.getElementById(anchor.id), anchor) + } + for (let index = 0; index < ordinaryLinkCount; index++) { + const anchor = doc.getElementById(`ordinary-item-${index}`)! + assert.equal( + anchor.getAttribute('href'), + `/teams/team-7/items/item-${index}?view=summary`, + ) + assert.equal(anchor.textContent, `Item ${index}`) + assert.equal( + anchor.getAttribute('data-status'), + index === 42 ? 'active' : null, + ) + assert.deepEqual(data.rows[index], { + id: `item-${index}`, + label: `Item ${index}`, + details: { score: index * 3, open: index % 2 === 0 }, + }) + } + for (let index = 0; index < hashLinkCount; index++) { + const anchor = doc.getElementById(`hash-${index}`)! + assert.equal( + anchor.getAttribute('data-status'), + index % 2 === 0 ? 'active' : null, + ) + assert.equal( + anchor.getAttribute('href'), + `/teams/team-7/items/item-42?view=summary#${index % 2 === 0 ? 'details' : 'other'}`, + ) + assert.equal(anchor.textContent, `Section ${index}`) + } + assert.equal(result.diagnostics.clicks, 0) + doc + .getElementById('interactive')! + .dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true })) + assert.equal(current.app.snapshot().diagnostics.clicks, 1) + assert.deepEqual(errors, []) + } + + async function after() { + const sample = current + if (!sample) { + return + } + try { + if (!sample.failed) { + assert.ok(sample.completed, 'Hydration sample was not completed') + validate() + } + } finally { + current = undefined + try { + sample.app.dispose() + await turn() + await turn() + if (!sample.failed) { + assert.deepEqual(sample.errors, []) + } + } finally { + for (const handle of sample.immediates) { + clearImmediate(handle) + } + sample.dom.window.close() + } + } + } + + return { + before, + run, + after, + snapshot, + } +} diff --git a/benchmarks/client-nav/scenarios/hydration/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/hydration/solid/speed.bench.ts new file mode 100644 index 0000000000..b386cb8215 --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { setup } from './setup' + +test('client-hydration', async ({ bench }) => { + const scenario = setup() + + await bench( + 'hydrate restored route state and mixed Links (solid)', + { beforeEach: scenario.before, afterEach: scenario.after }, + async () => { + await scenario.run() + }, + ).run({ + time: 5000, + warmupTime: 1000, + warmupIterations: 20, + throws: true, + }) +}) diff --git a/benchmarks/client-nav/scenarios/hydration/solid/src/app.tsx b/benchmarks/client-nav/scenarios/hydration/solid/src/app.tsx new file mode 100644 index 0000000000..cb772d6b5b --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/src/app.tsx @@ -0,0 +1,213 @@ +import { For, onMount } from 'solid-js' +import { HydrationScript } from 'solid-js/web' +import { + HeadContent, + Link, + Outlet, + Scripts, + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, +} from '@tanstack/solid-router' +import { + clientUrl, + hashLinkCount, + ordinaryLinkCount, + serverUrl, +} from '../fixture' +import type { JSX } from 'solid-js' +import type { Diagnostics } from '../fixture' + +export function createFixtureRouter(server: boolean, diagnostics: Diagnostics) { + function beforeLoad() { + diagnostics.beforeLoads++ + if (!server) { + throw new Error('Hydration reran beforeLoad instead of restoring context') + } + } + + function loader() { + diagnostics.loaders++ + if (!server) { + throw new Error('Hydration reran a loader instead of restoring data') + } + } + + const root = createRootRoute({ + beforeLoad: () => { + beforeLoad() + return { viewer: { id: 'viewer-3', name: 'Ada', role: 'editor' } } + }, + head: () => ({ + meta: [{ charset: 'utf-8' }, { title: 'Hydration benchmark' }], + }), + shellComponent: Document, + }) + const team = createRoute({ + getParentRoute: () => root, + path: '/teams/$teamId', + beforeLoad: ({ context, params }) => { + beforeLoad() + return { team: { id: params.teamId, member: context.viewer.id } } + }, + loader: ({ context }) => { + loader() + return { + title: `Team ${context.team.id}`, + categories: ['open', 'closed'], + } + }, + component: Team, + }) + const items = createRoute({ + getParentRoute: () => team, + path: 'items/$itemId', + validateSearch: (search: Record) => ({ + view: search.view === 'details' ? 'details' : 'summary', + }), + beforeLoad: ({ context }) => { + beforeLoad() + return { permissions: { edit: context.viewer.role === 'editor' } } + }, + loader: ({ context, params }) => { + loader() + return { + selected: params.itemId, + owner: context.team.member, + rows: Array.from({ length: ordinaryLinkCount }, (_, index) => ({ + id: `item-${index}`, + label: `Item ${index}`, + details: { score: index * 3, open: index % 2 === 0 }, + })), + } + }, + component: Items, + }) + + function Document(props: { children: JSX.Element }) { + return ( + + + + + + + {props.children} + + + + ) + } + + function Team() { + const context = team.useRouteContext() + const data = team.useLoaderData() + return ( +
+

{data().title}

+

{context().viewer.name}

+ +
+ ) + } + + function Items() { + const data = items.useLoaderData() + const context = items.useRouteContext() + onMount(() => { + diagnostics.mounted = true + }) + return ( + <> +

+ {context().permissions.edit ? 'Editable' : 'Read only'} +

+ + + + + {(row) => ( + + + + + + )} + + +
{row.id}{row.details.score} + + {diagnostics.countUpdates + ? (state) => { + // Read the getter so this unit-only probe observes + // Link reactivity, rather than component execution. + void state.isActive + diagnostics.ordinaryEvaluations++ + return row.label + } + : row.label} + +
+ +
Details
+ + ) + } + + return createRouter({ + routeTree: root.addChildren([team.addChildren([items])]), + history: createMemoryHistory({ + initialEntries: [server ? serverUrl : clientUrl], + }), + isServer: server, + scrollRestoration: false, + defaultHashScrollIntoView: false, + defaultPreload: false, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} diff --git a/benchmarks/client-nav/scenarios/hydration/solid/src/client.tsx b/benchmarks/client-nav/scenarios/hydration/solid/src/client.tsx new file mode 100644 index 0000000000..ef0f5268d6 --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/src/client.tsx @@ -0,0 +1,91 @@ +import { sharedConfig } from 'solid-js' +import { hydrate as hydrateDOM, isServer as solidIsServer } from 'solid-js/web' +import { RouterProvider } from '@tanstack/solid-router' +import { hydrate } from '@tanstack/router-core/ssr/client' +import { isServer } from '@tanstack/router-core/isServer' +import { createDiagnostics, hashLinkCount } from '../fixture' +import { createFixtureRouter } from './app' + +export const serverEnvironment = isServer +export const solidServerEnvironment = solidIsServer +let router: ReturnType | undefined +let disposeRoot: (() => void) | undefined +let unsubscribe: (() => void) | undefined +let diagnostics = createDiagnostics() + +type HydrationWindow = Window & { + _$HY?: { done?: boolean; events?: Array; r: object } +} + +export async function start(countUpdates = false) { + if (router) { + throw new Error('A hydration sample must use a fresh client realm') + } + if (!window.$_TSR?.router) { + throw new Error('Missing SSR hydration payload') + } + const bootstrap = (window as HydrationWindow)._$HY + if (!bootstrap || bootstrap.done || sharedConfig.context) { + throw new Error('Missing or already consumed Solid hydration bootstrap') + } + diagnostics = createDiagnostics(countUpdates) + router = createFixtureRouter(false, diagnostics) + unsubscribe = router.subscribe('onRendered', () => { + diagnostics.rendered++ + }) + // Solid's RouterClient uses this core restoration API. Await it directly so + // the shell has the same component/key hierarchy as the server provider. + await hydrate(router) + window.$_TSR.h() + disposeRoot = hydrateDOM(() => , document) +} + +export function ready() { + if ( + !diagnostics.mounted || + !diagnostics.rendered || + sharedConfig.context || + router?.stores.status.get() === 'pending' + ) { + return false + } + // Each Link's onMount updates its hydration signal. Solid updates attributes + // through fine-grained effects, without rerendering the route components. + for (let index = 0; index < hashLinkCount; index++) { + const anchor = document.getElementById(`hash-${index}`) + if ( + !anchor || + anchor.getAttribute('data-status') !== (index % 2 === 0 ? 'active' : null) + ) { + return false + } + } + return true +} + +export function snapshot() { + return { + diagnostics: { + ...diagnostics, + initialHashStates: [...diagnostics.initialHashStates], + hashStates: [...diagnostics.hashStates], + }, + hydrating: !!sharedConfig.context, + location: router?.stores.location.get().href, + resolvedLocation: router?.stores.resolvedLocation.get()?.href, + matches: router?.stores.matches.get().map((match) => ({ + status: match.status, + context: match.context, + loaderData: match.loaderData, + })), + } +} + +export function dispose() { + try { + disposeRoot?.() + } finally { + unsubscribe?.() + router?.history.destroy() + } +} diff --git a/benchmarks/client-nav/scenarios/hydration/solid/src/server.tsx b/benchmarks/client-nav/scenarios/hydration/solid/src/server.tsx new file mode 100644 index 0000000000..6052c48eac --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/src/server.tsx @@ -0,0 +1,40 @@ +import { RouterProvider } from '@tanstack/solid-router' +import { + createRequestHandler, + renderRouterToStream, +} from '@tanstack/solid-router/ssr/server' +import { isServer } from '@tanstack/router-core/isServer' +import { isServer as solidIsServer } from 'solid-js/web' +import { createDiagnostics, serverUrl } from '../fixture' +import { createFixtureRouter } from './app' + +export async function renderFixture() { + if ((isServer as boolean | undefined) !== true || !solidIsServer) { + throw new Error('Fixture generation requires the production server build') + } + const diagnostics = createDiagnostics() + const response = await createRequestHandler({ + createRouter: () => createFixtureRouter(true, diagnostics), + request: new Request(`http://localhost${serverUrl}`), + })(({ request, router, responseHeaders }) => + renderRouterToStream({ + request, + router, + responseHeaders, + // The route shell owns the document, as in Solid Start. Using the same + // provider tree on both sides preserves Solid's hydration key sequence. + children: () => , + }), + ) + const html = await response.text() + if ( + response.status !== 200 || + diagnostics.beforeLoads !== 3 || + diagnostics.loaders !== 2 + ) { + throw new Error( + 'SSR fixture did not execute its beforeLoad and loader functions', + ) + } + return html +} diff --git a/benchmarks/client-nav/scenarios/hydration/solid/tsconfig.json b/benchmarks/client-nav/scenarios/hydration/solid/tsconfig.json new file mode 100644 index 0000000000..daf27ddf12 --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": ["./*.ts", "./src/**/*"] +} diff --git a/benchmarks/client-nav/scenarios/hydration/solid/vite.config.ts b/benchmarks/client-nav/scenarios/hydration/solid/vite.config.ts new file mode 100644 index 0000000000..16e5ff95aa --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/vite.config.ts @@ -0,0 +1,38 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import solid from 'vite-plugin-solid' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +export default defineConfig({ + root: fileURLToPath(new URL('.', import.meta.url)), + define: { 'process.env.NODE_ENV': JSON.stringify('production') }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + // The Node worker evaluates the prebuilt bundle and needs no JSX transform + // or browser test setup injected by vite-plugin-solid. + !process.env.VITEST && solid({ ssr: true, hot: false, dev: false }), + ], + resolve: { conditions: ['solid', 'browser', 'production'] }, + build: { + outDir: './dist/client', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/client.tsx', + name: 'HydrationBenchmark', + formats: ['iife'], + fileName: () => 'client.js', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav hydration (solid)', + watch: false, + environment: 'node', + isolate: true, + include: ['hydration.test.ts'], + benchmark: { include: ['speed.bench.ts'] }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/hydration/solid/vite.server.config.ts b/benchmarks/client-nav/scenarios/hydration/solid/vite.server.config.ts new file mode 100644 index 0000000000..9787cbb4e2 --- /dev/null +++ b/benchmarks/client-nav/scenarios/hydration/solid/vite.server.config.ts @@ -0,0 +1,29 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vite' +import solid from 'vite-plugin-solid' + +export default defineConfig({ + root: fileURLToPath(new URL('.', import.meta.url)), + define: { 'process.env.NODE_ENV': JSON.stringify('production') }, + plugins: [solid({ ssr: true, hot: false, dev: false })], + resolve: { conditions: ['solid', 'node', 'production'] }, + ssr: { + noExternal: true, + resolve: { conditions: ['solid', 'node', 'production'] }, + }, + build: { + ssr: true, + outDir: './dist/server', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/server.tsx', + formats: ['es'], + fileName: () => 'server.js', + }, + rolldownOptions: { + platform: 'node', + external: [/^node:/], + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/link-churn/react/project.json b/benchmarks/client-nav/scenarios/link-churn/react/project.json new file mode 100644 index 0000000000..1606b2c456 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-link-churn-react", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/react-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/link-churn/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/link-churn/react/setup.ts b/benchmarks/client-nav/scenarios/link-churn/react/setup.ts new file mode 100644 index 0000000000..59221603da --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/setup.ts @@ -0,0 +1,18 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, initialUrl, scenarioSteps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'React', + mount: mountTestApp, + steps: scenarioSteps, + assertAfterStep: assertStepResult, + initialUrl, + }) +} diff --git a/benchmarks/client-nav/scenarios/link-churn/react/speed.bench.ts b/benchmarks/client-nav/scenarios/link-churn/react/speed.bench.ts new file mode 100644 index 0000000000..ca0b370528 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-link-churn', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-link-churn navigation loop (react)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/link-churn/react/speed.flame.ts b/benchmarks/client-nav/scenarios/link-churn/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/link-churn/react/src/main.tsx b/benchmarks/client-nav/scenarios/link-churn/react/src/main.tsx new file mode 100644 index 0000000000..5febd6f795 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/src/main.tsx @@ -0,0 +1,37 @@ +import type { RouterHistory } from '@tanstack/history' +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { createRoot } from 'react-dom/client' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const reactRoot = createRoot(container) + reactRoot.render() + + return { + router, + unmount() { + reactRoot.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/link-churn/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/link-churn/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..4535430b61 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/src/routeTree.gen.ts @@ -0,0 +1,121 @@ +/* eslint-disable */ + +// @ts-nocheck + +// 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 HubRouteImport } from './routes/hub' +import { Route as OtherRouteImport } from './routes/other' +import { Route as HubListRouteImport } from './routes/hub.list' +import { Route as HubDetailIdRouteImport } from './routes/hub.detail.$id' + +const HubRoute = HubRouteImport.update({ + id: '/hub', + path: '/hub', + getParentRoute: () => rootRouteImport, +} as any) +const OtherRoute = OtherRouteImport.update({ + id: '/other', + path: '/other', + getParentRoute: () => rootRouteImport, +} as any) +const HubListRoute = HubListRouteImport.update({ + id: '/list', + path: '/list', + getParentRoute: () => HubRoute, +} as any) +const HubDetailIdRoute = HubDetailIdRouteImport.update({ + id: '/detail/$id', + path: '/detail/$id', + getParentRoute: () => HubRoute, +} as any) + +export interface FileRoutesByFullPath { + '/hub': typeof HubRouteWithChildren + '/other': typeof OtherRoute + '/hub/list': typeof HubListRoute + '/hub/detail/$id': typeof HubDetailIdRoute +} +export interface FileRoutesByTo { + '/hub': typeof HubRouteWithChildren + '/other': typeof OtherRoute + '/hub/list': typeof HubListRoute + '/hub/detail/$id': typeof HubDetailIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/hub': typeof HubRouteWithChildren + '/other': typeof OtherRoute + '/hub/list': typeof HubListRoute + '/hub/detail/$id': typeof HubDetailIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/hub' | '/other' | '/hub/list' | '/hub/detail/$id' + fileRoutesByTo: FileRoutesByTo + to: '/hub' | '/other' | '/hub/list' | '/hub/detail/$id' + id: '__root__' | '/hub' | '/other' | '/hub/list' | '/hub/detail/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + HubRoute: typeof HubRouteWithChildren + OtherRoute: typeof OtherRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/hub': { + id: '/hub' + path: '/hub' + fullPath: '/hub' + preLoaderRoute: typeof HubRouteImport + parentRoute: typeof rootRouteImport + } + '/other': { + id: '/other' + path: '/other' + fullPath: '/other' + preLoaderRoute: typeof OtherRouteImport + parentRoute: typeof rootRouteImport + } + '/hub/list': { + id: '/hub/list' + path: '/list' + fullPath: '/hub/list' + preLoaderRoute: typeof HubListRouteImport + parentRoute: typeof HubRoute + } + '/hub/detail/$id': { + id: '/hub/detail/$id' + path: '/detail/$id' + fullPath: '/hub/detail/$id' + preLoaderRoute: typeof HubDetailIdRouteImport + parentRoute: typeof HubRoute + } + } +} + +interface HubRouteChildren { + HubListRoute: typeof HubListRoute + HubDetailIdRoute: typeof HubDetailIdRoute +} + +const HubRouteChildren: HubRouteChildren = { + HubListRoute: HubListRoute, + HubDetailIdRoute: HubDetailIdRoute, +} + +const HubRouteWithChildren = HubRoute._addFileChildren(HubRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + HubRoute: HubRouteWithChildren, + OtherRoute: OtherRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/link-churn/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/link-churn/react/src/routes/__root.tsx new file mode 100644 index 0000000000..199cf1ff73 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/src/routes/__root.tsx @@ -0,0 +1,39 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/react-router' +import { sortedSearch } from '../../../shared' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.detail.$id.tsx b/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.detail.$id.tsx new file mode 100644 index 0000000000..143cb39a7a --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.detail.$id.tsx @@ -0,0 +1,21 @@ +import { Link, createFileRoute } from '@tanstack/react-router' +import { detailMarker } from '../../../shared' + +export const Route = createFileRoute('/hub/detail/$id')({ + component: DetailPage, +}) + +function DetailPage() { + const params = Route.useParams() + + return ( +
+

{detailMarker(params.id)}

+ Back to list + + Next + + Elsewhere +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.list.tsx b/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.list.tsx new file mode 100644 index 0000000000..5aa37b20a7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.list.tsx @@ -0,0 +1,65 @@ +import { Link, createFileRoute } from '@tanstack/react-router' +import { + listItemIds, + listMarker, + listRelativeTestId, + listSortedMarker, +} from '../../../shared' + +export const Route = createFileRoute('/hub/list')({ + component: ListPage, +}) + +const ascSearch = { sort: 'asc' } as const + +// List Links depart whenever the list leaf is left. +function ListLinks() { + return ( +
    + {listItemIds.map((id) => { + const page = Number(id) + return ( +
  • + + {`Item ${id}`} + + + {`Item ${id} asc`} + + + {`Item ${id} exact`} + + ({ ...prev, page })}> + {`Page ${id}`} + + ({ ...prev, page, sort: 'asc' as const })} + data-testid={id === '1' ? listRelativeTestId : undefined} + > + {`Page ${id} asc`} + +
  • + ) + })} +
+ ) +} + +function ListPage() { + const sort = Route.useSearch({ select: (search) => search.sort }) + + return ( +
+

+ {sort === 'desc' ? listSortedMarker : listMarker} +

+ +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.tsx b/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.tsx new file mode 100644 index 0000000000..ac12eae2da --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.tsx @@ -0,0 +1,64 @@ +import { Link, Outlet, createFileRoute } from '@tanstack/react-router' +import { + hubItemIds, + hubRelativeTestId, + validateHubSearch, +} from '../../../shared' + +export const Route = createFileRoute('/hub')({ + validateSearch: validateHubSearch, + component: HubLayout, +}) + +// Layout Links stay mounted while the hub leaves change. +function HubLinks() { + return ( +
+ {hubItemIds.map((id) => { + const page = Number(id) + return ( +
+ + {`Detail ${id}`} + + + {`Detail ${id} exact`} + + + {`List page ${id}`} + + ({ ...prev, page })}> + {`List keep ${id}`} + + ({ ...prev, page })} + data-testid={id === '1' ? hubRelativeTestId : undefined} + > + {`Here page ${id}`} + +
+ ) + })} +
+ ) +} + +function HubLayout() { + return ( +
+ + +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/link-churn/react/src/routes/other.tsx b/benchmarks/client-nav/scenarios/link-churn/react/src/routes/other.tsx new file mode 100644 index 0000000000..1f146b789f --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/src/routes/other.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/react-router' +import { otherMarker } from '../../../shared' + +export const Route = createFileRoute('/other')({ + component: OtherPage, +}) + +function OtherPage() { + return ( +
+

{otherMarker}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/link-churn/react/tsconfig.json b/benchmarks/client-nav/scenarios/link-churn/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "jsxImportSource": "react", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/link-churn/react/vite.config.ts b/benchmarks/client-nav/scenarios/link-churn/react/vite.config.ts new file mode 100644 index 0000000000..344974ebf9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/react/vite.config.ts @@ -0,0 +1,42 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import react from '@vitejs/plugin-react' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'react', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + react(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav link-churn (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/link-churn/shared.ts b/benchmarks/client-nav/scenarios/link-churn/shared.ts new file mode 100644 index 0000000000..d936af35cc --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/shared.ts @@ -0,0 +1,178 @@ +/** + * Shared definition of the `link-churn` scenario: Links that leave, stay and + * arrive across navigations. A `/hub` layout renders Links that stay mounted + * while its leaves change; the `/hub/list` leaf renders Links that depart when + * leaving it and mount again when returning; `/other` sits outside the layout + * so leaving the list there unmounts layout and leaf Links together. The + * existing `links` scenario keeps all its Links in the root layout, so none of + * them ever departs or remounts. The three framework apps consume these + * constants so the workload is identical modulo the rendering layer. + */ +import type { ScenarioStep } from '../harness' + +// Layout (staying) Links: HUB_ITEM_COUNT ids x 5 variants. +export const HUB_ITEM_COUNT = 6 +// List leaf (departing) Links: LIST_ITEM_COUNT ids x 5 variants. +export const LIST_ITEM_COUNT = 20 + +const ids = (count: number) => + Array.from({ length: count }, (_, index) => String(index + 1)) + +export const hubItemIds = ids(HUB_ITEM_COUNT) +export const listItemIds = ids(LIST_ITEM_COUNT) + +export interface HubSearch { + page?: number + sort?: 'asc' | 'desc' +} + +/** Search validation of the `/hub` layout, inherited by its leaves. */ +export function validateHubSearch(search: Record): HubSearch { + const result: HubSearch = {} + if (typeof search.page === 'number') { + result.page = search.page + } + if (search.sort === 'asc' || search.sort === 'desc') { + result.sort = search.sort + } + return result +} + +export const sortedSearch = { sort: 'desc' } as const + +export function detailMarker(id: string) { + return `detail-${id}` +} + +export const listMarker = 'list' +export const listSortedMarker = 'list-desc' +export const otherMarker = 'other' + +// Sampled Links whose href depends on the current location: the first layout +// `to="."` updater Link and the first list `to="."` updater Link. +export const hubRelativeTestId = 'hub-relative-1' +export const listRelativeTestId = 'list-relative-1' + +interface StepDef { + testId: string + marker: string + /** Expected number of `.active-link` elements after the step. */ + activeCount: number + /** Expected href of the sampled layout updater Link (null: not mounted). */ + hubRelativeHref: string | null + /** Expected href of the sampled list updater Link (null: not mounted). */ + listRelativeHref: string | null +} + +// On the list, every layout `includeSearch: false` Link to the list is active. +const listActiveCount = HUB_ITEM_COUNT + +export const stepDefs: ReadonlyArray = [ + // 1. list -> detail/1: list Links depart, layout Links stay and update. + { + testId: 'go-detail-1', + marker: detailMarker('1'), + activeCount: 1, + hubRelativeHref: '/hub/detail/1?page=1', + listRelativeHref: null, + }, + // 2. detail/1 -> detail/2: same route, new param; every Link stays. + { + testId: 'go-detail-2', + marker: detailMarker('2'), + activeCount: 1, + hubRelativeHref: '/hub/detail/2?page=1', + listRelativeHref: null, + }, + // 3. detail/2 -> list: list Links mount. + { + testId: 'go-list', + marker: listMarker, + activeCount: listActiveCount, + hubRelativeHref: '/hub/list?page=1', + listRelativeHref: '/hub/list?page=1&sort=asc', + }, + // 4. list -> other: layout and list Links depart together. + { + testId: 'go-other', + marker: otherMarker, + activeCount: 0, + hubRelativeHref: null, + listRelativeHref: null, + }, + // 5. other -> list: layout and list Links all mount. + { + testId: 'go-list', + marker: listMarker, + activeCount: listActiveCount, + hubRelativeHref: '/hub/list?page=1', + listRelativeHref: '/hub/list?page=1&sort=asc', + }, + // 6a. list -> list?sort=desc: nothing departs, updater Links rebuild. + { + testId: 'go-list-sorted', + marker: listSortedMarker, + activeCount: listActiveCount, + hubRelativeHref: '/hub/list?sort=desc&page=1', + listRelativeHref: '/hub/list?sort=asc&page=1', + }, + // 6b. back to the plain list so the lap ends on the initial location. + { + testId: 'go-list', + marker: listMarker, + activeCount: listActiveCount, + hubRelativeHref: '/hub/list?page=1', + listRelativeHref: '/hub/list?page=1&sort=asc', + }, +] + +export const initialUrl = '/hub/list' + +export const scenarioSteps: ReadonlyArray = stepDefs.map( + (step) => step.testId, +) + +function assertHref( + container: HTMLElement, + testId: string, + expected: string | null, + stepIndex: number, +) { + const link = container.querySelector(`[data-testid="${testId}"]`) + const href = link ? link.getAttribute('href') : null + if (href !== expected) { + throw new Error( + `Expected "${testId}" href ${JSON.stringify(expected)} after step ${stepIndex}, received ${JSON.stringify(href)}`, + ) + } +} + +export function assertStepResult(stepIndex: number, container: HTMLElement) { + const step = stepDefs[stepIndex]! + + const marker = container.querySelector('[data-testid="page-state"]') + if (marker?.textContent !== step.marker) { + throw new Error( + `Expected page marker "${step.marker}" after step ${stepIndex}, received "${marker?.textContent}"`, + ) + } + + const activeLinks = container.querySelectorAll('a.active-link') + if (activeLinks.length !== step.activeCount) { + throw new Error( + `Expected ${step.activeCount} active link(s) after step ${stepIndex}, received ${activeLinks.length}`, + ) + } + + assertHref(container, hubRelativeTestId, step.hubRelativeHref, stepIndex) + assertHref(container, listRelativeTestId, step.listRelativeHref, stepIndex) +} + +// One lap through the 7-step sequence per benchmark iteration. +export const ticksPerIteration = stepDefs.length + +export const benchOptions = { + warmupIterations: 50, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/project.json b/benchmarks/client-nav/scenarios/link-churn/solid/project.json new file mode 100644 index 0000000000..4e46143b32 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-link-churn-solid", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/solid-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/link-churn/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/setup.ts b/benchmarks/client-nav/scenarios/link-churn/solid/setup.ts new file mode 100644 index 0000000000..a2a024341d --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/setup.ts @@ -0,0 +1,18 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, initialUrl, scenarioSteps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Solid', + mount: mountTestApp, + steps: scenarioSteps, + assertAfterStep: assertStepResult, + initialUrl, + }) +} diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/link-churn/solid/speed.bench.ts new file mode 100644 index 0000000000..80c4aaa6fd --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-link-churn', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-link-churn navigation loop (solid)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/link-churn/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/src/main.tsx b/benchmarks/client-nav/scenarios/link-churn/solid/src/main.tsx new file mode 100644 index 0000000000..fa9d239418 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/src/main.tsx @@ -0,0 +1,34 @@ +import type { RouterHistory } from '@tanstack/history' +import { render } from 'solid-js/web' +import { RouterProvider, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const unmount = render(() => , container) + + return { + router, + unmount, + } +} diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/link-churn/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..e3cb546963 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/src/routeTree.gen.ts @@ -0,0 +1,121 @@ +/* eslint-disable */ + +// @ts-nocheck + +// 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 HubRouteImport } from './routes/hub' +import { Route as OtherRouteImport } from './routes/other' +import { Route as HubListRouteImport } from './routes/hub.list' +import { Route as HubDetailIdRouteImport } from './routes/hub.detail.$id' + +const HubRoute = HubRouteImport.update({ + id: '/hub', + path: '/hub', + getParentRoute: () => rootRouteImport, +} as any) +const OtherRoute = OtherRouteImport.update({ + id: '/other', + path: '/other', + getParentRoute: () => rootRouteImport, +} as any) +const HubListRoute = HubListRouteImport.update({ + id: '/list', + path: '/list', + getParentRoute: () => HubRoute, +} as any) +const HubDetailIdRoute = HubDetailIdRouteImport.update({ + id: '/detail/$id', + path: '/detail/$id', + getParentRoute: () => HubRoute, +} as any) + +export interface FileRoutesByFullPath { + '/hub': typeof HubRouteWithChildren + '/other': typeof OtherRoute + '/hub/list': typeof HubListRoute + '/hub/detail/$id': typeof HubDetailIdRoute +} +export interface FileRoutesByTo { + '/hub': typeof HubRouteWithChildren + '/other': typeof OtherRoute + '/hub/list': typeof HubListRoute + '/hub/detail/$id': typeof HubDetailIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/hub': typeof HubRouteWithChildren + '/other': typeof OtherRoute + '/hub/list': typeof HubListRoute + '/hub/detail/$id': typeof HubDetailIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/hub' | '/other' | '/hub/list' | '/hub/detail/$id' + fileRoutesByTo: FileRoutesByTo + to: '/hub' | '/other' | '/hub/list' | '/hub/detail/$id' + id: '__root__' | '/hub' | '/other' | '/hub/list' | '/hub/detail/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + HubRoute: typeof HubRouteWithChildren + OtherRoute: typeof OtherRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/hub': { + id: '/hub' + path: '/hub' + fullPath: '/hub' + preLoaderRoute: typeof HubRouteImport + parentRoute: typeof rootRouteImport + } + '/other': { + id: '/other' + path: '/other' + fullPath: '/other' + preLoaderRoute: typeof OtherRouteImport + parentRoute: typeof rootRouteImport + } + '/hub/list': { + id: '/hub/list' + path: '/list' + fullPath: '/hub/list' + preLoaderRoute: typeof HubListRouteImport + parentRoute: typeof HubRoute + } + '/hub/detail/$id': { + id: '/hub/detail/$id' + path: '/detail/$id' + fullPath: '/hub/detail/$id' + preLoaderRoute: typeof HubDetailIdRouteImport + parentRoute: typeof HubRoute + } + } +} + +interface HubRouteChildren { + HubListRoute: typeof HubListRoute + HubDetailIdRoute: typeof HubDetailIdRoute +} + +const HubRouteChildren: HubRouteChildren = { + HubListRoute: HubListRoute, + HubDetailIdRoute: HubDetailIdRoute, +} + +const HubRouteWithChildren = HubRoute._addFileChildren(HubRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + HubRoute: HubRouteWithChildren, + OtherRoute: OtherRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..a9de4ea356 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/__root.tsx @@ -0,0 +1,39 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/solid-router' +import { sortedSearch } from '../../../shared' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.detail.$id.tsx b/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.detail.$id.tsx new file mode 100644 index 0000000000..7aca4a9935 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.detail.$id.tsx @@ -0,0 +1,24 @@ +import { Link, createFileRoute } from '@tanstack/solid-router' +import { detailMarker } from '../../../shared' + +export const Route = createFileRoute('/hub/detail/$id')({ + component: DetailPage, +}) + +function DetailPage() { + const params = Route.useParams() + + return ( +
+

{detailMarker(params().id)}

+ Back to list + + Next + + Elsewhere +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.list.tsx b/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.list.tsx new file mode 100644 index 0000000000..5796a50b02 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.list.tsx @@ -0,0 +1,68 @@ +import { For } from 'solid-js' +import { Link, createFileRoute } from '@tanstack/solid-router' +import { + listItemIds, + listMarker, + listRelativeTestId, + listSortedMarker, +} from '../../../shared' + +export const Route = createFileRoute('/hub/list')({ + component: ListPage, +}) + +const ascSearch = { sort: 'asc' } as const + +// List Links depart whenever the list leaf is left. +function ListLinks() { + return ( +
    + + {(id) => { + const page = Number(id) + return ( +
  • + + {`Item ${id}`} + + + {`Item ${id} asc`} + + + {`Item ${id} exact`} + + ({ ...prev, page })}> + {`Page ${id}`} + + ({ ...prev, page, sort: 'asc' as const })} + data-testid={id === '1' ? listRelativeTestId : undefined} + > + {`Page ${id} asc`} + +
  • + ) + }} +
    +
+ ) +} + +function ListPage() { + const sort = Route.useSearch({ select: (search) => search.sort }) + + return ( +
+

+ {sort() === 'desc' ? listSortedMarker : listMarker} +

+ +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.tsx b/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.tsx new file mode 100644 index 0000000000..4682f85aae --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.tsx @@ -0,0 +1,67 @@ +import { For } from 'solid-js' +import { Link, Outlet, createFileRoute } from '@tanstack/solid-router' +import { + hubItemIds, + hubRelativeTestId, + validateHubSearch, +} from '../../../shared' + +export const Route = createFileRoute('/hub')({ + validateSearch: validateHubSearch, + component: HubLayout, +}) + +// Layout Links stay mounted while the hub leaves change. +function HubLinks() { + return ( +
+ + {(id) => { + const page = Number(id) + return ( +
+ + {`Detail ${id}`} + + + {`Detail ${id} exact`} + + + {`List page ${id}`} + + ({ ...prev, page })}> + {`List keep ${id}`} + + ({ ...prev, page })} + data-testid={id === '1' ? hubRelativeTestId : undefined} + > + {`Here page ${id}`} + +
+ ) + }} +
+
+ ) +} + +function HubLayout() { + return ( +
+ + +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/other.tsx b/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/other.tsx new file mode 100644 index 0000000000..2606089113 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/other.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { otherMarker } from '../../../shared' + +export const Route = createFileRoute('/other')({ + component: OtherPage, +}) + +function OtherPage() { + return ( +
+

{otherMarker}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/tsconfig.json b/benchmarks/client-nav/scenarios/link-churn/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "solid-js", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/link-churn/solid/vite.config.ts b/benchmarks/client-nav/scenarios/link-churn/solid/vite.config.ts new file mode 100644 index 0000000000..37718a2d6a --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/solid/vite.config.ts @@ -0,0 +1,50 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import solid from 'vite-plugin-solid' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'solid', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + solid({ hot: false, dev: false }), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + resolve: { + conditions: ['solid', 'browser'], + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav link-churn (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/project.json b/benchmarks/client-nav/scenarios/link-churn/vue/project.json new file mode 100644 index 0000000000..fb890ddfb8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-link-churn-vue", + "projectType": "application", + "targets": { + "build:client": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "NODE_ENV=production vite build --config {projectRoot}/vite.config.ts" + } + }, + "test:types:client": { + "executor": "nx:run-commands", + "dependsOn": [ + { + "projects": ["@tanstack/vue-router", "@tanstack/router-plugin"], + "target": "build" + } + ], + "options": { + "command": "tsc -p {projectRoot}/tsconfig.json --noEmit" + } + }, + "test:flame": { + "executor": "nx:run-commands", + "cache": false, + "dependsOn": ["build:client"], + "options": { + "command": "NODE_ENV=production flame run --md-format=detailed --delay=none --node-options=\"--stack-size=65500\" ./scenarios/link-churn/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/setup.ts b/benchmarks/client-nav/scenarios/link-churn/vue/setup.ts new file mode 100644 index 0000000000..95cacb9ea8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/setup.ts @@ -0,0 +1,18 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, initialUrl, scenarioSteps } from '../shared' +import type * as App from './src/main' + +const appModulePath = './dist/app.js' +const { mountTestApp } = (await import( + /* @vite-ignore */ appModulePath +)) as typeof App + +export function setup() { + return createScenarioSetup({ + frameworkLabel: 'Vue', + mount: mountTestApp, + steps: scenarioSteps, + assertAfterStep: assertStepResult, + initialUrl, + }) +} diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/link-churn/vue/speed.bench.ts new file mode 100644 index 0000000000..dea511c24c --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/speed.bench.ts @@ -0,0 +1,19 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-link-churn', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-link-churn navigation loop (vue)', + benchLifecycle(scenario), + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }, + ).run(benchOptions) +}) diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/link-churn/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/speed.flame.ts @@ -0,0 +1,18 @@ +import { window } from '../../../jsdom.ts' +import { setup } from './setup.ts' + +const DURATION_MS = 10_000 + +const test = setup() + +try { + await test.before() + + const startedAt = performance.now() + while (performance.now() - startedAt < DURATION_MS) { + await test.tick() + } +} finally { + test.after() + window.close() +} diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/src/main.tsx b/benchmarks/client-nav/scenarios/link-churn/vue/src/main.tsx new file mode 100644 index 0000000000..cae9b54f1d --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/src/main.tsx @@ -0,0 +1,41 @@ +import type { RouterHistory } from '@tanstack/history' +import * as Vue from 'vue' +import { RouterProvider, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + scrollRestoration: true, + // Key the scroll-restoration cache by pathname instead of the default + // random per-entry location key: with push navigations the default mints + // a fresh key per navigation and the module-level cache grows one entry + // per push for the whole run, which is non-stationary. + getScrollRestorationKey: (location) => location.pathname, + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const component = + const app = Vue.createApp({ + render: () => component, + }) + + app.mount(container) + + return { + router, + unmount() { + app.unmount() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/link-churn/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..9327bbc01d --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/src/routeTree.gen.ts @@ -0,0 +1,121 @@ +/* eslint-disable */ + +// @ts-nocheck + +// 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 HubRouteImport } from './routes/hub' +import { Route as OtherRouteImport } from './routes/other' +import { Route as HubListRouteImport } from './routes/hub.list' +import { Route as HubDetailIdRouteImport } from './routes/hub.detail.$id' + +const HubRoute = HubRouteImport.update({ + id: '/hub', + path: '/hub', + getParentRoute: () => rootRouteImport, +} as any) +const OtherRoute = OtherRouteImport.update({ + id: '/other', + path: '/other', + getParentRoute: () => rootRouteImport, +} as any) +const HubListRoute = HubListRouteImport.update({ + id: '/list', + path: '/list', + getParentRoute: () => HubRoute, +} as any) +const HubDetailIdRoute = HubDetailIdRouteImport.update({ + id: '/detail/$id', + path: '/detail/$id', + getParentRoute: () => HubRoute, +} as any) + +export interface FileRoutesByFullPath { + '/hub': typeof HubRouteWithChildren + '/other': typeof OtherRoute + '/hub/list': typeof HubListRoute + '/hub/detail/$id': typeof HubDetailIdRoute +} +export interface FileRoutesByTo { + '/hub': typeof HubRouteWithChildren + '/other': typeof OtherRoute + '/hub/list': typeof HubListRoute + '/hub/detail/$id': typeof HubDetailIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/hub': typeof HubRouteWithChildren + '/other': typeof OtherRoute + '/hub/list': typeof HubListRoute + '/hub/detail/$id': typeof HubDetailIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/hub' | '/other' | '/hub/list' | '/hub/detail/$id' + fileRoutesByTo: FileRoutesByTo + to: '/hub' | '/other' | '/hub/list' | '/hub/detail/$id' + id: '__root__' | '/hub' | '/other' | '/hub/list' | '/hub/detail/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + HubRoute: typeof HubRouteWithChildren + OtherRoute: typeof OtherRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/hub': { + id: '/hub' + path: '/hub' + fullPath: '/hub' + preLoaderRoute: typeof HubRouteImport + parentRoute: typeof rootRouteImport + } + '/other': { + id: '/other' + path: '/other' + fullPath: '/other' + preLoaderRoute: typeof OtherRouteImport + parentRoute: typeof rootRouteImport + } + '/hub/list': { + id: '/hub/list' + path: '/list' + fullPath: '/hub/list' + preLoaderRoute: typeof HubListRouteImport + parentRoute: typeof HubRoute + } + '/hub/detail/$id': { + id: '/hub/detail/$id' + path: '/detail/$id' + fullPath: '/hub/detail/$id' + preLoaderRoute: typeof HubDetailIdRouteImport + parentRoute: typeof HubRoute + } + } +} + +interface HubRouteChildren { + HubListRoute: typeof HubListRoute + HubDetailIdRoute: typeof HubDetailIdRoute +} + +const HubRouteChildren: HubRouteChildren = { + HubListRoute: HubListRoute, + HubDetailIdRoute: HubDetailIdRoute, +} + +const HubRouteWithChildren = HubRoute._addFileChildren(HubRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + HubRoute: HubRouteWithChildren, + OtherRoute: OtherRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..a4f7985c5a --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/__root.tsx @@ -0,0 +1,46 @@ +import * as Vue from 'vue' +import { Link, Outlet, createRootRoute } from '@tanstack/vue-router' +import { sortedSearch } from '../../../shared' + +const RootComponent = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + ) + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.detail.$id.tsx b/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.detail.$id.tsx new file mode 100644 index 0000000000..4701ab44eb --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.detail.$id.tsx @@ -0,0 +1,27 @@ +import * as Vue from 'vue' +import { Link, createFileRoute } from '@tanstack/vue-router' +import { detailMarker } from '../../../shared' + +const DetailPage = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
+

{detailMarker(params.value.id)}

+ Back to list + + Next + + Elsewhere +
+ ) + }, +}) + +export const Route = createFileRoute('/hub/detail/$id')({ + component: DetailPage, +}) diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.list.tsx b/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.list.tsx new file mode 100644 index 0000000000..02abd6db1b --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.list.tsx @@ -0,0 +1,74 @@ +import * as Vue from 'vue' +import { Link, createFileRoute } from '@tanstack/vue-router' +import { + listItemIds, + listMarker, + listRelativeTestId, + listSortedMarker, +} from '../../../shared' + +const ascSearch = { sort: 'asc' } as const + +// List Links depart whenever the list leaf is left. +const ListLinks = Vue.defineComponent({ + setup() { + return () => ( +
    + {listItemIds.map((id) => { + const page = Number(id) + return ( +
  • + + {`Item ${id}`} + + + {`Item ${id} asc`} + + + {`Item ${id} exact`} + + ({ ...prev, page })}> + {`Page ${id}`} + + ({ + ...prev, + page, + sort: 'asc' as const, + })} + data-testid={id === '1' ? listRelativeTestId : undefined} + > + {`Page ${id} asc`} + +
  • + ) + })} +
+ ) + }, +}) + +const ListPage = Vue.defineComponent({ + setup() { + const sort = Route.useSearch({ select: (search) => search.sort }) + + return () => ( +
+

+ {sort.value === 'desc' ? listSortedMarker : listMarker} +

+ +
+ ) + }, +}) + +export const Route = createFileRoute('/hub/list')({ + component: ListPage, +}) diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.tsx b/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.tsx new file mode 100644 index 0000000000..5be17f3350 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.tsx @@ -0,0 +1,69 @@ +import * as Vue from 'vue' +import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' +import { + hubItemIds, + hubRelativeTestId, + validateHubSearch, +} from '../../../shared' + +// Layout Links stay mounted while the hub leaves change. +const HubLinks = Vue.defineComponent({ + setup() { + return () => ( +
+ {hubItemIds.map((id) => { + const page = Number(id) + return ( +
+ + {`Detail ${id}`} + + + {`Detail ${id} exact`} + + + {`List page ${id}`} + + ({ ...prev, page })}> + {`List keep ${id}`} + + ({ ...prev, page })} + data-testid={id === '1' ? hubRelativeTestId : undefined} + > + {`Here page ${id}`} + +
+ ) + })} +
+ ) + }, +}) + +const HubLayout = Vue.defineComponent({ + setup() { + return () => ( +
+ + +
+ ) + }, +}) + +export const Route = createFileRoute('/hub')({ + validateSearch: validateHubSearch, + component: HubLayout, +}) diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/other.tsx b/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/other.tsx new file mode 100644 index 0000000000..08dec586fa --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/other.tsx @@ -0,0 +1,17 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { otherMarker } from '../../../shared' + +const OtherPage = Vue.defineComponent({ + setup() { + return () => ( +
+

{otherMarker}

+
+ ) + }, +}) + +export const Route = createFileRoute('/other')({ + component: OtherPage, +}) diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/tsconfig.json b/benchmarks/client-nav/scenarios/link-churn/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../../../tsconfig.json", + "compilerOptions": { + "jsx": "preserve", + "jsxImportSource": "vue", + "allowImportingTsExtensions": true, + "types": ["node", "vite/client", "vitest/globals"] + }, + "include": [ + "speed.bench.ts", + "speed.flame.ts", + "setup.ts", + "vite.config.ts", + "../shared.ts", + "../../harness.ts", + "../../../setup-helpers.ts", + "../../../jsdom.ts", + "../../../vitest.setup.ts", + "./src/**/*" + ] +} diff --git a/benchmarks/client-nav/scenarios/link-churn/vue/vite.config.ts b/benchmarks/client-nav/scenarios/link-churn/vue/vite.config.ts new file mode 100644 index 0000000000..8f56734e04 --- /dev/null +++ b/benchmarks/client-nav/scenarios/link-churn/vue/vite.config.ts @@ -0,0 +1,44 @@ +import { fileURLToPath } from 'node:url' +import { defineConfig } from 'vitest/config' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' +import codspeedPlugin from '@codspeed/vitest-plugin' +import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' + +const rootDir = fileURLToPath(new URL('.', import.meta.url)) + +export default defineConfig({ + root: rootDir, + define: { + 'process.env.NODE_ENV': JSON.stringify('production'), + }, + plugins: [ + !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && + codspeedPlugin(), + tanstackRouter({ + target: 'vue', + routesDirectory: `${rootDir}src/routes`, + generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, + }), + vue(), + vueJsx(), + ], + build: { + outDir: './dist', + emptyOutDir: true, + minify: false, + lib: { + entry: './src/main.tsx', + formats: ['es'], + fileName: 'app', + }, + }, + test: { + execArgv: cpuSimulationExecArgv(), + name: '@benchmarks/client-nav link-churn (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/links/react/speed.bench.ts b/benchmarks/client-nav/scenarios/links/react/speed.bench.ts index 68bb869182..75f5f725d4 100644 --- a/benchmarks/client-nav/scenarios/links/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/links/react/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-links', () => { - const test = setup() +test('client-links', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-links navigation loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/links/react/src/main.tsx b/benchmarks/client-nav/scenarios/links/react/src/main.tsx index ef0b99555c..5febd6f795 100644 --- a/benchmarks/client-nav/scenarios/links/react/src/main.tsx +++ b/benchmarks/client-nav/scenarios/links/react/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import { RouterProvider, createRouter } from '@tanstack/react-router' import { createRoot } from 'react-dom/client' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -20,8 +22,8 @@ declare module '@tanstack/react-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const reactRoot = createRoot(container) reactRoot.render() diff --git a/benchmarks/client-nav/scenarios/links/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/links/react/src/routeTree.gen.ts index 97ec042c1c..6e0c29ca88 100644 --- a/benchmarks/client-nav/scenarios/links/react/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/links/react/src/routeTree.gen.ts @@ -9,20 +9,20 @@ // 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 AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' import { Route as ItemsIdRouteImport } from './routes/items.$id' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) const ItemsIdRoute = ItemsIdRouteImport.update({ id: '/items/$id', path: '/items/$id', @@ -61,13 +61,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -75,6 +68,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } '/items/$id': { id: '/items/$id' path: '/items/$id' diff --git a/benchmarks/client-nav/scenarios/links/react/vite.config.ts b/benchmarks/client-nav/scenarios/links/react/vite.config.ts index 9e9cd48895..69de10b5b7 100644 --- a/benchmarks/client-nav/scenarios/links/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/links/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import react from '@vitejs/plugin-react' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -32,6 +33,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav links (react)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts index beba86fb6c..fc7f3e71e7 100644 --- a/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-links', () => { - const test = setup() +test('client-links', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-links navigation loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/links/solid/src/main.tsx b/benchmarks/client-nav/scenarios/links/solid/src/main.tsx index 817045bd02..fa9d239418 100644 --- a/benchmarks/client-nav/scenarios/links/solid/src/main.tsx +++ b/benchmarks/client-nav/scenarios/links/solid/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import { render } from 'solid-js/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -20,8 +22,8 @@ declare module '@tanstack/solid-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const unmount = render(() => , container) diff --git a/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts index b61431e40d..0da70513e8 100644 --- a/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts @@ -9,20 +9,20 @@ // 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 AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' import { Route as ItemsIdRouteImport } from './routes/items.$id' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) const ItemsIdRoute = ItemsIdRouteImport.update({ id: '/items/$id', path: '/items/$id', @@ -61,13 +61,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -75,6 +68,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } '/items/$id': { id: '/items/$id' path: '/items/$id' diff --git a/benchmarks/client-nav/scenarios/links/solid/vite.config.ts b/benchmarks/client-nav/scenarios/links/solid/vite.config.ts index 9a5b3d138b..e37342ffc3 100644 --- a/benchmarks/client-nav/scenarios/links/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/links/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import solid from 'vite-plugin-solid' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -35,6 +36,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav links (solid)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts index 54b99d1273..2ace7a8409 100644 --- a/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-links', () => { - const test = setup() +test('client-links', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-links navigation loop (vue)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/links/vue/src/main.tsx b/benchmarks/client-nav/scenarios/links/vue/src/main.tsx index c96d3f3a2e..cae9b54f1d 100644 --- a/benchmarks/client-nav/scenarios/links/vue/src/main.tsx +++ b/benchmarks/client-nav/scenarios/links/vue/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import * as Vue from 'vue' import { RouterProvider, createRouter } from '@tanstack/vue-router' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -20,8 +22,8 @@ declare module '@tanstack/vue-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const component = const app = Vue.createApp({ diff --git a/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts index cee64be43c..7d2b1e9bbb 100644 --- a/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts @@ -9,20 +9,20 @@ // 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 AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' import { Route as ItemsIdRouteImport } from './routes/items.$id' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) const ItemsIdRoute = ItemsIdRouteImport.update({ id: '/items/$id', path: '/items/$id', @@ -61,13 +61,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -75,6 +68,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } '/items/$id': { id: '/items/$id' path: '/items/$id' diff --git a/benchmarks/client-nav/scenarios/links/vue/vite.config.ts b/benchmarks/client-nav/scenarios/links/vue/vite.config.ts index d1cf9f561d..ad89a49d70 100644 --- a/benchmarks/client-nav/scenarios/links/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/links/vue/vite.config.ts @@ -4,6 +4,7 @@ import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -34,6 +35,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav links (vue)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts b/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts index 7c44f1a0f7..8bcc53b88e 100644 --- a/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-loaders', () => { - const test = setup() +test('client-loaders', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-loaders navigation loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/loaders/react/src/main.tsx b/benchmarks/client-nav/scenarios/loaders/react/src/main.tsx index ef0b99555c..5febd6f795 100644 --- a/benchmarks/client-nav/scenarios/loaders/react/src/main.tsx +++ b/benchmarks/client-nav/scenarios/loaders/react/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import { RouterProvider, createRouter } from '@tanstack/react-router' import { createRoot } from 'react-dom/client' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -20,8 +22,8 @@ declare module '@tanstack/react-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const reactRoot = createRoot(container) reactRoot.render() diff --git a/benchmarks/client-nav/scenarios/loaders/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/loaders/react/src/routeTree.gen.ts index 50f0a8863b..35908a225f 100644 --- a/benchmarks/client-nav/scenarios/loaders/react/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/loaders/react/src/routeTree.gen.ts @@ -9,24 +9,19 @@ // 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 DepsRouteImport } from './routes/deps' import { Route as IndexRouteImport } from './routes/index' -import { Route as FreshIdRouteImport } from './routes/fresh.$id' +import { Route as DepsRouteImport } from './routes/deps' import { Route as CachedIdRouteImport } from './routes/cached.$id' +import { Route as FreshIdRouteImport } from './routes/fresh.$id' -const DepsRoute = DepsRouteImport.update({ - id: '/deps', - path: '/deps', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const FreshIdRoute = FreshIdRouteImport.update({ - id: '/fresh/$id', - path: '/fresh/$id', +const DepsRoute = DepsRouteImport.update({ + id: '/deps', + path: '/deps', getParentRoute: () => rootRouteImport, } as any) const CachedIdRoute = CachedIdRouteImport.update({ @@ -34,6 +29,11 @@ const CachedIdRoute = CachedIdRouteImport.update({ path: '/cached/$id', getParentRoute: () => rootRouteImport, } as any) +const FreshIdRoute = FreshIdRouteImport.update({ + id: '/fresh/$id', + path: '/fresh/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -71,13 +71,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/deps': { - id: '/deps' - path: '/deps' - fullPath: '/deps' - preLoaderRoute: typeof DepsRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -85,11 +78,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/fresh/$id': { - id: '/fresh/$id' - path: '/fresh/$id' - fullPath: '/fresh/$id' - preLoaderRoute: typeof FreshIdRouteImport + '/deps': { + id: '/deps' + path: '/deps' + fullPath: '/deps' + preLoaderRoute: typeof DepsRouteImport parentRoute: typeof rootRouteImport } '/cached/$id': { @@ -99,6 +92,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof CachedIdRouteImport parentRoute: typeof rootRouteImport } + '/fresh/$id': { + id: '/fresh/$id' + path: '/fresh/$id' + fullPath: '/fresh/$id' + preLoaderRoute: typeof FreshIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/loaders/react/vite.config.ts b/benchmarks/client-nav/scenarios/loaders/react/vite.config.ts index 6fa28bcd35..818b224130 100644 --- a/benchmarks/client-nav/scenarios/loaders/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/loaders/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import react from '@vitejs/plugin-react' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -32,6 +33,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav loaders (react)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts index 4c97823d11..953a17b31a 100644 --- a/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-loaders', () => { - const test = setup() +test('client-loaders', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-loaders navigation loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/loaders/solid/src/main.tsx b/benchmarks/client-nav/scenarios/loaders/solid/src/main.tsx index 817045bd02..fa9d239418 100644 --- a/benchmarks/client-nav/scenarios/loaders/solid/src/main.tsx +++ b/benchmarks/client-nav/scenarios/loaders/solid/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import { render } from 'solid-js/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -20,8 +22,8 @@ declare module '@tanstack/solid-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const unmount = render(() => , container) diff --git a/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts index bdec400237..fa5d032141 100644 --- a/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts @@ -9,24 +9,19 @@ // 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 DepsRouteImport } from './routes/deps' import { Route as IndexRouteImport } from './routes/index' -import { Route as FreshIdRouteImport } from './routes/fresh.$id' +import { Route as DepsRouteImport } from './routes/deps' import { Route as CachedIdRouteImport } from './routes/cached.$id' +import { Route as FreshIdRouteImport } from './routes/fresh.$id' -const DepsRoute = DepsRouteImport.update({ - id: '/deps', - path: '/deps', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const FreshIdRoute = FreshIdRouteImport.update({ - id: '/fresh/$id', - path: '/fresh/$id', +const DepsRoute = DepsRouteImport.update({ + id: '/deps', + path: '/deps', getParentRoute: () => rootRouteImport, } as any) const CachedIdRoute = CachedIdRouteImport.update({ @@ -34,6 +29,11 @@ const CachedIdRoute = CachedIdRouteImport.update({ path: '/cached/$id', getParentRoute: () => rootRouteImport, } as any) +const FreshIdRoute = FreshIdRouteImport.update({ + id: '/fresh/$id', + path: '/fresh/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -71,13 +71,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/deps': { - id: '/deps' - path: '/deps' - fullPath: '/deps' - preLoaderRoute: typeof DepsRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -85,11 +78,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/fresh/$id': { - id: '/fresh/$id' - path: '/fresh/$id' - fullPath: '/fresh/$id' - preLoaderRoute: typeof FreshIdRouteImport + '/deps': { + id: '/deps' + path: '/deps' + fullPath: '/deps' + preLoaderRoute: typeof DepsRouteImport parentRoute: typeof rootRouteImport } '/cached/$id': { @@ -99,6 +92,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof CachedIdRouteImport parentRoute: typeof rootRouteImport } + '/fresh/$id': { + id: '/fresh/$id' + path: '/fresh/$id' + fullPath: '/fresh/$id' + preLoaderRoute: typeof FreshIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/loaders/solid/vite.config.ts b/benchmarks/client-nav/scenarios/loaders/solid/vite.config.ts index ea913ac578..90584d3b7e 100644 --- a/benchmarks/client-nav/scenarios/loaders/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/loaders/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import solid from 'vite-plugin-solid' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -35,6 +36,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav loaders (solid)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts index eeb9cefaeb..1ae2f89a56 100644 --- a/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-loaders', () => { - const test = setup() +test('client-loaders', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-loaders navigation loop (vue)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/loaders/vue/src/main.tsx b/benchmarks/client-nav/scenarios/loaders/vue/src/main.tsx index c96d3f3a2e..cae9b54f1d 100644 --- a/benchmarks/client-nav/scenarios/loaders/vue/src/main.tsx +++ b/benchmarks/client-nav/scenarios/loaders/vue/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import * as Vue from 'vue' import { RouterProvider, createRouter } from '@tanstack/vue-router' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -20,8 +22,8 @@ declare module '@tanstack/vue-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const component = const app = Vue.createApp({ diff --git a/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts index 25a82df477..10cb8f2aca 100644 --- a/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts @@ -9,24 +9,19 @@ // 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 DepsRouteImport } from './routes/deps' import { Route as IndexRouteImport } from './routes/index' -import { Route as FreshIdRouteImport } from './routes/fresh.$id' +import { Route as DepsRouteImport } from './routes/deps' import { Route as CachedIdRouteImport } from './routes/cached.$id' +import { Route as FreshIdRouteImport } from './routes/fresh.$id' -const DepsRoute = DepsRouteImport.update({ - id: '/deps', - path: '/deps', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const FreshIdRoute = FreshIdRouteImport.update({ - id: '/fresh/$id', - path: '/fresh/$id', +const DepsRoute = DepsRouteImport.update({ + id: '/deps', + path: '/deps', getParentRoute: () => rootRouteImport, } as any) const CachedIdRoute = CachedIdRouteImport.update({ @@ -34,6 +29,11 @@ const CachedIdRoute = CachedIdRouteImport.update({ path: '/cached/$id', getParentRoute: () => rootRouteImport, } as any) +const FreshIdRoute = FreshIdRouteImport.update({ + id: '/fresh/$id', + path: '/fresh/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -71,13 +71,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/deps': { - id: '/deps' - path: '/deps' - fullPath: '/deps' - preLoaderRoute: typeof DepsRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -85,11 +78,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/fresh/$id': { - id: '/fresh/$id' - path: '/fresh/$id' - fullPath: '/fresh/$id' - preLoaderRoute: typeof FreshIdRouteImport + '/deps': { + id: '/deps' + path: '/deps' + fullPath: '/deps' + preLoaderRoute: typeof DepsRouteImport parentRoute: typeof rootRouteImport } '/cached/$id': { @@ -99,6 +92,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof CachedIdRouteImport parentRoute: typeof rootRouteImport } + '/fresh/$id': { + id: '/fresh/$id' + path: '/fresh/$id' + fullPath: '/fresh/$id' + preLoaderRoute: typeof FreshIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/loaders/vue/vite.config.ts b/benchmarks/client-nav/scenarios/loaders/vue/vite.config.ts index 350fadf387..ecf4cce139 100644 --- a/benchmarks/client-nav/scenarios/loaders/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/loaders/vue/vite.config.ts @@ -4,6 +4,7 @@ import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -34,6 +35,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav loaders (vue)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts b/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts index 8f7967c42c..6c3a64b026 100644 --- a/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-mount', () => { - const test = setup() +test('client-mount', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-mount loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/mount/react/src/main.tsx b/benchmarks/client-nav/scenarios/mount/react/src/main.tsx index 78fe2082aa..4e45ed7ef3 100644 --- a/benchmarks/client-nav/scenarios/mount/react/src/main.tsx +++ b/benchmarks/client-nav/scenarios/mount/react/src/main.tsx @@ -1,19 +1,12 @@ -import { - RouterProvider, - createBrowserHistory, - createRouter, -} from '@tanstack/react-router' +import { RouterProvider, createRouter } from '@tanstack/react-router' import { createRoot } from 'react-dom/client' import { routeTree } from './routeTree.gen' -import type { RouterHistory } from '@tanstack/react-router' +import type { RouterHistory } from '@tanstack/history' /** * Unlike the other scenarios, this app is mounted and unmounted in a loop, so * it must not register page-lifetime globals that have no dispose path: - * - the history is created explicitly and `destroy()`ed on unmount — the - * default per-router `createBrowserHistory()` monkey-patches - * `window.history.pushState`/`replaceState`, chaining one wrapper per - * router and degrading every later mount; + * - the harness injects and destroys a fresh memory history per mount; * - `scrollRestoration` stays off — enabling it registers per-router * document/window listeners that retain every router ever created. */ @@ -30,8 +23,7 @@ declare module '@tanstack/react-router' { } } -export function mountTestApp(container: HTMLElement) { - const history = createBrowserHistory() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { const router = createTestRouter(history) const reactRoot = createRoot(container) @@ -41,7 +33,6 @@ export function mountTestApp(container: HTMLElement) { router, unmount() { reactRoot.unmount() - history.destroy() }, } } diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/mount/react/src/routeTree.gen.ts index a796abe0ec..f9b7e5c268 100644 --- a/benchmarks/client-nav/scenarios/mount/react/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/mount/react/src/routeTree.gen.ts @@ -9,35 +9,20 @@ // 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 ShopRouteImport } from './routes/shop' -import { Route as SettingsRouteImport } from './routes/settings' -import { Route as SearchRouteImport } from './routes/search' -import { Route as BlogRouteImport } from './routes/blog' -import { Route as AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' -import { Route as ShopIndexRouteImport } from './routes/shop.index' +import { Route as AboutRouteImport } from './routes/about' +import { Route as BlogRouteImport } from './routes/blog' +import { Route as SearchRouteImport } from './routes/search' +import { Route as SettingsRouteImport } from './routes/settings' +import { Route as ShopRouteImport } from './routes/shop' import { Route as BlogIndexRouteImport } from './routes/blog.index' -import { Route as ShopProductIdRouteImport } from './routes/shop.$productId' import { Route as BlogSlugRouteImport } from './routes/blog.$slug' +import { Route as ShopIndexRouteImport } from './routes/shop.index' +import { Route as ShopProductIdRouteImport } from './routes/shop.$productId' -const ShopRoute = ShopRouteImport.update({ - id: '/shop', - path: '/shop', - getParentRoute: () => rootRouteImport, -} as any) -const SettingsRoute = SettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => rootRouteImport, -} as any) -const SearchRoute = SearchRouteImport.update({ - id: '/search', - path: '/search', - getParentRoute: () => rootRouteImport, -} as any) -const BlogRoute = BlogRouteImport.update({ - id: '/blog', - path: '/blog', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AboutRoute = AboutRouteImport.update({ @@ -45,31 +30,46 @@ const AboutRoute = AboutRouteImport.update({ path: '/about', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const BlogRoute = BlogRouteImport.update({ + id: '/blog', + path: '/blog', getParentRoute: () => rootRouteImport, } as any) -const ShopIndexRoute = ShopIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => ShopRoute, +const SearchRoute = SearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => rootRouteImport, +} as any) +const SettingsRoute = SettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => rootRouteImport, +} as any) +const ShopRoute = ShopRouteImport.update({ + id: '/shop', + path: '/shop', + getParentRoute: () => rootRouteImport, } as any) const BlogIndexRoute = BlogIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => BlogRoute, } as any) -const ShopProductIdRoute = ShopProductIdRouteImport.update({ - id: '/$productId', - path: '/$productId', - getParentRoute: () => ShopRoute, -} as any) const BlogSlugRoute = BlogSlugRouteImport.update({ id: '/$slug', path: '/$slug', getParentRoute: () => BlogRoute, } as any) +const ShopIndexRoute = ShopIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => ShopRoute, +} as any) +const ShopProductIdRoute = ShopProductIdRouteImport.update({ + id: '/$productId', + path: '/$productId', + getParentRoute: () => ShopRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -154,32 +154,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/shop': { - id: '/shop' - path: '/shop' - fullPath: '/shop' - preLoaderRoute: typeof ShopRouteImport - parentRoute: typeof rootRouteImport - } - '/settings': { - id: '/settings' - path: '/settings' - fullPath: '/settings' - preLoaderRoute: typeof SettingsRouteImport - parentRoute: typeof rootRouteImport - } - '/search': { - id: '/search' - path: '/search' - fullPath: '/search' - preLoaderRoute: typeof SearchRouteImport - parentRoute: typeof rootRouteImport - } - '/blog': { - id: '/blog' - path: '/blog' - fullPath: '/blog' - preLoaderRoute: typeof BlogRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/about': { @@ -189,19 +168,33 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/blog': { + id: '/blog' + path: '/blog' + fullPath: '/blog' + preLoaderRoute: typeof BlogRouteImport parentRoute: typeof rootRouteImport } - '/shop/': { - id: '/shop/' - path: '/' - fullPath: '/shop/' - preLoaderRoute: typeof ShopIndexRouteImport - parentRoute: typeof ShopRoute + '/search': { + id: '/search' + path: '/search' + fullPath: '/search' + preLoaderRoute: typeof SearchRouteImport + parentRoute: typeof rootRouteImport + } + '/settings': { + id: '/settings' + path: '/settings' + fullPath: '/settings' + preLoaderRoute: typeof SettingsRouteImport + parentRoute: typeof rootRouteImport + } + '/shop': { + id: '/shop' + path: '/shop' + fullPath: '/shop' + preLoaderRoute: typeof ShopRouteImport + parentRoute: typeof rootRouteImport } '/blog/': { id: '/blog/' @@ -210,13 +203,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof BlogIndexRouteImport parentRoute: typeof BlogRoute } - '/shop/$productId': { - id: '/shop/$productId' - path: '/$productId' - fullPath: '/shop/$productId' - preLoaderRoute: typeof ShopProductIdRouteImport - parentRoute: typeof ShopRoute - } '/blog/$slug': { id: '/blog/$slug' path: '/$slug' @@ -224,6 +210,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof BlogSlugRouteImport parentRoute: typeof BlogRoute } + '/shop/': { + id: '/shop/' + path: '/' + fullPath: '/shop/' + preLoaderRoute: typeof ShopIndexRouteImport + parentRoute: typeof ShopRoute + } + '/shop/$productId': { + id: '/shop/$productId' + path: '/$productId' + fullPath: '/shop/$productId' + preLoaderRoute: typeof ShopProductIdRouteImport + parentRoute: typeof ShopRoute + } } } diff --git a/benchmarks/client-nav/scenarios/mount/react/vite.config.ts b/benchmarks/client-nav/scenarios/mount/react/vite.config.ts index 68ee46738a..e197d33a9e 100644 --- a/benchmarks/client-nav/scenarios/mount/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/mount/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import react from '@vitejs/plugin-react' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -32,6 +33,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav mount (react)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts index 1bce4c6750..236f875f57 100644 --- a/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-mount', () => { - const test = setup() +test('client-mount', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-mount loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/main.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/main.tsx index ae03b145ca..2586872f5c 100644 --- a/benchmarks/client-nav/scenarios/mount/solid/src/main.tsx +++ b/benchmarks/client-nav/scenarios/mount/solid/src/main.tsx @@ -1,19 +1,12 @@ import { render } from 'solid-js/web' -import { - RouterProvider, - createBrowserHistory, - createRouter, -} from '@tanstack/solid-router' +import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' -import type { RouterHistory } from '@tanstack/solid-router' +import type { RouterHistory } from '@tanstack/history' /** * Unlike the other scenarios, this app is mounted and unmounted in a loop, so * it must not register page-lifetime globals that have no dispose path: - * - the history is created explicitly and `destroy()`ed on unmount — the - * default per-router `createBrowserHistory()` monkey-patches - * `window.history.pushState`/`replaceState`, chaining one wrapper per - * router and degrading every later mount; + * - the harness injects and destroys a fresh memory history per mount; * - `scrollRestoration` stays off — enabling it registers per-router * document/window listeners that retain every router ever created. */ @@ -30,8 +23,7 @@ declare module '@tanstack/solid-router' { } } -export function mountTestApp(container: HTMLElement) { - const history = createBrowserHistory() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { const router = createTestRouter(history) const dispose = render(() => , container) @@ -40,7 +32,6 @@ export function mountTestApp(container: HTMLElement) { router, unmount() { dispose() - history.destroy() }, } } diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/mount/solid/src/routeTree.gen.ts index dc0acc183d..30247636dd 100644 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/mount/solid/src/routeTree.gen.ts @@ -9,35 +9,20 @@ // 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 ShopRouteImport } from './routes/shop' -import { Route as SettingsRouteImport } from './routes/settings' -import { Route as SearchRouteImport } from './routes/search' -import { Route as BlogRouteImport } from './routes/blog' -import { Route as AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' -import { Route as ShopIndexRouteImport } from './routes/shop.index' +import { Route as AboutRouteImport } from './routes/about' +import { Route as BlogRouteImport } from './routes/blog' +import { Route as SearchRouteImport } from './routes/search' +import { Route as SettingsRouteImport } from './routes/settings' +import { Route as ShopRouteImport } from './routes/shop' import { Route as BlogIndexRouteImport } from './routes/blog.index' -import { Route as ShopProductIdRouteImport } from './routes/shop.$productId' import { Route as BlogSlugRouteImport } from './routes/blog.$slug' +import { Route as ShopIndexRouteImport } from './routes/shop.index' +import { Route as ShopProductIdRouteImport } from './routes/shop.$productId' -const ShopRoute = ShopRouteImport.update({ - id: '/shop', - path: '/shop', - getParentRoute: () => rootRouteImport, -} as any) -const SettingsRoute = SettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => rootRouteImport, -} as any) -const SearchRoute = SearchRouteImport.update({ - id: '/search', - path: '/search', - getParentRoute: () => rootRouteImport, -} as any) -const BlogRoute = BlogRouteImport.update({ - id: '/blog', - path: '/blog', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AboutRoute = AboutRouteImport.update({ @@ -45,31 +30,46 @@ const AboutRoute = AboutRouteImport.update({ path: '/about', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const BlogRoute = BlogRouteImport.update({ + id: '/blog', + path: '/blog', getParentRoute: () => rootRouteImport, } as any) -const ShopIndexRoute = ShopIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => ShopRoute, +const SearchRoute = SearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => rootRouteImport, +} as any) +const SettingsRoute = SettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => rootRouteImport, +} as any) +const ShopRoute = ShopRouteImport.update({ + id: '/shop', + path: '/shop', + getParentRoute: () => rootRouteImport, } as any) const BlogIndexRoute = BlogIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => BlogRoute, } as any) -const ShopProductIdRoute = ShopProductIdRouteImport.update({ - id: '/$productId', - path: '/$productId', - getParentRoute: () => ShopRoute, -} as any) const BlogSlugRoute = BlogSlugRouteImport.update({ id: '/$slug', path: '/$slug', getParentRoute: () => BlogRoute, } as any) +const ShopIndexRoute = ShopIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => ShopRoute, +} as any) +const ShopProductIdRoute = ShopProductIdRouteImport.update({ + id: '/$productId', + path: '/$productId', + getParentRoute: () => ShopRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -154,32 +154,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/shop': { - id: '/shop' - path: '/shop' - fullPath: '/shop' - preLoaderRoute: typeof ShopRouteImport - parentRoute: typeof rootRouteImport - } - '/settings': { - id: '/settings' - path: '/settings' - fullPath: '/settings' - preLoaderRoute: typeof SettingsRouteImport - parentRoute: typeof rootRouteImport - } - '/search': { - id: '/search' - path: '/search' - fullPath: '/search' - preLoaderRoute: typeof SearchRouteImport - parentRoute: typeof rootRouteImport - } - '/blog': { - id: '/blog' - path: '/blog' - fullPath: '/blog' - preLoaderRoute: typeof BlogRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/about': { @@ -189,19 +168,33 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/blog': { + id: '/blog' + path: '/blog' + fullPath: '/blog' + preLoaderRoute: typeof BlogRouteImport parentRoute: typeof rootRouteImport } - '/shop/': { - id: '/shop/' - path: '/' - fullPath: '/shop/' - preLoaderRoute: typeof ShopIndexRouteImport - parentRoute: typeof ShopRoute + '/search': { + id: '/search' + path: '/search' + fullPath: '/search' + preLoaderRoute: typeof SearchRouteImport + parentRoute: typeof rootRouteImport + } + '/settings': { + id: '/settings' + path: '/settings' + fullPath: '/settings' + preLoaderRoute: typeof SettingsRouteImport + parentRoute: typeof rootRouteImport + } + '/shop': { + id: '/shop' + path: '/shop' + fullPath: '/shop' + preLoaderRoute: typeof ShopRouteImport + parentRoute: typeof rootRouteImport } '/blog/': { id: '/blog/' @@ -210,13 +203,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof BlogIndexRouteImport parentRoute: typeof BlogRoute } - '/shop/$productId': { - id: '/shop/$productId' - path: '/$productId' - fullPath: '/shop/$productId' - preLoaderRoute: typeof ShopProductIdRouteImport - parentRoute: typeof ShopRoute - } '/blog/$slug': { id: '/blog/$slug' path: '/$slug' @@ -224,6 +210,20 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof BlogSlugRouteImport parentRoute: typeof BlogRoute } + '/shop/': { + id: '/shop/' + path: '/' + fullPath: '/shop/' + preLoaderRoute: typeof ShopIndexRouteImport + parentRoute: typeof ShopRoute + } + '/shop/$productId': { + id: '/shop/$productId' + path: '/$productId' + fullPath: '/shop/$productId' + preLoaderRoute: typeof ShopProductIdRouteImport + parentRoute: typeof ShopRoute + } } } diff --git a/benchmarks/client-nav/scenarios/mount/solid/vite.config.ts b/benchmarks/client-nav/scenarios/mount/solid/vite.config.ts index 910d332f9c..5b586dd128 100644 --- a/benchmarks/client-nav/scenarios/mount/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/mount/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import solid from 'vite-plugin-solid' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -35,6 +36,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav mount (solid)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts index d2e4b72c84..d9268ba91b 100644 --- a/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts @@ -1,34 +1,15 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-mount', () => { - const test = setup() +test('client-mount', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( - 'client-mount loop (vue)', - async () => { - for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() - } - }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + await bench('client-mount loop (vue)', benchLifecycle(scenario), async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await scenario.tick() + } + await scenario.finishBatch() + }).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/main.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/main.tsx index 6d238e2832..fc493c10a5 100644 --- a/benchmarks/client-nav/scenarios/mount/vue/src/main.tsx +++ b/benchmarks/client-nav/scenarios/mount/vue/src/main.tsx @@ -1,19 +1,12 @@ import * as Vue from 'vue' -import { - RouterProvider, - createBrowserHistory, - createRouter, -} from '@tanstack/vue-router' +import { RouterProvider, createRouter } from '@tanstack/vue-router' import { routeTree } from './routeTree.gen' -import type { RouterHistory } from '@tanstack/vue-router' +import type { RouterHistory } from '@tanstack/history' /** * Unlike the other scenarios, this app is mounted and unmounted in a loop, so * it must not register page-lifetime globals that have no dispose path: - * - the history is created explicitly and `destroy()`ed on unmount — the - * default per-router `createBrowserHistory()` monkey-patches - * `window.history.pushState`/`replaceState`, chaining one wrapper per - * router and degrading every later mount; + * - the harness injects and destroys a fresh memory history per mount; * - `scrollRestoration` stays off — enabling it registers per-router * document/window listeners that retain every router ever created. */ @@ -30,8 +23,7 @@ declare module '@tanstack/vue-router' { } } -export function mountTestApp(container: HTMLElement) { - const history = createBrowserHistory() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { const router = createTestRouter(history) const component = @@ -45,7 +37,6 @@ export function mountTestApp(container: HTMLElement) { router, unmount() { app.unmount() - history.destroy() }, } } diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/mount/vue/src/routeTree.gen.ts index 98643d63c9..cd27c917e1 100644 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/mount/vue/src/routeTree.gen.ts @@ -9,35 +9,20 @@ // 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 ShopRouteImport } from './routes/shop' -import { Route as SettingsRouteImport } from './routes/settings' -import { Route as SearchRouteImport } from './routes/search' -import { Route as BlogRouteImport } from './routes/blog' -import { Route as AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' -import { Route as ShopIndexRouteImport } from './routes/shop.index' +import { Route as AboutRouteImport } from './routes/about' +import { Route as BlogRouteImport } from './routes/blog' +import { Route as SearchRouteImport } from './routes/search' +import { Route as SettingsRouteImport } from './routes/settings' +import { Route as ShopRouteImport } from './routes/shop' import { Route as BlogIndexRouteImport } from './routes/blog.index' -import { Route as ShopProductIdRouteImport } from './routes/shop.$productId' import { Route as BlogSlugRouteImport } from './routes/blog.$slug' +import { Route as ShopIndexRouteImport } from './routes/shop.index' +import { Route as ShopProductIdRouteImport } from './routes/shop.$productId' -const ShopRoute = ShopRouteImport.update({ - id: '/shop', - path: '/shop', - getParentRoute: () => rootRouteImport, -} as any) -const SettingsRoute = SettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => rootRouteImport, -} as any) -const SearchRoute = SearchRouteImport.update({ - id: '/search', - path: '/search', - getParentRoute: () => rootRouteImport, -} as any) -const BlogRoute = BlogRouteImport.update({ - id: '/blog', - path: '/blog', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AboutRoute = AboutRouteImport.update({ @@ -45,31 +30,46 @@ const AboutRoute = AboutRouteImport.update({ path: '/about', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const BlogRoute = BlogRouteImport.update({ + id: '/blog', + path: '/blog', getParentRoute: () => rootRouteImport, } as any) -const ShopIndexRoute = ShopIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => ShopRoute, +const SearchRoute = SearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => rootRouteImport, +} as any) +const SettingsRoute = SettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => rootRouteImport, +} as any) +const ShopRoute = ShopRouteImport.update({ + id: '/shop', + path: '/shop', + getParentRoute: () => rootRouteImport, } as any) const BlogIndexRoute = BlogIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => BlogRoute, } as any) -const ShopProductIdRoute = ShopProductIdRouteImport.update({ - id: '/$productId', - path: '/$productId', - getParentRoute: () => ShopRoute, -} as any) const BlogSlugRoute = BlogSlugRouteImport.update({ id: '/$slug', path: '/$slug', getParentRoute: () => BlogRoute, } as any) +const ShopIndexRoute = ShopIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => ShopRoute, +} as any) +const ShopProductIdRoute = ShopProductIdRouteImport.update({ + id: '/$productId', + path: '/$productId', + getParentRoute: () => ShopRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -154,32 +154,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/shop': { - id: '/shop' - path: '/shop' - fullPath: '/shop' - preLoaderRoute: typeof ShopRouteImport - parentRoute: typeof rootRouteImport - } - '/settings': { - id: '/settings' - path: '/settings' - fullPath: '/settings' - preLoaderRoute: typeof SettingsRouteImport - parentRoute: typeof rootRouteImport - } - '/search': { - id: '/search' - path: '/search' - fullPath: '/search' - preLoaderRoute: typeof SearchRouteImport - parentRoute: typeof rootRouteImport - } - '/blog': { - id: '/blog' - path: '/blog' - fullPath: '/blog' - preLoaderRoute: typeof BlogRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/about': { @@ -189,19 +168,33 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/blog': { + id: '/blog' + path: '/blog' + fullPath: '/blog' + preLoaderRoute: typeof BlogRouteImport parentRoute: typeof rootRouteImport } - '/shop/': { - id: '/shop/' - path: '/' - fullPath: '/shop/' - preLoaderRoute: typeof ShopIndexRouteImport - parentRoute: typeof ShopRoute + '/search': { + id: '/search' + path: '/search' + fullPath: '/search' + preLoaderRoute: typeof SearchRouteImport + parentRoute: typeof rootRouteImport + } + '/settings': { + id: '/settings' + path: '/settings' + fullPath: '/settings' + preLoaderRoute: typeof SettingsRouteImport + parentRoute: typeof rootRouteImport + } + '/shop': { + id: '/shop' + path: '/shop' + fullPath: '/shop' + preLoaderRoute: typeof ShopRouteImport + parentRoute: typeof rootRouteImport } '/blog/': { id: '/blog/' @@ -210,13 +203,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof BlogIndexRouteImport parentRoute: typeof BlogRoute } - '/shop/$productId': { - id: '/shop/$productId' - path: '/$productId' - fullPath: '/shop/$productId' - preLoaderRoute: typeof ShopProductIdRouteImport - parentRoute: typeof ShopRoute - } '/blog/$slug': { id: '/blog/$slug' path: '/$slug' @@ -224,6 +210,20 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof BlogSlugRouteImport parentRoute: typeof BlogRoute } + '/shop/': { + id: '/shop/' + path: '/' + fullPath: '/shop/' + preLoaderRoute: typeof ShopIndexRouteImport + parentRoute: typeof ShopRoute + } + '/shop/$productId': { + id: '/shop/$productId' + path: '/$productId' + fullPath: '/shop/$productId' + preLoaderRoute: typeof ShopProductIdRouteImport + parentRoute: typeof ShopRoute + } } } diff --git a/benchmarks/client-nav/scenarios/mount/vue/vite.config.ts b/benchmarks/client-nav/scenarios/mount/vue/vite.config.ts index 107e1037b6..8d4005f339 100644 --- a/benchmarks/client-nav/scenarios/mount/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/mount/vue/vite.config.ts @@ -4,6 +4,7 @@ import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -34,6 +35,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav mount (vue)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts b/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts index 321b1ad230..fa5809c1fd 100644 --- a/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-nested-params', () => { - const test = setup() +test('client-nested-params', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-nested-params navigation loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/main.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/main.tsx index ef0b99555c..5febd6f795 100644 --- a/benchmarks/client-nav/scenarios/nested-params/react/src/main.tsx +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import { RouterProvider, createRouter } from '@tanstack/react-router' import { createRoot } from 'react-dom/client' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -20,8 +22,8 @@ declare module '@tanstack/react-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const reactRoot = createRoot(container) reactRoot.render() diff --git a/benchmarks/client-nav/scenarios/nested-params/react/vite.config.ts b/benchmarks/client-nav/scenarios/nested-params/react/vite.config.ts index 672b1850ff..a99060bf1c 100644 --- a/benchmarks/client-nav/scenarios/nested-params/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/nested-params/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import react from '@vitejs/plugin-react' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -32,6 +33,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav nested-params (react)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts index d35980f612..2c64d9a221 100644 --- a/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-nested-params', () => { - const test = setup() +test('client-nested-params', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-nested-params navigation loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/main.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/main.tsx index 817045bd02..fa9d239418 100644 --- a/benchmarks/client-nav/scenarios/nested-params/solid/src/main.tsx +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import { render } from 'solid-js/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -20,8 +22,8 @@ declare module '@tanstack/solid-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const unmount = render(() => , container) diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/vite.config.ts b/benchmarks/client-nav/scenarios/nested-params/solid/vite.config.ts index f5c9e13c0f..9897e2c199 100644 --- a/benchmarks/client-nav/scenarios/nested-params/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/nested-params/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import solid from 'vite-plugin-solid' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -35,6 +36,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav nested-params (solid)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts index fac8703c34..bd3e82e070 100644 --- a/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-nested-params', () => { - const test = setup() +test('client-nested-params', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-nested-params navigation loop (vue)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/main.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/main.tsx index c96d3f3a2e..cae9b54f1d 100644 --- a/benchmarks/client-nav/scenarios/nested-params/vue/src/main.tsx +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import * as Vue from 'vue' import { RouterProvider, createRouter } from '@tanstack/vue-router' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -20,8 +22,8 @@ declare module '@tanstack/vue-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const component = const app = Vue.createApp({ diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/vite.config.ts b/benchmarks/client-nav/scenarios/nested-params/vue/vite.config.ts index 59a4af48ef..0d74eb7a7c 100644 --- a/benchmarks/client-nav/scenarios/nested-params/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/nested-params/vue/vite.config.ts @@ -4,6 +4,7 @@ import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -34,6 +35,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav nested-params (vue)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts b/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts index c869ebdcfb..5c210b2fd7 100644 --- a/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-preload', () => { - const test = setup() +test('client-preload', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-preload interaction loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/preload/react/src/main.tsx b/benchmarks/client-nav/scenarios/preload/react/src/main.tsx index 6f8942c118..395867f674 100644 --- a/benchmarks/client-nav/scenarios/preload/react/src/main.tsx +++ b/benchmarks/client-nav/scenarios/preload/react/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import { RouterProvider, createRouter } from '@tanstack/react-router' import { createRoot } from 'react-dom/client' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -23,8 +25,8 @@ declare module '@tanstack/react-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const reactRoot = createRoot(container) reactRoot.render() diff --git a/benchmarks/client-nav/scenarios/preload/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/preload/react/src/routeTree.gen.ts index 0c76e85974..20619341c0 100644 --- a/benchmarks/client-nav/scenarios/preload/react/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/preload/react/src/routeTree.gen.ts @@ -9,20 +9,20 @@ // 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 DocsRouteImport } from './routes/docs' import { Route as IndexRouteImport } from './routes/index' +import { Route as DocsRouteImport } from './routes/docs' import { Route as SectionsSectionRouteImport } from './routes/sections.$section' -const DocsRoute = DocsRouteImport.update({ - id: '/docs', - path: '/docs', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const DocsRoute = DocsRouteImport.update({ + id: '/docs', + path: '/docs', + getParentRoute: () => rootRouteImport, +} as any) const SectionsSectionRoute = SectionsSectionRouteImport.update({ id: '/sections/$section', path: '/sections/$section', @@ -61,13 +61,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/docs': { - id: '/docs' - path: '/docs' - fullPath: '/docs' - preLoaderRoute: typeof DocsRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -75,6 +68,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/docs': { + id: '/docs' + path: '/docs' + fullPath: '/docs' + preLoaderRoute: typeof DocsRouteImport + parentRoute: typeof rootRouteImport + } '/sections/$section': { id: '/sections/$section' path: '/sections/$section' diff --git a/benchmarks/client-nav/scenarios/preload/react/vite.config.ts b/benchmarks/client-nav/scenarios/preload/react/vite.config.ts index ff51686959..8a41fc8707 100644 --- a/benchmarks/client-nav/scenarios/preload/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/preload/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import react from '@vitejs/plugin-react' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -32,6 +33,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav preload (react)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts index ff2771985b..f835b4a7b9 100644 --- a/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-preload', () => { - const test = setup() +test('client-preload', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-preload interaction loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/preload/solid/src/main.tsx b/benchmarks/client-nav/scenarios/preload/solid/src/main.tsx index 72e414c0a0..3791156c64 100644 --- a/benchmarks/client-nav/scenarios/preload/solid/src/main.tsx +++ b/benchmarks/client-nav/scenarios/preload/solid/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import { render } from 'solid-js/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -23,8 +25,8 @@ declare module '@tanstack/solid-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const unmount = render(() => , container) diff --git a/benchmarks/client-nav/scenarios/preload/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/preload/solid/src/routeTree.gen.ts index 645d925238..97e215b6da 100644 --- a/benchmarks/client-nav/scenarios/preload/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/preload/solid/src/routeTree.gen.ts @@ -9,20 +9,20 @@ // 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 DocsRouteImport } from './routes/docs' import { Route as IndexRouteImport } from './routes/index' +import { Route as DocsRouteImport } from './routes/docs' import { Route as SectionsSectionRouteImport } from './routes/sections.$section' -const DocsRoute = DocsRouteImport.update({ - id: '/docs', - path: '/docs', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const DocsRoute = DocsRouteImport.update({ + id: '/docs', + path: '/docs', + getParentRoute: () => rootRouteImport, +} as any) const SectionsSectionRoute = SectionsSectionRouteImport.update({ id: '/sections/$section', path: '/sections/$section', @@ -61,13 +61,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/docs': { - id: '/docs' - path: '/docs' - fullPath: '/docs' - preLoaderRoute: typeof DocsRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -75,6 +68,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/docs': { + id: '/docs' + path: '/docs' + fullPath: '/docs' + preLoaderRoute: typeof DocsRouteImport + parentRoute: typeof rootRouteImport + } '/sections/$section': { id: '/sections/$section' path: '/sections/$section' diff --git a/benchmarks/client-nav/scenarios/preload/solid/vite.config.ts b/benchmarks/client-nav/scenarios/preload/solid/vite.config.ts index b542834469..07014e6124 100644 --- a/benchmarks/client-nav/scenarios/preload/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/preload/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import solid from 'vite-plugin-solid' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -35,6 +36,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav preload (solid)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts index 2e790e9240..e0ec83619b 100644 --- a/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-preload', () => { - const test = setup() +test('client-preload', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-preload interaction loop (vue)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/preload/vue/src/main.tsx b/benchmarks/client-nav/scenarios/preload/vue/src/main.tsx index 1e325392a4..3da20b2cbf 100644 --- a/benchmarks/client-nav/scenarios/preload/vue/src/main.tsx +++ b/benchmarks/client-nav/scenarios/preload/vue/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import * as Vue from 'vue' import { RouterProvider, createRouter } from '@tanstack/vue-router' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -23,8 +25,8 @@ declare module '@tanstack/vue-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const component = const app = Vue.createApp({ diff --git a/benchmarks/client-nav/scenarios/preload/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/preload/vue/src/routeTree.gen.ts index 05a751060b..5f95d09da0 100644 --- a/benchmarks/client-nav/scenarios/preload/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/preload/vue/src/routeTree.gen.ts @@ -9,20 +9,20 @@ // 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 DocsRouteImport } from './routes/docs' import { Route as IndexRouteImport } from './routes/index' +import { Route as DocsRouteImport } from './routes/docs' import { Route as SectionsSectionRouteImport } from './routes/sections.$section' -const DocsRoute = DocsRouteImport.update({ - id: '/docs', - path: '/docs', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const DocsRoute = DocsRouteImport.update({ + id: '/docs', + path: '/docs', + getParentRoute: () => rootRouteImport, +} as any) const SectionsSectionRoute = SectionsSectionRouteImport.update({ id: '/sections/$section', path: '/sections/$section', @@ -61,13 +61,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/docs': { - id: '/docs' - path: '/docs' - fullPath: '/docs' - preLoaderRoute: typeof DocsRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -75,6 +68,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/docs': { + id: '/docs' + path: '/docs' + fullPath: '/docs' + preLoaderRoute: typeof DocsRouteImport + parentRoute: typeof rootRouteImport + } '/sections/$section': { id: '/sections/$section' path: '/sections/$section' diff --git a/benchmarks/client-nav/scenarios/preload/vue/vite.config.ts b/benchmarks/client-nav/scenarios/preload/vue/vite.config.ts index 25e64b5bef..8d00e66378 100644 --- a/benchmarks/client-nav/scenarios/preload/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/preload/vue/vite.config.ts @@ -4,6 +4,7 @@ import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -34,6 +35,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav preload (vue)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts b/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts index 9b77a79838..dd1b6f3686 100644 --- a/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-rewrites', () => { - const test = setup() +test('client-rewrites', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-rewrites navigation loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/rewrites/react/src/main.tsx b/benchmarks/client-nav/scenarios/rewrites/react/src/main.tsx index 47746bb0fb..28020ce373 100644 --- a/benchmarks/client-nav/scenarios/rewrites/react/src/main.tsx +++ b/benchmarks/client-nav/scenarios/rewrites/react/src/main.tsx @@ -1,11 +1,13 @@ +import type { RouterHistory } from '@tanstack/history' import { RouterProvider, createRouter } from '@tanstack/react-router' import { createRoot } from 'react-dom/client' import { routeTree } from './routeTree.gen' import { basepath, localeRewrite } from '../../shared' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, basepath, rewrite: localeRewrite, scrollRestoration: true, @@ -23,8 +25,8 @@ declare module '@tanstack/react-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const reactRoot = createRoot(container) reactRoot.render() diff --git a/benchmarks/client-nav/scenarios/rewrites/react/vite.config.ts b/benchmarks/client-nav/scenarios/rewrites/react/vite.config.ts index 8c07cff4fb..e79e8522e9 100644 --- a/benchmarks/client-nav/scenarios/rewrites/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/rewrites/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import react from '@vitejs/plugin-react' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -32,6 +33,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav rewrites (react)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/rewrites/shared.ts b/benchmarks/client-nav/scenarios/rewrites/shared.ts index c45b15d503..0ca0a7ceb9 100644 --- a/benchmarks/client-nav/scenarios/rewrites/shared.ts +++ b/benchmarks/client-nav/scenarios/rewrites/shared.ts @@ -8,6 +8,7 @@ * parsing the committed location. */ import type { ScenarioStep } from '../harness' +import type { RouterHistory } from '@tanstack/history' export const basepath = '/app' export const defaultLocale = 'en' @@ -51,7 +52,7 @@ interface StepDef { testId: string /** Internal router pathname expected after the step. */ routerPath: string - /** External window.location pathname expected after the step. */ + /** External history pathname expected after the step. */ windowPath: string } @@ -70,7 +71,11 @@ export const steps: ReadonlyArray = stepDefs.map( (step) => step.testId, ) -export function assertStepResult(stepIndex: number, container: HTMLElement) { +export function assertStepResult( + stepIndex: number, + container: HTMLElement, + history: RouterHistory, +) { const expected = stepDefs[stepIndex]! const marker = container.querySelector('[data-testid="loc"]') const routerPath = marker?.textContent @@ -81,9 +86,9 @@ export function assertStepResult(stepIndex: number, container: HTMLElement) { ) } - if (window.location.pathname !== expected.windowPath) { + if (history.location.pathname !== expected.windowPath) { throw new Error( - `Expected window pathname "${expected.windowPath}" after step ${stepIndex}, received "${window.location.pathname}"`, + `Expected history pathname "${expected.windowPath}" after step ${stepIndex}, received "${history.location.pathname}"`, ) } } diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts index 30d3436071..9c4313e2ff 100644 --- a/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-rewrites', () => { - const test = setup() +test('client-rewrites', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-rewrites navigation loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/src/main.tsx b/benchmarks/client-nav/scenarios/rewrites/solid/src/main.tsx index a80de580fb..31f1d07650 100644 --- a/benchmarks/client-nav/scenarios/rewrites/solid/src/main.tsx +++ b/benchmarks/client-nav/scenarios/rewrites/solid/src/main.tsx @@ -1,11 +1,13 @@ +import type { RouterHistory } from '@tanstack/history' import { render } from 'solid-js/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' import { basepath, localeRewrite } from '../../shared' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, basepath, rewrite: localeRewrite, scrollRestoration: true, @@ -23,8 +25,8 @@ declare module '@tanstack/solid-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const unmount = render(() => , container) diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/vite.config.ts b/benchmarks/client-nav/scenarios/rewrites/solid/vite.config.ts index 41613c2ad4..c9e99b7d60 100644 --- a/benchmarks/client-nav/scenarios/rewrites/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/rewrites/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import solid from 'vite-plugin-solid' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -35,6 +36,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav rewrites (solid)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts index c10b8723bb..e96aff39eb 100644 --- a/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-rewrites', () => { - const test = setup() +test('client-rewrites', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-rewrites navigation loop (vue)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/src/main.tsx b/benchmarks/client-nav/scenarios/rewrites/vue/src/main.tsx index 83e430038d..6695e82dbb 100644 --- a/benchmarks/client-nav/scenarios/rewrites/vue/src/main.tsx +++ b/benchmarks/client-nav/scenarios/rewrites/vue/src/main.tsx @@ -1,11 +1,13 @@ +import type { RouterHistory } from '@tanstack/history' import * as Vue from 'vue' import { RouterProvider, createRouter } from '@tanstack/vue-router' import { routeTree } from './routeTree.gen' import { basepath, localeRewrite } from '../../shared' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, basepath, rewrite: localeRewrite, scrollRestoration: true, @@ -23,8 +25,8 @@ declare module '@tanstack/vue-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const component = const app = Vue.createApp({ diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/vite.config.ts b/benchmarks/client-nav/scenarios/rewrites/vue/vite.config.ts index 39e22b6c3e..1a795a4e1d 100644 --- a/benchmarks/client-nav/scenarios/rewrites/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/rewrites/vue/vite.config.ts @@ -4,6 +4,7 @@ import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -34,6 +35,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav rewrites (vue)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.bench.ts b/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.bench.ts index 50cc26d5d6..6f4b448775 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-route-tree-scale', () => { - const test = setup() +test('client-route-tree-scale', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-route-tree-scale navigation loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/main.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/main.tsx index ef0b99555c..5febd6f795 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/main.tsx +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import { RouterProvider, createRouter } from '@tanstack/react-router' import { createRoot } from 'react-dom/client' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -20,8 +22,8 @@ declare module '@tanstack/react-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const reactRoot = createRoot(container) reactRoot.render() diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routeTree.gen.ts index b58b75180f..f8eeb73dda 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routeTree.gen.ts @@ -9,68 +9,52 @@ // 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 SecFRouteImport } from './routes/sec-f' -import { Route as SecERouteImport } from './routes/sec-e' -import { Route as SecDRouteImport } from './routes/sec-d' -import { Route as SecCRouteImport } from './routes/sec-c' -import { Route as SecBRouteImport } from './routes/sec-b' -import { Route as SecARouteImport } from './routes/sec-a' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as IndexRouteImport } from './routes/index' -import { Route as SecFIndexRouteImport } from './routes/sec-f.index' -import { Route as SecEIndexRouteImport } from './routes/sec-e.index' -import { Route as SecDIndexRouteImport } from './routes/sec-d.index' -import { Route as SecCIndexRouteImport } from './routes/sec-c.index' -import { Route as SecBIndexRouteImport } from './routes/sec-b.index' -import { Route as SecAIndexRouteImport } from './routes/sec-a.index' -import { Route as SecFSettingsRouteImport } from './routes/sec-f.settings' -import { Route as SecFAboutRouteImport } from './routes/sec-f.about' -import { Route as SecFIdRouteImport } from './routes/sec-f.$id' -import { Route as SecESettingsRouteImport } from './routes/sec-e.settings' -import { Route as SecEAboutRouteImport } from './routes/sec-e.about' -import { Route as SecEIdRouteImport } from './routes/sec-e.$id' -import { Route as SecDSettingsRouteImport } from './routes/sec-d.settings' -import { Route as SecDAboutRouteImport } from './routes/sec-d.about' -import { Route as SecDIdRouteImport } from './routes/sec-d.$id' -import { Route as SecCSettingsRouteImport } from './routes/sec-c.settings' -import { Route as SecCAboutRouteImport } from './routes/sec-c.about' -import { Route as SecCIdRouteImport } from './routes/sec-c.$id' -import { Route as SecBSettingsRouteImport } from './routes/sec-b.settings' -import { Route as SecBAboutRouteImport } from './routes/sec-b.about' -import { Route as SecBIdRouteImport } from './routes/sec-b.$id' -import { Route as SecASettingsRouteImport } from './routes/sec-a.settings' -import { Route as SecAAboutRouteImport } from './routes/sec-a.about' -import { Route as SecAIdRouteImport } from './routes/sec-a.$id' -import { Route as ReleaseVChar123versionChar125RouteImport } from './routes/release.v{$version}' -import { Route as FilesSplatRouteImport } from './routes/files.$' -import { Route as LayoutBetaRouteImport } from './routes/_layout.beta' -import { Route as LayoutAlphaRouteImport } from './routes/_layout.alpha' -import { Route as marketingPromoRouteImport } from './routes/(marketing)/promo' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as SecARouteImport } from './routes/sec-a' +import { Route as SecBRouteImport } from './routes/sec-b' +import { Route as SecCRouteImport } from './routes/sec-c' +import { Route as SecDRouteImport } from './routes/sec-d' +import { Route as SecERouteImport } from './routes/sec-e' +import { Route as SecFRouteImport } from './routes/sec-f' import { Route as marketingPricingRouteImport } from './routes/(marketing)/pricing' +import { Route as marketingPromoRouteImport } from './routes/(marketing)/promo' +import { Route as LayoutAlphaRouteImport } from './routes/_layout.alpha' +import { Route as LayoutBetaRouteImport } from './routes/_layout.beta' +import { Route as FilesSplatRouteImport } from './routes/files.$' +import { Route as ReleaseVChar123versionChar125RouteImport } from './routes/release.v{$version}' +import { Route as SecAIndexRouteImport } from './routes/sec-a.index' +import { Route as SecAIdRouteImport } from './routes/sec-a.$id' +import { Route as SecAAboutRouteImport } from './routes/sec-a.about' +import { Route as SecASettingsRouteImport } from './routes/sec-a.settings' +import { Route as SecBIndexRouteImport } from './routes/sec-b.index' +import { Route as SecBIdRouteImport } from './routes/sec-b.$id' +import { Route as SecBAboutRouteImport } from './routes/sec-b.about' +import { Route as SecBSettingsRouteImport } from './routes/sec-b.settings' +import { Route as SecCIndexRouteImport } from './routes/sec-c.index' +import { Route as SecCIdRouteImport } from './routes/sec-c.$id' +import { Route as SecCAboutRouteImport } from './routes/sec-c.about' +import { Route as SecCSettingsRouteImport } from './routes/sec-c.settings' +import { Route as SecDIndexRouteImport } from './routes/sec-d.index' +import { Route as SecDIdRouteImport } from './routes/sec-d.$id' +import { Route as SecDAboutRouteImport } from './routes/sec-d.about' +import { Route as SecDSettingsRouteImport } from './routes/sec-d.settings' +import { Route as SecEIndexRouteImport } from './routes/sec-e.index' +import { Route as SecEIdRouteImport } from './routes/sec-e.$id' +import { Route as SecEAboutRouteImport } from './routes/sec-e.about' +import { Route as SecESettingsRouteImport } from './routes/sec-e.settings' +import { Route as SecFIndexRouteImport } from './routes/sec-f.index' +import { Route as SecFIdRouteImport } from './routes/sec-f.$id' +import { Route as SecFAboutRouteImport } from './routes/sec-f.about' +import { Route as SecFSettingsRouteImport } from './routes/sec-f.settings' -const SecFRoute = SecFRouteImport.update({ - id: '/sec-f', - path: '/sec-f', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const SecERoute = SecERouteImport.update({ - id: '/sec-e', - path: '/sec-e', - getParentRoute: () => rootRouteImport, -} as any) -const SecDRoute = SecDRouteImport.update({ - id: '/sec-d', - path: '/sec-d', - getParentRoute: () => rootRouteImport, -} as any) -const SecCRoute = SecCRouteImport.update({ - id: '/sec-c', - path: '/sec-c', - getParentRoute: () => rootRouteImport, -} as any) -const SecBRoute = SecBRouteImport.update({ - id: '/sec-b', - path: '/sec-b', +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', getParentRoute: () => rootRouteImport, } as any) const SecARoute = SecARouteImport.update({ @@ -78,134 +62,55 @@ const SecARoute = SecARouteImport.update({ path: '/sec-a', getParentRoute: () => rootRouteImport, } as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', +const SecBRoute = SecBRouteImport.update({ + id: '/sec-b', + path: '/sec-b', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SecCRoute = SecCRouteImport.update({ + id: '/sec-c', + path: '/sec-c', getParentRoute: () => rootRouteImport, } as any) -const SecFIndexRoute = SecFIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecFRoute, +const SecDRoute = SecDRouteImport.update({ + id: '/sec-d', + path: '/sec-d', + getParentRoute: () => rootRouteImport, } as any) -const SecEIndexRoute = SecEIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecERoute, +const SecERoute = SecERouteImport.update({ + id: '/sec-e', + path: '/sec-e', + getParentRoute: () => rootRouteImport, } as any) -const SecDIndexRoute = SecDIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecDRoute, +const SecFRoute = SecFRouteImport.update({ + id: '/sec-f', + path: '/sec-f', + getParentRoute: () => rootRouteImport, } as any) -const SecCIndexRoute = SecCIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecCRoute, +const marketingPricingRoute = marketingPricingRouteImport.update({ + id: '/(marketing)/pricing', + path: '/pricing', + getParentRoute: () => rootRouteImport, } as any) -const SecBIndexRoute = SecBIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecBRoute, +const marketingPromoRoute = marketingPromoRouteImport.update({ + id: '/(marketing)/promo', + path: '/promo', + getParentRoute: () => rootRouteImport, } as any) -const SecAIndexRoute = SecAIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecARoute, +const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ + id: '/alpha', + path: '/alpha', + getParentRoute: () => LayoutRoute, } as any) -const SecFSettingsRoute = SecFSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecFRoute, +const LayoutBetaRoute = LayoutBetaRouteImport.update({ + id: '/beta', + path: '/beta', + getParentRoute: () => LayoutRoute, } as any) -const SecFAboutRoute = SecFAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecFRoute, -} as any) -const SecFIdRoute = SecFIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecFRoute, -} as any) -const SecESettingsRoute = SecESettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecERoute, -} as any) -const SecEAboutRoute = SecEAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecERoute, -} as any) -const SecEIdRoute = SecEIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecERoute, -} as any) -const SecDSettingsRoute = SecDSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecDRoute, -} as any) -const SecDAboutRoute = SecDAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecDRoute, -} as any) -const SecDIdRoute = SecDIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecDRoute, -} as any) -const SecCSettingsRoute = SecCSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecCRoute, -} as any) -const SecCAboutRoute = SecCAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecCRoute, -} as any) -const SecCIdRoute = SecCIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecCRoute, -} as any) -const SecBSettingsRoute = SecBSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecBRoute, -} as any) -const SecBAboutRoute = SecBAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecBRoute, -} as any) -const SecBIdRoute = SecBIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecBRoute, -} as any) -const SecASettingsRoute = SecASettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecARoute, -} as any) -const SecAAboutRoute = SecAAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecARoute, -} as any) -const SecAIdRoute = SecAIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecARoute, +const FilesSplatRoute = FilesSplatRouteImport.update({ + id: '/files/$', + path: '/files/$', + getParentRoute: () => rootRouteImport, } as any) const ReleaseVChar123versionChar125Route = ReleaseVChar123versionChar125RouteImport.update({ @@ -213,30 +118,125 @@ const ReleaseVChar123versionChar125Route = path: '/release/v{$version}', getParentRoute: () => rootRouteImport, } as any) -const FilesSplatRoute = FilesSplatRouteImport.update({ - id: '/files/$', - path: '/files/$', - getParentRoute: () => rootRouteImport, +const SecAIndexRoute = SecAIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecARoute, } as any) -const LayoutBetaRoute = LayoutBetaRouteImport.update({ - id: '/beta', - path: '/beta', - getParentRoute: () => LayoutRoute, +const SecAIdRoute = SecAIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecARoute, } as any) -const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ - id: '/alpha', - path: '/alpha', - getParentRoute: () => LayoutRoute, +const SecAAboutRoute = SecAAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecARoute, } as any) -const marketingPromoRoute = marketingPromoRouteImport.update({ - id: '/(marketing)/promo', - path: '/promo', - getParentRoute: () => rootRouteImport, +const SecASettingsRoute = SecASettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecARoute, } as any) -const marketingPricingRoute = marketingPricingRouteImport.update({ - id: '/(marketing)/pricing', - path: '/pricing', - getParentRoute: () => rootRouteImport, +const SecBIndexRoute = SecBIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecBRoute, +} as any) +const SecBIdRoute = SecBIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecBRoute, +} as any) +const SecBAboutRoute = SecBAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecBRoute, +} as any) +const SecBSettingsRoute = SecBSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecBRoute, +} as any) +const SecCIndexRoute = SecCIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecCRoute, +} as any) +const SecCIdRoute = SecCIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecCRoute, +} as any) +const SecCAboutRoute = SecCAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecCRoute, +} as any) +const SecCSettingsRoute = SecCSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecCRoute, +} as any) +const SecDIndexRoute = SecDIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecDRoute, +} as any) +const SecDIdRoute = SecDIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecDRoute, +} as any) +const SecDAboutRoute = SecDAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecDRoute, +} as any) +const SecDSettingsRoute = SecDSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecDRoute, +} as any) +const SecEIndexRoute = SecEIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecERoute, +} as any) +const SecEIdRoute = SecEIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecERoute, +} as any) +const SecEAboutRoute = SecEAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecERoute, +} as any) +const SecESettingsRoute = SecESettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecERoute, +} as any) +const SecFIndexRoute = SecFIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecFRoute, +} as any) +const SecFIdRoute = SecFIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecFRoute, +} as any) +const SecFAboutRoute = SecFAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecFRoute, +} as any) +const SecFSettingsRoute = SecFSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecFRoute, } as any) export interface FileRoutesByFullPath { @@ -484,46 +484,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/sec-f': { - id: '/sec-f' - path: '/sec-f' - fullPath: '/sec-f' - preLoaderRoute: typeof SecFRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-e': { - id: '/sec-e' - path: '/sec-e' - fullPath: '/sec-e' - preLoaderRoute: typeof SecERouteImport - parentRoute: typeof rootRouteImport - } - '/sec-d': { - id: '/sec-d' - path: '/sec-d' - fullPath: '/sec-d' - preLoaderRoute: typeof SecDRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-c': { - id: '/sec-c' - path: '/sec-c' - fullPath: '/sec-c' - preLoaderRoute: typeof SecCRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-b': { - id: '/sec-b' - path: '/sec-b' - fullPath: '/sec-b' - preLoaderRoute: typeof SecBRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-a': { - id: '/sec-a' - path: '/sec-a' - fullPath: '/sec-a' - preLoaderRoute: typeof SecARouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -533,47 +498,89 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/sec-a': { + id: '/sec-a' + path: '/sec-a' + fullPath: '/sec-a' + preLoaderRoute: typeof SecARouteImport parentRoute: typeof rootRouteImport } - '/sec-f/': { - id: '/sec-f/' - path: '/' - fullPath: '/sec-f/' - preLoaderRoute: typeof SecFIndexRouteImport - parentRoute: typeof SecFRoute + '/sec-b': { + id: '/sec-b' + path: '/sec-b' + fullPath: '/sec-b' + preLoaderRoute: typeof SecBRouteImport + parentRoute: typeof rootRouteImport } - '/sec-e/': { - id: '/sec-e/' - path: '/' - fullPath: '/sec-e/' - preLoaderRoute: typeof SecEIndexRouteImport - parentRoute: typeof SecERoute + '/sec-c': { + id: '/sec-c' + path: '/sec-c' + fullPath: '/sec-c' + preLoaderRoute: typeof SecCRouteImport + parentRoute: typeof rootRouteImport } - '/sec-d/': { - id: '/sec-d/' - path: '/' - fullPath: '/sec-d/' - preLoaderRoute: typeof SecDIndexRouteImport - parentRoute: typeof SecDRoute + '/sec-d': { + id: '/sec-d' + path: '/sec-d' + fullPath: '/sec-d' + preLoaderRoute: typeof SecDRouteImport + parentRoute: typeof rootRouteImport } - '/sec-c/': { - id: '/sec-c/' - path: '/' - fullPath: '/sec-c/' - preLoaderRoute: typeof SecCIndexRouteImport - parentRoute: typeof SecCRoute + '/sec-e': { + id: '/sec-e' + path: '/sec-e' + fullPath: '/sec-e' + preLoaderRoute: typeof SecERouteImport + parentRoute: typeof rootRouteImport } - '/sec-b/': { - id: '/sec-b/' - path: '/' - fullPath: '/sec-b/' - preLoaderRoute: typeof SecBIndexRouteImport - parentRoute: typeof SecBRoute + '/sec-f': { + id: '/sec-f' + path: '/sec-f' + fullPath: '/sec-f' + preLoaderRoute: typeof SecFRouteImport + parentRoute: typeof rootRouteImport + } + '/(marketing)/pricing': { + id: '/(marketing)/pricing' + path: '/pricing' + fullPath: '/pricing' + preLoaderRoute: typeof marketingPricingRouteImport + parentRoute: typeof rootRouteImport + } + '/(marketing)/promo': { + id: '/(marketing)/promo' + path: '/promo' + fullPath: '/promo' + preLoaderRoute: typeof marketingPromoRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/alpha': { + id: '/_layout/alpha' + path: '/alpha' + fullPath: '/alpha' + preLoaderRoute: typeof LayoutAlphaRouteImport + parentRoute: typeof LayoutRoute + } + '/_layout/beta': { + id: '/_layout/beta' + path: '/beta' + fullPath: '/beta' + preLoaderRoute: typeof LayoutBetaRouteImport + parentRoute: typeof LayoutRoute + } + '/files/$': { + id: '/files/$' + path: '/files/$' + fullPath: '/files/$' + preLoaderRoute: typeof FilesSplatRouteImport + parentRoute: typeof rootRouteImport + } + '/release/v{$version}': { + id: '/release/v{$version}' + path: '/release/v{$version}' + fullPath: '/release/v{$version}' + preLoaderRoute: typeof ReleaseVChar123versionChar125RouteImport + parentRoute: typeof rootRouteImport } '/sec-a/': { id: '/sec-a/' @@ -582,125 +589,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof SecAIndexRouteImport parentRoute: typeof SecARoute } - '/sec-f/settings': { - id: '/sec-f/settings' - path: '/settings' - fullPath: '/sec-f/settings' - preLoaderRoute: typeof SecFSettingsRouteImport - parentRoute: typeof SecFRoute - } - '/sec-f/about': { - id: '/sec-f/about' - path: '/about' - fullPath: '/sec-f/about' - preLoaderRoute: typeof SecFAboutRouteImport - parentRoute: typeof SecFRoute - } - '/sec-f/$id': { - id: '/sec-f/$id' - path: '/$id' - fullPath: '/sec-f/$id' - preLoaderRoute: typeof SecFIdRouteImport - parentRoute: typeof SecFRoute - } - '/sec-e/settings': { - id: '/sec-e/settings' - path: '/settings' - fullPath: '/sec-e/settings' - preLoaderRoute: typeof SecESettingsRouteImport - parentRoute: typeof SecERoute - } - '/sec-e/about': { - id: '/sec-e/about' - path: '/about' - fullPath: '/sec-e/about' - preLoaderRoute: typeof SecEAboutRouteImport - parentRoute: typeof SecERoute - } - '/sec-e/$id': { - id: '/sec-e/$id' - path: '/$id' - fullPath: '/sec-e/$id' - preLoaderRoute: typeof SecEIdRouteImport - parentRoute: typeof SecERoute - } - '/sec-d/settings': { - id: '/sec-d/settings' - path: '/settings' - fullPath: '/sec-d/settings' - preLoaderRoute: typeof SecDSettingsRouteImport - parentRoute: typeof SecDRoute - } - '/sec-d/about': { - id: '/sec-d/about' - path: '/about' - fullPath: '/sec-d/about' - preLoaderRoute: typeof SecDAboutRouteImport - parentRoute: typeof SecDRoute - } - '/sec-d/$id': { - id: '/sec-d/$id' - path: '/$id' - fullPath: '/sec-d/$id' - preLoaderRoute: typeof SecDIdRouteImport - parentRoute: typeof SecDRoute - } - '/sec-c/settings': { - id: '/sec-c/settings' - path: '/settings' - fullPath: '/sec-c/settings' - preLoaderRoute: typeof SecCSettingsRouteImport - parentRoute: typeof SecCRoute - } - '/sec-c/about': { - id: '/sec-c/about' - path: '/about' - fullPath: '/sec-c/about' - preLoaderRoute: typeof SecCAboutRouteImport - parentRoute: typeof SecCRoute - } - '/sec-c/$id': { - id: '/sec-c/$id' - path: '/$id' - fullPath: '/sec-c/$id' - preLoaderRoute: typeof SecCIdRouteImport - parentRoute: typeof SecCRoute - } - '/sec-b/settings': { - id: '/sec-b/settings' - path: '/settings' - fullPath: '/sec-b/settings' - preLoaderRoute: typeof SecBSettingsRouteImport - parentRoute: typeof SecBRoute - } - '/sec-b/about': { - id: '/sec-b/about' - path: '/about' - fullPath: '/sec-b/about' - preLoaderRoute: typeof SecBAboutRouteImport - parentRoute: typeof SecBRoute - } - '/sec-b/$id': { - id: '/sec-b/$id' - path: '/$id' - fullPath: '/sec-b/$id' - preLoaderRoute: typeof SecBIdRouteImport - parentRoute: typeof SecBRoute - } - '/sec-a/settings': { - id: '/sec-a/settings' - path: '/settings' - fullPath: '/sec-a/settings' - preLoaderRoute: typeof SecASettingsRouteImport - parentRoute: typeof SecARoute - } - '/sec-a/about': { - id: '/sec-a/about' - path: '/about' - fullPath: '/sec-a/about' - preLoaderRoute: typeof SecAAboutRouteImport - parentRoute: typeof SecARoute - } '/sec-a/$id': { id: '/sec-a/$id' path: '/$id' @@ -708,47 +596,159 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof SecAIdRouteImport parentRoute: typeof SecARoute } - '/release/v{$version}': { - id: '/release/v{$version}' - path: '/release/v{$version}' - fullPath: '/release/v{$version}' - preLoaderRoute: typeof ReleaseVChar123versionChar125RouteImport - parentRoute: typeof rootRouteImport + '/sec-a/about': { + id: '/sec-a/about' + path: '/about' + fullPath: '/sec-a/about' + preLoaderRoute: typeof SecAAboutRouteImport + parentRoute: typeof SecARoute } - '/files/$': { - id: '/files/$' - path: '/files/$' - fullPath: '/files/$' - preLoaderRoute: typeof FilesSplatRouteImport - parentRoute: typeof rootRouteImport + '/sec-a/settings': { + id: '/sec-a/settings' + path: '/settings' + fullPath: '/sec-a/settings' + preLoaderRoute: typeof SecASettingsRouteImport + parentRoute: typeof SecARoute } - '/_layout/beta': { - id: '/_layout/beta' - path: '/beta' - fullPath: '/beta' - preLoaderRoute: typeof LayoutBetaRouteImport - parentRoute: typeof LayoutRoute + '/sec-b/': { + id: '/sec-b/' + path: '/' + fullPath: '/sec-b/' + preLoaderRoute: typeof SecBIndexRouteImport + parentRoute: typeof SecBRoute } - '/_layout/alpha': { - id: '/_layout/alpha' - path: '/alpha' - fullPath: '/alpha' - preLoaderRoute: typeof LayoutAlphaRouteImport - parentRoute: typeof LayoutRoute + '/sec-b/$id': { + id: '/sec-b/$id' + path: '/$id' + fullPath: '/sec-b/$id' + preLoaderRoute: typeof SecBIdRouteImport + parentRoute: typeof SecBRoute } - '/(marketing)/promo': { - id: '/(marketing)/promo' - path: '/promo' - fullPath: '/promo' - preLoaderRoute: typeof marketingPromoRouteImport - parentRoute: typeof rootRouteImport + '/sec-b/about': { + id: '/sec-b/about' + path: '/about' + fullPath: '/sec-b/about' + preLoaderRoute: typeof SecBAboutRouteImport + parentRoute: typeof SecBRoute } - '/(marketing)/pricing': { - id: '/(marketing)/pricing' - path: '/pricing' - fullPath: '/pricing' - preLoaderRoute: typeof marketingPricingRouteImport - parentRoute: typeof rootRouteImport + '/sec-b/settings': { + id: '/sec-b/settings' + path: '/settings' + fullPath: '/sec-b/settings' + preLoaderRoute: typeof SecBSettingsRouteImport + parentRoute: typeof SecBRoute + } + '/sec-c/': { + id: '/sec-c/' + path: '/' + fullPath: '/sec-c/' + preLoaderRoute: typeof SecCIndexRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/$id': { + id: '/sec-c/$id' + path: '/$id' + fullPath: '/sec-c/$id' + preLoaderRoute: typeof SecCIdRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/about': { + id: '/sec-c/about' + path: '/about' + fullPath: '/sec-c/about' + preLoaderRoute: typeof SecCAboutRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/settings': { + id: '/sec-c/settings' + path: '/settings' + fullPath: '/sec-c/settings' + preLoaderRoute: typeof SecCSettingsRouteImport + parentRoute: typeof SecCRoute + } + '/sec-d/': { + id: '/sec-d/' + path: '/' + fullPath: '/sec-d/' + preLoaderRoute: typeof SecDIndexRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/$id': { + id: '/sec-d/$id' + path: '/$id' + fullPath: '/sec-d/$id' + preLoaderRoute: typeof SecDIdRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/about': { + id: '/sec-d/about' + path: '/about' + fullPath: '/sec-d/about' + preLoaderRoute: typeof SecDAboutRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/settings': { + id: '/sec-d/settings' + path: '/settings' + fullPath: '/sec-d/settings' + preLoaderRoute: typeof SecDSettingsRouteImport + parentRoute: typeof SecDRoute + } + '/sec-e/': { + id: '/sec-e/' + path: '/' + fullPath: '/sec-e/' + preLoaderRoute: typeof SecEIndexRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/$id': { + id: '/sec-e/$id' + path: '/$id' + fullPath: '/sec-e/$id' + preLoaderRoute: typeof SecEIdRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/about': { + id: '/sec-e/about' + path: '/about' + fullPath: '/sec-e/about' + preLoaderRoute: typeof SecEAboutRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/settings': { + id: '/sec-e/settings' + path: '/settings' + fullPath: '/sec-e/settings' + preLoaderRoute: typeof SecESettingsRouteImport + parentRoute: typeof SecERoute + } + '/sec-f/': { + id: '/sec-f/' + path: '/' + fullPath: '/sec-f/' + preLoaderRoute: typeof SecFIndexRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/$id': { + id: '/sec-f/$id' + path: '/$id' + fullPath: '/sec-f/$id' + preLoaderRoute: typeof SecFIdRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/about': { + id: '/sec-f/about' + path: '/about' + fullPath: '/sec-f/about' + preLoaderRoute: typeof SecFAboutRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/settings': { + id: '/sec-f/settings' + path: '/settings' + fullPath: '/sec-f/settings' + preLoaderRoute: typeof SecFSettingsRouteImport + parentRoute: typeof SecFRoute } } } diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/vite.config.ts b/benchmarks/client-nav/scenarios/route-tree-scale/react/vite.config.ts index 686907a506..0f588fda53 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import react from '@vitejs/plugin-react' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -35,6 +36,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav route-tree-scale (react)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.bench.ts index 3d7a22a027..9244ef1350 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-route-tree-scale', () => { - const test = setup() +test('client-route-tree-scale', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-route-tree-scale navigation loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/main.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/main.tsx index 817045bd02..fa9d239418 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/main.tsx +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import { render } from 'solid-js/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -20,8 +22,8 @@ declare module '@tanstack/solid-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const unmount = render(() => , container) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts index 20b4af6146..e6f3596562 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts @@ -9,68 +9,52 @@ // 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 SecFRouteImport } from './routes/sec-f' -import { Route as SecERouteImport } from './routes/sec-e' -import { Route as SecDRouteImport } from './routes/sec-d' -import { Route as SecCRouteImport } from './routes/sec-c' -import { Route as SecBRouteImport } from './routes/sec-b' -import { Route as SecARouteImport } from './routes/sec-a' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as IndexRouteImport } from './routes/index' -import { Route as SecFIndexRouteImport } from './routes/sec-f.index' -import { Route as SecEIndexRouteImport } from './routes/sec-e.index' -import { Route as SecDIndexRouteImport } from './routes/sec-d.index' -import { Route as SecCIndexRouteImport } from './routes/sec-c.index' -import { Route as SecBIndexRouteImport } from './routes/sec-b.index' -import { Route as SecAIndexRouteImport } from './routes/sec-a.index' -import { Route as SecFSettingsRouteImport } from './routes/sec-f.settings' -import { Route as SecFAboutRouteImport } from './routes/sec-f.about' -import { Route as SecFIdRouteImport } from './routes/sec-f.$id' -import { Route as SecESettingsRouteImport } from './routes/sec-e.settings' -import { Route as SecEAboutRouteImport } from './routes/sec-e.about' -import { Route as SecEIdRouteImport } from './routes/sec-e.$id' -import { Route as SecDSettingsRouteImport } from './routes/sec-d.settings' -import { Route as SecDAboutRouteImport } from './routes/sec-d.about' -import { Route as SecDIdRouteImport } from './routes/sec-d.$id' -import { Route as SecCSettingsRouteImport } from './routes/sec-c.settings' -import { Route as SecCAboutRouteImport } from './routes/sec-c.about' -import { Route as SecCIdRouteImport } from './routes/sec-c.$id' -import { Route as SecBSettingsRouteImport } from './routes/sec-b.settings' -import { Route as SecBAboutRouteImport } from './routes/sec-b.about' -import { Route as SecBIdRouteImport } from './routes/sec-b.$id' -import { Route as SecASettingsRouteImport } from './routes/sec-a.settings' -import { Route as SecAAboutRouteImport } from './routes/sec-a.about' -import { Route as SecAIdRouteImport } from './routes/sec-a.$id' -import { Route as ReleaseVChar123versionChar125RouteImport } from './routes/release.v{$version}' -import { Route as FilesSplatRouteImport } from './routes/files.$' -import { Route as LayoutBetaRouteImport } from './routes/_layout.beta' -import { Route as LayoutAlphaRouteImport } from './routes/_layout.alpha' -import { Route as marketingPromoRouteImport } from './routes/(marketing)/promo' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as SecARouteImport } from './routes/sec-a' +import { Route as SecBRouteImport } from './routes/sec-b' +import { Route as SecCRouteImport } from './routes/sec-c' +import { Route as SecDRouteImport } from './routes/sec-d' +import { Route as SecERouteImport } from './routes/sec-e' +import { Route as SecFRouteImport } from './routes/sec-f' import { Route as marketingPricingRouteImport } from './routes/(marketing)/pricing' +import { Route as marketingPromoRouteImport } from './routes/(marketing)/promo' +import { Route as LayoutAlphaRouteImport } from './routes/_layout.alpha' +import { Route as LayoutBetaRouteImport } from './routes/_layout.beta' +import { Route as FilesSplatRouteImport } from './routes/files.$' +import { Route as ReleaseVChar123versionChar125RouteImport } from './routes/release.v{$version}' +import { Route as SecAIndexRouteImport } from './routes/sec-a.index' +import { Route as SecAIdRouteImport } from './routes/sec-a.$id' +import { Route as SecAAboutRouteImport } from './routes/sec-a.about' +import { Route as SecASettingsRouteImport } from './routes/sec-a.settings' +import { Route as SecBIndexRouteImport } from './routes/sec-b.index' +import { Route as SecBIdRouteImport } from './routes/sec-b.$id' +import { Route as SecBAboutRouteImport } from './routes/sec-b.about' +import { Route as SecBSettingsRouteImport } from './routes/sec-b.settings' +import { Route as SecCIndexRouteImport } from './routes/sec-c.index' +import { Route as SecCIdRouteImport } from './routes/sec-c.$id' +import { Route as SecCAboutRouteImport } from './routes/sec-c.about' +import { Route as SecCSettingsRouteImport } from './routes/sec-c.settings' +import { Route as SecDIndexRouteImport } from './routes/sec-d.index' +import { Route as SecDIdRouteImport } from './routes/sec-d.$id' +import { Route as SecDAboutRouteImport } from './routes/sec-d.about' +import { Route as SecDSettingsRouteImport } from './routes/sec-d.settings' +import { Route as SecEIndexRouteImport } from './routes/sec-e.index' +import { Route as SecEIdRouteImport } from './routes/sec-e.$id' +import { Route as SecEAboutRouteImport } from './routes/sec-e.about' +import { Route as SecESettingsRouteImport } from './routes/sec-e.settings' +import { Route as SecFIndexRouteImport } from './routes/sec-f.index' +import { Route as SecFIdRouteImport } from './routes/sec-f.$id' +import { Route as SecFAboutRouteImport } from './routes/sec-f.about' +import { Route as SecFSettingsRouteImport } from './routes/sec-f.settings' -const SecFRoute = SecFRouteImport.update({ - id: '/sec-f', - path: '/sec-f', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const SecERoute = SecERouteImport.update({ - id: '/sec-e', - path: '/sec-e', - getParentRoute: () => rootRouteImport, -} as any) -const SecDRoute = SecDRouteImport.update({ - id: '/sec-d', - path: '/sec-d', - getParentRoute: () => rootRouteImport, -} as any) -const SecCRoute = SecCRouteImport.update({ - id: '/sec-c', - path: '/sec-c', - getParentRoute: () => rootRouteImport, -} as any) -const SecBRoute = SecBRouteImport.update({ - id: '/sec-b', - path: '/sec-b', +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', getParentRoute: () => rootRouteImport, } as any) const SecARoute = SecARouteImport.update({ @@ -78,134 +62,55 @@ const SecARoute = SecARouteImport.update({ path: '/sec-a', getParentRoute: () => rootRouteImport, } as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', +const SecBRoute = SecBRouteImport.update({ + id: '/sec-b', + path: '/sec-b', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SecCRoute = SecCRouteImport.update({ + id: '/sec-c', + path: '/sec-c', getParentRoute: () => rootRouteImport, } as any) -const SecFIndexRoute = SecFIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecFRoute, +const SecDRoute = SecDRouteImport.update({ + id: '/sec-d', + path: '/sec-d', + getParentRoute: () => rootRouteImport, } as any) -const SecEIndexRoute = SecEIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecERoute, +const SecERoute = SecERouteImport.update({ + id: '/sec-e', + path: '/sec-e', + getParentRoute: () => rootRouteImport, } as any) -const SecDIndexRoute = SecDIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecDRoute, +const SecFRoute = SecFRouteImport.update({ + id: '/sec-f', + path: '/sec-f', + getParentRoute: () => rootRouteImport, } as any) -const SecCIndexRoute = SecCIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecCRoute, +const marketingPricingRoute = marketingPricingRouteImport.update({ + id: '/(marketing)/pricing', + path: '/pricing', + getParentRoute: () => rootRouteImport, } as any) -const SecBIndexRoute = SecBIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecBRoute, +const marketingPromoRoute = marketingPromoRouteImport.update({ + id: '/(marketing)/promo', + path: '/promo', + getParentRoute: () => rootRouteImport, } as any) -const SecAIndexRoute = SecAIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecARoute, +const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ + id: '/alpha', + path: '/alpha', + getParentRoute: () => LayoutRoute, } as any) -const SecFSettingsRoute = SecFSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecFRoute, +const LayoutBetaRoute = LayoutBetaRouteImport.update({ + id: '/beta', + path: '/beta', + getParentRoute: () => LayoutRoute, } as any) -const SecFAboutRoute = SecFAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecFRoute, -} as any) -const SecFIdRoute = SecFIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecFRoute, -} as any) -const SecESettingsRoute = SecESettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecERoute, -} as any) -const SecEAboutRoute = SecEAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecERoute, -} as any) -const SecEIdRoute = SecEIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecERoute, -} as any) -const SecDSettingsRoute = SecDSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecDRoute, -} as any) -const SecDAboutRoute = SecDAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecDRoute, -} as any) -const SecDIdRoute = SecDIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecDRoute, -} as any) -const SecCSettingsRoute = SecCSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecCRoute, -} as any) -const SecCAboutRoute = SecCAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecCRoute, -} as any) -const SecCIdRoute = SecCIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecCRoute, -} as any) -const SecBSettingsRoute = SecBSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecBRoute, -} as any) -const SecBAboutRoute = SecBAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecBRoute, -} as any) -const SecBIdRoute = SecBIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecBRoute, -} as any) -const SecASettingsRoute = SecASettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecARoute, -} as any) -const SecAAboutRoute = SecAAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecARoute, -} as any) -const SecAIdRoute = SecAIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecARoute, +const FilesSplatRoute = FilesSplatRouteImport.update({ + id: '/files/$', + path: '/files/$', + getParentRoute: () => rootRouteImport, } as any) const ReleaseVChar123versionChar125Route = ReleaseVChar123versionChar125RouteImport.update({ @@ -213,30 +118,125 @@ const ReleaseVChar123versionChar125Route = path: '/release/v{$version}', getParentRoute: () => rootRouteImport, } as any) -const FilesSplatRoute = FilesSplatRouteImport.update({ - id: '/files/$', - path: '/files/$', - getParentRoute: () => rootRouteImport, +const SecAIndexRoute = SecAIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecARoute, } as any) -const LayoutBetaRoute = LayoutBetaRouteImport.update({ - id: '/beta', - path: '/beta', - getParentRoute: () => LayoutRoute, +const SecAIdRoute = SecAIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecARoute, } as any) -const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ - id: '/alpha', - path: '/alpha', - getParentRoute: () => LayoutRoute, +const SecAAboutRoute = SecAAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecARoute, } as any) -const marketingPromoRoute = marketingPromoRouteImport.update({ - id: '/(marketing)/promo', - path: '/promo', - getParentRoute: () => rootRouteImport, +const SecASettingsRoute = SecASettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecARoute, } as any) -const marketingPricingRoute = marketingPricingRouteImport.update({ - id: '/(marketing)/pricing', - path: '/pricing', - getParentRoute: () => rootRouteImport, +const SecBIndexRoute = SecBIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecBRoute, +} as any) +const SecBIdRoute = SecBIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecBRoute, +} as any) +const SecBAboutRoute = SecBAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecBRoute, +} as any) +const SecBSettingsRoute = SecBSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecBRoute, +} as any) +const SecCIndexRoute = SecCIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecCRoute, +} as any) +const SecCIdRoute = SecCIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecCRoute, +} as any) +const SecCAboutRoute = SecCAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecCRoute, +} as any) +const SecCSettingsRoute = SecCSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecCRoute, +} as any) +const SecDIndexRoute = SecDIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecDRoute, +} as any) +const SecDIdRoute = SecDIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecDRoute, +} as any) +const SecDAboutRoute = SecDAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecDRoute, +} as any) +const SecDSettingsRoute = SecDSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecDRoute, +} as any) +const SecEIndexRoute = SecEIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecERoute, +} as any) +const SecEIdRoute = SecEIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecERoute, +} as any) +const SecEAboutRoute = SecEAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecERoute, +} as any) +const SecESettingsRoute = SecESettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecERoute, +} as any) +const SecFIndexRoute = SecFIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecFRoute, +} as any) +const SecFIdRoute = SecFIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecFRoute, +} as any) +const SecFAboutRoute = SecFAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecFRoute, +} as any) +const SecFSettingsRoute = SecFSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecFRoute, } as any) export interface FileRoutesByFullPath { @@ -484,46 +484,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/sec-f': { - id: '/sec-f' - path: '/sec-f' - fullPath: '/sec-f' - preLoaderRoute: typeof SecFRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-e': { - id: '/sec-e' - path: '/sec-e' - fullPath: '/sec-e' - preLoaderRoute: typeof SecERouteImport - parentRoute: typeof rootRouteImport - } - '/sec-d': { - id: '/sec-d' - path: '/sec-d' - fullPath: '/sec-d' - preLoaderRoute: typeof SecDRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-c': { - id: '/sec-c' - path: '/sec-c' - fullPath: '/sec-c' - preLoaderRoute: typeof SecCRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-b': { - id: '/sec-b' - path: '/sec-b' - fullPath: '/sec-b' - preLoaderRoute: typeof SecBRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-a': { - id: '/sec-a' - path: '/sec-a' - fullPath: '/sec-a' - preLoaderRoute: typeof SecARouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -533,47 +498,89 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/sec-a': { + id: '/sec-a' + path: '/sec-a' + fullPath: '/sec-a' + preLoaderRoute: typeof SecARouteImport parentRoute: typeof rootRouteImport } - '/sec-f/': { - id: '/sec-f/' - path: '/' - fullPath: '/sec-f/' - preLoaderRoute: typeof SecFIndexRouteImport - parentRoute: typeof SecFRoute + '/sec-b': { + id: '/sec-b' + path: '/sec-b' + fullPath: '/sec-b' + preLoaderRoute: typeof SecBRouteImport + parentRoute: typeof rootRouteImport } - '/sec-e/': { - id: '/sec-e/' - path: '/' - fullPath: '/sec-e/' - preLoaderRoute: typeof SecEIndexRouteImport - parentRoute: typeof SecERoute + '/sec-c': { + id: '/sec-c' + path: '/sec-c' + fullPath: '/sec-c' + preLoaderRoute: typeof SecCRouteImport + parentRoute: typeof rootRouteImport } - '/sec-d/': { - id: '/sec-d/' - path: '/' - fullPath: '/sec-d/' - preLoaderRoute: typeof SecDIndexRouteImport - parentRoute: typeof SecDRoute + '/sec-d': { + id: '/sec-d' + path: '/sec-d' + fullPath: '/sec-d' + preLoaderRoute: typeof SecDRouteImport + parentRoute: typeof rootRouteImport } - '/sec-c/': { - id: '/sec-c/' - path: '/' - fullPath: '/sec-c/' - preLoaderRoute: typeof SecCIndexRouteImport - parentRoute: typeof SecCRoute + '/sec-e': { + id: '/sec-e' + path: '/sec-e' + fullPath: '/sec-e' + preLoaderRoute: typeof SecERouteImport + parentRoute: typeof rootRouteImport } - '/sec-b/': { - id: '/sec-b/' - path: '/' - fullPath: '/sec-b/' - preLoaderRoute: typeof SecBIndexRouteImport - parentRoute: typeof SecBRoute + '/sec-f': { + id: '/sec-f' + path: '/sec-f' + fullPath: '/sec-f' + preLoaderRoute: typeof SecFRouteImport + parentRoute: typeof rootRouteImport + } + '/(marketing)/pricing': { + id: '/(marketing)/pricing' + path: '/pricing' + fullPath: '/pricing' + preLoaderRoute: typeof marketingPricingRouteImport + parentRoute: typeof rootRouteImport + } + '/(marketing)/promo': { + id: '/(marketing)/promo' + path: '/promo' + fullPath: '/promo' + preLoaderRoute: typeof marketingPromoRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/alpha': { + id: '/_layout/alpha' + path: '/alpha' + fullPath: '/alpha' + preLoaderRoute: typeof LayoutAlphaRouteImport + parentRoute: typeof LayoutRoute + } + '/_layout/beta': { + id: '/_layout/beta' + path: '/beta' + fullPath: '/beta' + preLoaderRoute: typeof LayoutBetaRouteImport + parentRoute: typeof LayoutRoute + } + '/files/$': { + id: '/files/$' + path: '/files/$' + fullPath: '/files/$' + preLoaderRoute: typeof FilesSplatRouteImport + parentRoute: typeof rootRouteImport + } + '/release/v{$version}': { + id: '/release/v{$version}' + path: '/release/v{$version}' + fullPath: '/release/v{$version}' + preLoaderRoute: typeof ReleaseVChar123versionChar125RouteImport + parentRoute: typeof rootRouteImport } '/sec-a/': { id: '/sec-a/' @@ -582,125 +589,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof SecAIndexRouteImport parentRoute: typeof SecARoute } - '/sec-f/settings': { - id: '/sec-f/settings' - path: '/settings' - fullPath: '/sec-f/settings' - preLoaderRoute: typeof SecFSettingsRouteImport - parentRoute: typeof SecFRoute - } - '/sec-f/about': { - id: '/sec-f/about' - path: '/about' - fullPath: '/sec-f/about' - preLoaderRoute: typeof SecFAboutRouteImport - parentRoute: typeof SecFRoute - } - '/sec-f/$id': { - id: '/sec-f/$id' - path: '/$id' - fullPath: '/sec-f/$id' - preLoaderRoute: typeof SecFIdRouteImport - parentRoute: typeof SecFRoute - } - '/sec-e/settings': { - id: '/sec-e/settings' - path: '/settings' - fullPath: '/sec-e/settings' - preLoaderRoute: typeof SecESettingsRouteImport - parentRoute: typeof SecERoute - } - '/sec-e/about': { - id: '/sec-e/about' - path: '/about' - fullPath: '/sec-e/about' - preLoaderRoute: typeof SecEAboutRouteImport - parentRoute: typeof SecERoute - } - '/sec-e/$id': { - id: '/sec-e/$id' - path: '/$id' - fullPath: '/sec-e/$id' - preLoaderRoute: typeof SecEIdRouteImport - parentRoute: typeof SecERoute - } - '/sec-d/settings': { - id: '/sec-d/settings' - path: '/settings' - fullPath: '/sec-d/settings' - preLoaderRoute: typeof SecDSettingsRouteImport - parentRoute: typeof SecDRoute - } - '/sec-d/about': { - id: '/sec-d/about' - path: '/about' - fullPath: '/sec-d/about' - preLoaderRoute: typeof SecDAboutRouteImport - parentRoute: typeof SecDRoute - } - '/sec-d/$id': { - id: '/sec-d/$id' - path: '/$id' - fullPath: '/sec-d/$id' - preLoaderRoute: typeof SecDIdRouteImport - parentRoute: typeof SecDRoute - } - '/sec-c/settings': { - id: '/sec-c/settings' - path: '/settings' - fullPath: '/sec-c/settings' - preLoaderRoute: typeof SecCSettingsRouteImport - parentRoute: typeof SecCRoute - } - '/sec-c/about': { - id: '/sec-c/about' - path: '/about' - fullPath: '/sec-c/about' - preLoaderRoute: typeof SecCAboutRouteImport - parentRoute: typeof SecCRoute - } - '/sec-c/$id': { - id: '/sec-c/$id' - path: '/$id' - fullPath: '/sec-c/$id' - preLoaderRoute: typeof SecCIdRouteImport - parentRoute: typeof SecCRoute - } - '/sec-b/settings': { - id: '/sec-b/settings' - path: '/settings' - fullPath: '/sec-b/settings' - preLoaderRoute: typeof SecBSettingsRouteImport - parentRoute: typeof SecBRoute - } - '/sec-b/about': { - id: '/sec-b/about' - path: '/about' - fullPath: '/sec-b/about' - preLoaderRoute: typeof SecBAboutRouteImport - parentRoute: typeof SecBRoute - } - '/sec-b/$id': { - id: '/sec-b/$id' - path: '/$id' - fullPath: '/sec-b/$id' - preLoaderRoute: typeof SecBIdRouteImport - parentRoute: typeof SecBRoute - } - '/sec-a/settings': { - id: '/sec-a/settings' - path: '/settings' - fullPath: '/sec-a/settings' - preLoaderRoute: typeof SecASettingsRouteImport - parentRoute: typeof SecARoute - } - '/sec-a/about': { - id: '/sec-a/about' - path: '/about' - fullPath: '/sec-a/about' - preLoaderRoute: typeof SecAAboutRouteImport - parentRoute: typeof SecARoute - } '/sec-a/$id': { id: '/sec-a/$id' path: '/$id' @@ -708,47 +596,159 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof SecAIdRouteImport parentRoute: typeof SecARoute } - '/release/v{$version}': { - id: '/release/v{$version}' - path: '/release/v{$version}' - fullPath: '/release/v{$version}' - preLoaderRoute: typeof ReleaseVChar123versionChar125RouteImport - parentRoute: typeof rootRouteImport + '/sec-a/about': { + id: '/sec-a/about' + path: '/about' + fullPath: '/sec-a/about' + preLoaderRoute: typeof SecAAboutRouteImport + parentRoute: typeof SecARoute } - '/files/$': { - id: '/files/$' - path: '/files/$' - fullPath: '/files/$' - preLoaderRoute: typeof FilesSplatRouteImport - parentRoute: typeof rootRouteImport + '/sec-a/settings': { + id: '/sec-a/settings' + path: '/settings' + fullPath: '/sec-a/settings' + preLoaderRoute: typeof SecASettingsRouteImport + parentRoute: typeof SecARoute } - '/_layout/beta': { - id: '/_layout/beta' - path: '/beta' - fullPath: '/beta' - preLoaderRoute: typeof LayoutBetaRouteImport - parentRoute: typeof LayoutRoute + '/sec-b/': { + id: '/sec-b/' + path: '/' + fullPath: '/sec-b/' + preLoaderRoute: typeof SecBIndexRouteImport + parentRoute: typeof SecBRoute } - '/_layout/alpha': { - id: '/_layout/alpha' - path: '/alpha' - fullPath: '/alpha' - preLoaderRoute: typeof LayoutAlphaRouteImport - parentRoute: typeof LayoutRoute + '/sec-b/$id': { + id: '/sec-b/$id' + path: '/$id' + fullPath: '/sec-b/$id' + preLoaderRoute: typeof SecBIdRouteImport + parentRoute: typeof SecBRoute } - '/(marketing)/promo': { - id: '/(marketing)/promo' - path: '/promo' - fullPath: '/promo' - preLoaderRoute: typeof marketingPromoRouteImport - parentRoute: typeof rootRouteImport + '/sec-b/about': { + id: '/sec-b/about' + path: '/about' + fullPath: '/sec-b/about' + preLoaderRoute: typeof SecBAboutRouteImport + parentRoute: typeof SecBRoute } - '/(marketing)/pricing': { - id: '/(marketing)/pricing' - path: '/pricing' - fullPath: '/pricing' - preLoaderRoute: typeof marketingPricingRouteImport - parentRoute: typeof rootRouteImport + '/sec-b/settings': { + id: '/sec-b/settings' + path: '/settings' + fullPath: '/sec-b/settings' + preLoaderRoute: typeof SecBSettingsRouteImport + parentRoute: typeof SecBRoute + } + '/sec-c/': { + id: '/sec-c/' + path: '/' + fullPath: '/sec-c/' + preLoaderRoute: typeof SecCIndexRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/$id': { + id: '/sec-c/$id' + path: '/$id' + fullPath: '/sec-c/$id' + preLoaderRoute: typeof SecCIdRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/about': { + id: '/sec-c/about' + path: '/about' + fullPath: '/sec-c/about' + preLoaderRoute: typeof SecCAboutRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/settings': { + id: '/sec-c/settings' + path: '/settings' + fullPath: '/sec-c/settings' + preLoaderRoute: typeof SecCSettingsRouteImport + parentRoute: typeof SecCRoute + } + '/sec-d/': { + id: '/sec-d/' + path: '/' + fullPath: '/sec-d/' + preLoaderRoute: typeof SecDIndexRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/$id': { + id: '/sec-d/$id' + path: '/$id' + fullPath: '/sec-d/$id' + preLoaderRoute: typeof SecDIdRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/about': { + id: '/sec-d/about' + path: '/about' + fullPath: '/sec-d/about' + preLoaderRoute: typeof SecDAboutRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/settings': { + id: '/sec-d/settings' + path: '/settings' + fullPath: '/sec-d/settings' + preLoaderRoute: typeof SecDSettingsRouteImport + parentRoute: typeof SecDRoute + } + '/sec-e/': { + id: '/sec-e/' + path: '/' + fullPath: '/sec-e/' + preLoaderRoute: typeof SecEIndexRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/$id': { + id: '/sec-e/$id' + path: '/$id' + fullPath: '/sec-e/$id' + preLoaderRoute: typeof SecEIdRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/about': { + id: '/sec-e/about' + path: '/about' + fullPath: '/sec-e/about' + preLoaderRoute: typeof SecEAboutRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/settings': { + id: '/sec-e/settings' + path: '/settings' + fullPath: '/sec-e/settings' + preLoaderRoute: typeof SecESettingsRouteImport + parentRoute: typeof SecERoute + } + '/sec-f/': { + id: '/sec-f/' + path: '/' + fullPath: '/sec-f/' + preLoaderRoute: typeof SecFIndexRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/$id': { + id: '/sec-f/$id' + path: '/$id' + fullPath: '/sec-f/$id' + preLoaderRoute: typeof SecFIdRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/about': { + id: '/sec-f/about' + path: '/about' + fullPath: '/sec-f/about' + preLoaderRoute: typeof SecFAboutRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/settings': { + id: '/sec-f/settings' + path: '/settings' + fullPath: '/sec-f/settings' + preLoaderRoute: typeof SecFSettingsRouteImport + parentRoute: typeof SecFRoute } } } diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/vite.config.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/vite.config.ts index dd0bd234e0..542ede131b 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import solid from 'vite-plugin-solid' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -38,6 +39,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav route-tree-scale (solid)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.bench.ts index a767b8d220..331e8e008f 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-route-tree-scale', () => { - const test = setup() +test('client-route-tree-scale', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-route-tree-scale navigation loop (vue)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/main.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/main.tsx index c96d3f3a2e..cae9b54f1d 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/main.tsx +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import * as Vue from 'vue' import { RouterProvider, createRouter } from '@tanstack/vue-router' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -20,8 +22,8 @@ declare module '@tanstack/vue-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const component = const app = Vue.createApp({ diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts index a03c051a79..a12f981bb4 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts @@ -9,68 +9,52 @@ // 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 SecFRouteImport } from './routes/sec-f' -import { Route as SecERouteImport } from './routes/sec-e' -import { Route as SecDRouteImport } from './routes/sec-d' -import { Route as SecCRouteImport } from './routes/sec-c' -import { Route as SecBRouteImport } from './routes/sec-b' -import { Route as SecARouteImport } from './routes/sec-a' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as IndexRouteImport } from './routes/index' -import { Route as SecFIndexRouteImport } from './routes/sec-f.index' -import { Route as SecEIndexRouteImport } from './routes/sec-e.index' -import { Route as SecDIndexRouteImport } from './routes/sec-d.index' -import { Route as SecCIndexRouteImport } from './routes/sec-c.index' -import { Route as SecBIndexRouteImport } from './routes/sec-b.index' -import { Route as SecAIndexRouteImport } from './routes/sec-a.index' -import { Route as SecFSettingsRouteImport } from './routes/sec-f.settings' -import { Route as SecFAboutRouteImport } from './routes/sec-f.about' -import { Route as SecFIdRouteImport } from './routes/sec-f.$id' -import { Route as SecESettingsRouteImport } from './routes/sec-e.settings' -import { Route as SecEAboutRouteImport } from './routes/sec-e.about' -import { Route as SecEIdRouteImport } from './routes/sec-e.$id' -import { Route as SecDSettingsRouteImport } from './routes/sec-d.settings' -import { Route as SecDAboutRouteImport } from './routes/sec-d.about' -import { Route as SecDIdRouteImport } from './routes/sec-d.$id' -import { Route as SecCSettingsRouteImport } from './routes/sec-c.settings' -import { Route as SecCAboutRouteImport } from './routes/sec-c.about' -import { Route as SecCIdRouteImport } from './routes/sec-c.$id' -import { Route as SecBSettingsRouteImport } from './routes/sec-b.settings' -import { Route as SecBAboutRouteImport } from './routes/sec-b.about' -import { Route as SecBIdRouteImport } from './routes/sec-b.$id' -import { Route as SecASettingsRouteImport } from './routes/sec-a.settings' -import { Route as SecAAboutRouteImport } from './routes/sec-a.about' -import { Route as SecAIdRouteImport } from './routes/sec-a.$id' -import { Route as ReleaseVChar123versionChar125RouteImport } from './routes/release.v{$version}' -import { Route as FilesSplatRouteImport } from './routes/files.$' -import { Route as LayoutBetaRouteImport } from './routes/_layout.beta' -import { Route as LayoutAlphaRouteImport } from './routes/_layout.alpha' -import { Route as marketingPromoRouteImport } from './routes/(marketing)/promo' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as SecARouteImport } from './routes/sec-a' +import { Route as SecBRouteImport } from './routes/sec-b' +import { Route as SecCRouteImport } from './routes/sec-c' +import { Route as SecDRouteImport } from './routes/sec-d' +import { Route as SecERouteImport } from './routes/sec-e' +import { Route as SecFRouteImport } from './routes/sec-f' import { Route as marketingPricingRouteImport } from './routes/(marketing)/pricing' +import { Route as marketingPromoRouteImport } from './routes/(marketing)/promo' +import { Route as LayoutAlphaRouteImport } from './routes/_layout.alpha' +import { Route as LayoutBetaRouteImport } from './routes/_layout.beta' +import { Route as FilesSplatRouteImport } from './routes/files.$' +import { Route as ReleaseVChar123versionChar125RouteImport } from './routes/release.v{$version}' +import { Route as SecAIndexRouteImport } from './routes/sec-a.index' +import { Route as SecAIdRouteImport } from './routes/sec-a.$id' +import { Route as SecAAboutRouteImport } from './routes/sec-a.about' +import { Route as SecASettingsRouteImport } from './routes/sec-a.settings' +import { Route as SecBIndexRouteImport } from './routes/sec-b.index' +import { Route as SecBIdRouteImport } from './routes/sec-b.$id' +import { Route as SecBAboutRouteImport } from './routes/sec-b.about' +import { Route as SecBSettingsRouteImport } from './routes/sec-b.settings' +import { Route as SecCIndexRouteImport } from './routes/sec-c.index' +import { Route as SecCIdRouteImport } from './routes/sec-c.$id' +import { Route as SecCAboutRouteImport } from './routes/sec-c.about' +import { Route as SecCSettingsRouteImport } from './routes/sec-c.settings' +import { Route as SecDIndexRouteImport } from './routes/sec-d.index' +import { Route as SecDIdRouteImport } from './routes/sec-d.$id' +import { Route as SecDAboutRouteImport } from './routes/sec-d.about' +import { Route as SecDSettingsRouteImport } from './routes/sec-d.settings' +import { Route as SecEIndexRouteImport } from './routes/sec-e.index' +import { Route as SecEIdRouteImport } from './routes/sec-e.$id' +import { Route as SecEAboutRouteImport } from './routes/sec-e.about' +import { Route as SecESettingsRouteImport } from './routes/sec-e.settings' +import { Route as SecFIndexRouteImport } from './routes/sec-f.index' +import { Route as SecFIdRouteImport } from './routes/sec-f.$id' +import { Route as SecFAboutRouteImport } from './routes/sec-f.about' +import { Route as SecFSettingsRouteImport } from './routes/sec-f.settings' -const SecFRoute = SecFRouteImport.update({ - id: '/sec-f', - path: '/sec-f', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const SecERoute = SecERouteImport.update({ - id: '/sec-e', - path: '/sec-e', - getParentRoute: () => rootRouteImport, -} as any) -const SecDRoute = SecDRouteImport.update({ - id: '/sec-d', - path: '/sec-d', - getParentRoute: () => rootRouteImport, -} as any) -const SecCRoute = SecCRouteImport.update({ - id: '/sec-c', - path: '/sec-c', - getParentRoute: () => rootRouteImport, -} as any) -const SecBRoute = SecBRouteImport.update({ - id: '/sec-b', - path: '/sec-b', +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', getParentRoute: () => rootRouteImport, } as any) const SecARoute = SecARouteImport.update({ @@ -78,134 +62,55 @@ const SecARoute = SecARouteImport.update({ path: '/sec-a', getParentRoute: () => rootRouteImport, } as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', +const SecBRoute = SecBRouteImport.update({ + id: '/sec-b', + path: '/sec-b', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SecCRoute = SecCRouteImport.update({ + id: '/sec-c', + path: '/sec-c', getParentRoute: () => rootRouteImport, } as any) -const SecFIndexRoute = SecFIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecFRoute, +const SecDRoute = SecDRouteImport.update({ + id: '/sec-d', + path: '/sec-d', + getParentRoute: () => rootRouteImport, } as any) -const SecEIndexRoute = SecEIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecERoute, +const SecERoute = SecERouteImport.update({ + id: '/sec-e', + path: '/sec-e', + getParentRoute: () => rootRouteImport, } as any) -const SecDIndexRoute = SecDIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecDRoute, +const SecFRoute = SecFRouteImport.update({ + id: '/sec-f', + path: '/sec-f', + getParentRoute: () => rootRouteImport, } as any) -const SecCIndexRoute = SecCIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecCRoute, +const marketingPricingRoute = marketingPricingRouteImport.update({ + id: '/(marketing)/pricing', + path: '/pricing', + getParentRoute: () => rootRouteImport, } as any) -const SecBIndexRoute = SecBIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecBRoute, +const marketingPromoRoute = marketingPromoRouteImport.update({ + id: '/(marketing)/promo', + path: '/promo', + getParentRoute: () => rootRouteImport, } as any) -const SecAIndexRoute = SecAIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SecARoute, +const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ + id: '/alpha', + path: '/alpha', + getParentRoute: () => LayoutRoute, } as any) -const SecFSettingsRoute = SecFSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecFRoute, +const LayoutBetaRoute = LayoutBetaRouteImport.update({ + id: '/beta', + path: '/beta', + getParentRoute: () => LayoutRoute, } as any) -const SecFAboutRoute = SecFAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecFRoute, -} as any) -const SecFIdRoute = SecFIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecFRoute, -} as any) -const SecESettingsRoute = SecESettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecERoute, -} as any) -const SecEAboutRoute = SecEAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecERoute, -} as any) -const SecEIdRoute = SecEIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecERoute, -} as any) -const SecDSettingsRoute = SecDSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecDRoute, -} as any) -const SecDAboutRoute = SecDAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecDRoute, -} as any) -const SecDIdRoute = SecDIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecDRoute, -} as any) -const SecCSettingsRoute = SecCSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecCRoute, -} as any) -const SecCAboutRoute = SecCAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecCRoute, -} as any) -const SecCIdRoute = SecCIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecCRoute, -} as any) -const SecBSettingsRoute = SecBSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecBRoute, -} as any) -const SecBAboutRoute = SecBAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecBRoute, -} as any) -const SecBIdRoute = SecBIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecBRoute, -} as any) -const SecASettingsRoute = SecASettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => SecARoute, -} as any) -const SecAAboutRoute = SecAAboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => SecARoute, -} as any) -const SecAIdRoute = SecAIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => SecARoute, +const FilesSplatRoute = FilesSplatRouteImport.update({ + id: '/files/$', + path: '/files/$', + getParentRoute: () => rootRouteImport, } as any) const ReleaseVChar123versionChar125Route = ReleaseVChar123versionChar125RouteImport.update({ @@ -213,30 +118,125 @@ const ReleaseVChar123versionChar125Route = path: '/release/v{$version}', getParentRoute: () => rootRouteImport, } as any) -const FilesSplatRoute = FilesSplatRouteImport.update({ - id: '/files/$', - path: '/files/$', - getParentRoute: () => rootRouteImport, +const SecAIndexRoute = SecAIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecARoute, } as any) -const LayoutBetaRoute = LayoutBetaRouteImport.update({ - id: '/beta', - path: '/beta', - getParentRoute: () => LayoutRoute, +const SecAIdRoute = SecAIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecARoute, } as any) -const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ - id: '/alpha', - path: '/alpha', - getParentRoute: () => LayoutRoute, +const SecAAboutRoute = SecAAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecARoute, } as any) -const marketingPromoRoute = marketingPromoRouteImport.update({ - id: '/(marketing)/promo', - path: '/promo', - getParentRoute: () => rootRouteImport, +const SecASettingsRoute = SecASettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecARoute, } as any) -const marketingPricingRoute = marketingPricingRouteImport.update({ - id: '/(marketing)/pricing', - path: '/pricing', - getParentRoute: () => rootRouteImport, +const SecBIndexRoute = SecBIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecBRoute, +} as any) +const SecBIdRoute = SecBIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecBRoute, +} as any) +const SecBAboutRoute = SecBAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecBRoute, +} as any) +const SecBSettingsRoute = SecBSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecBRoute, +} as any) +const SecCIndexRoute = SecCIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecCRoute, +} as any) +const SecCIdRoute = SecCIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecCRoute, +} as any) +const SecCAboutRoute = SecCAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecCRoute, +} as any) +const SecCSettingsRoute = SecCSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecCRoute, +} as any) +const SecDIndexRoute = SecDIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecDRoute, +} as any) +const SecDIdRoute = SecDIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecDRoute, +} as any) +const SecDAboutRoute = SecDAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecDRoute, +} as any) +const SecDSettingsRoute = SecDSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecDRoute, +} as any) +const SecEIndexRoute = SecEIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecERoute, +} as any) +const SecEIdRoute = SecEIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecERoute, +} as any) +const SecEAboutRoute = SecEAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecERoute, +} as any) +const SecESettingsRoute = SecESettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecERoute, +} as any) +const SecFIndexRoute = SecFIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecFRoute, +} as any) +const SecFIdRoute = SecFIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecFRoute, +} as any) +const SecFAboutRoute = SecFAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecFRoute, +} as any) +const SecFSettingsRoute = SecFSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecFRoute, } as any) export interface FileRoutesByFullPath { @@ -484,46 +484,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/sec-f': { - id: '/sec-f' - path: '/sec-f' - fullPath: '/sec-f' - preLoaderRoute: typeof SecFRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-e': { - id: '/sec-e' - path: '/sec-e' - fullPath: '/sec-e' - preLoaderRoute: typeof SecERouteImport - parentRoute: typeof rootRouteImport - } - '/sec-d': { - id: '/sec-d' - path: '/sec-d' - fullPath: '/sec-d' - preLoaderRoute: typeof SecDRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-c': { - id: '/sec-c' - path: '/sec-c' - fullPath: '/sec-c' - preLoaderRoute: typeof SecCRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-b': { - id: '/sec-b' - path: '/sec-b' - fullPath: '/sec-b' - preLoaderRoute: typeof SecBRouteImport - parentRoute: typeof rootRouteImport - } - '/sec-a': { - id: '/sec-a' - path: '/sec-a' - fullPath: '/sec-a' - preLoaderRoute: typeof SecARouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -533,47 +498,89 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/sec-a': { + id: '/sec-a' + path: '/sec-a' + fullPath: '/sec-a' + preLoaderRoute: typeof SecARouteImport parentRoute: typeof rootRouteImport } - '/sec-f/': { - id: '/sec-f/' - path: '/' - fullPath: '/sec-f/' - preLoaderRoute: typeof SecFIndexRouteImport - parentRoute: typeof SecFRoute + '/sec-b': { + id: '/sec-b' + path: '/sec-b' + fullPath: '/sec-b' + preLoaderRoute: typeof SecBRouteImport + parentRoute: typeof rootRouteImport } - '/sec-e/': { - id: '/sec-e/' - path: '/' - fullPath: '/sec-e/' - preLoaderRoute: typeof SecEIndexRouteImport - parentRoute: typeof SecERoute + '/sec-c': { + id: '/sec-c' + path: '/sec-c' + fullPath: '/sec-c' + preLoaderRoute: typeof SecCRouteImport + parentRoute: typeof rootRouteImport } - '/sec-d/': { - id: '/sec-d/' - path: '/' - fullPath: '/sec-d/' - preLoaderRoute: typeof SecDIndexRouteImport - parentRoute: typeof SecDRoute + '/sec-d': { + id: '/sec-d' + path: '/sec-d' + fullPath: '/sec-d' + preLoaderRoute: typeof SecDRouteImport + parentRoute: typeof rootRouteImport } - '/sec-c/': { - id: '/sec-c/' - path: '/' - fullPath: '/sec-c/' - preLoaderRoute: typeof SecCIndexRouteImport - parentRoute: typeof SecCRoute + '/sec-e': { + id: '/sec-e' + path: '/sec-e' + fullPath: '/sec-e' + preLoaderRoute: typeof SecERouteImport + parentRoute: typeof rootRouteImport } - '/sec-b/': { - id: '/sec-b/' - path: '/' - fullPath: '/sec-b/' - preLoaderRoute: typeof SecBIndexRouteImport - parentRoute: typeof SecBRoute + '/sec-f': { + id: '/sec-f' + path: '/sec-f' + fullPath: '/sec-f' + preLoaderRoute: typeof SecFRouteImport + parentRoute: typeof rootRouteImport + } + '/(marketing)/pricing': { + id: '/(marketing)/pricing' + path: '/pricing' + fullPath: '/pricing' + preLoaderRoute: typeof marketingPricingRouteImport + parentRoute: typeof rootRouteImport + } + '/(marketing)/promo': { + id: '/(marketing)/promo' + path: '/promo' + fullPath: '/promo' + preLoaderRoute: typeof marketingPromoRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/alpha': { + id: '/_layout/alpha' + path: '/alpha' + fullPath: '/alpha' + preLoaderRoute: typeof LayoutAlphaRouteImport + parentRoute: typeof LayoutRoute + } + '/_layout/beta': { + id: '/_layout/beta' + path: '/beta' + fullPath: '/beta' + preLoaderRoute: typeof LayoutBetaRouteImport + parentRoute: typeof LayoutRoute + } + '/files/$': { + id: '/files/$' + path: '/files/$' + fullPath: '/files/$' + preLoaderRoute: typeof FilesSplatRouteImport + parentRoute: typeof rootRouteImport + } + '/release/v{$version}': { + id: '/release/v{$version}' + path: '/release/v{$version}' + fullPath: '/release/v{$version}' + preLoaderRoute: typeof ReleaseVChar123versionChar125RouteImport + parentRoute: typeof rootRouteImport } '/sec-a/': { id: '/sec-a/' @@ -582,125 +589,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof SecAIndexRouteImport parentRoute: typeof SecARoute } - '/sec-f/settings': { - id: '/sec-f/settings' - path: '/settings' - fullPath: '/sec-f/settings' - preLoaderRoute: typeof SecFSettingsRouteImport - parentRoute: typeof SecFRoute - } - '/sec-f/about': { - id: '/sec-f/about' - path: '/about' - fullPath: '/sec-f/about' - preLoaderRoute: typeof SecFAboutRouteImport - parentRoute: typeof SecFRoute - } - '/sec-f/$id': { - id: '/sec-f/$id' - path: '/$id' - fullPath: '/sec-f/$id' - preLoaderRoute: typeof SecFIdRouteImport - parentRoute: typeof SecFRoute - } - '/sec-e/settings': { - id: '/sec-e/settings' - path: '/settings' - fullPath: '/sec-e/settings' - preLoaderRoute: typeof SecESettingsRouteImport - parentRoute: typeof SecERoute - } - '/sec-e/about': { - id: '/sec-e/about' - path: '/about' - fullPath: '/sec-e/about' - preLoaderRoute: typeof SecEAboutRouteImport - parentRoute: typeof SecERoute - } - '/sec-e/$id': { - id: '/sec-e/$id' - path: '/$id' - fullPath: '/sec-e/$id' - preLoaderRoute: typeof SecEIdRouteImport - parentRoute: typeof SecERoute - } - '/sec-d/settings': { - id: '/sec-d/settings' - path: '/settings' - fullPath: '/sec-d/settings' - preLoaderRoute: typeof SecDSettingsRouteImport - parentRoute: typeof SecDRoute - } - '/sec-d/about': { - id: '/sec-d/about' - path: '/about' - fullPath: '/sec-d/about' - preLoaderRoute: typeof SecDAboutRouteImport - parentRoute: typeof SecDRoute - } - '/sec-d/$id': { - id: '/sec-d/$id' - path: '/$id' - fullPath: '/sec-d/$id' - preLoaderRoute: typeof SecDIdRouteImport - parentRoute: typeof SecDRoute - } - '/sec-c/settings': { - id: '/sec-c/settings' - path: '/settings' - fullPath: '/sec-c/settings' - preLoaderRoute: typeof SecCSettingsRouteImport - parentRoute: typeof SecCRoute - } - '/sec-c/about': { - id: '/sec-c/about' - path: '/about' - fullPath: '/sec-c/about' - preLoaderRoute: typeof SecCAboutRouteImport - parentRoute: typeof SecCRoute - } - '/sec-c/$id': { - id: '/sec-c/$id' - path: '/$id' - fullPath: '/sec-c/$id' - preLoaderRoute: typeof SecCIdRouteImport - parentRoute: typeof SecCRoute - } - '/sec-b/settings': { - id: '/sec-b/settings' - path: '/settings' - fullPath: '/sec-b/settings' - preLoaderRoute: typeof SecBSettingsRouteImport - parentRoute: typeof SecBRoute - } - '/sec-b/about': { - id: '/sec-b/about' - path: '/about' - fullPath: '/sec-b/about' - preLoaderRoute: typeof SecBAboutRouteImport - parentRoute: typeof SecBRoute - } - '/sec-b/$id': { - id: '/sec-b/$id' - path: '/$id' - fullPath: '/sec-b/$id' - preLoaderRoute: typeof SecBIdRouteImport - parentRoute: typeof SecBRoute - } - '/sec-a/settings': { - id: '/sec-a/settings' - path: '/settings' - fullPath: '/sec-a/settings' - preLoaderRoute: typeof SecASettingsRouteImport - parentRoute: typeof SecARoute - } - '/sec-a/about': { - id: '/sec-a/about' - path: '/about' - fullPath: '/sec-a/about' - preLoaderRoute: typeof SecAAboutRouteImport - parentRoute: typeof SecARoute - } '/sec-a/$id': { id: '/sec-a/$id' path: '/$id' @@ -708,47 +596,159 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof SecAIdRouteImport parentRoute: typeof SecARoute } - '/release/v{$version}': { - id: '/release/v{$version}' - path: '/release/v{$version}' - fullPath: '/release/v{$version}' - preLoaderRoute: typeof ReleaseVChar123versionChar125RouteImport - parentRoute: typeof rootRouteImport + '/sec-a/about': { + id: '/sec-a/about' + path: '/about' + fullPath: '/sec-a/about' + preLoaderRoute: typeof SecAAboutRouteImport + parentRoute: typeof SecARoute } - '/files/$': { - id: '/files/$' - path: '/files/$' - fullPath: '/files/$' - preLoaderRoute: typeof FilesSplatRouteImport - parentRoute: typeof rootRouteImport + '/sec-a/settings': { + id: '/sec-a/settings' + path: '/settings' + fullPath: '/sec-a/settings' + preLoaderRoute: typeof SecASettingsRouteImport + parentRoute: typeof SecARoute } - '/_layout/beta': { - id: '/_layout/beta' - path: '/beta' - fullPath: '/beta' - preLoaderRoute: typeof LayoutBetaRouteImport - parentRoute: typeof LayoutRoute + '/sec-b/': { + id: '/sec-b/' + path: '/' + fullPath: '/sec-b/' + preLoaderRoute: typeof SecBIndexRouteImport + parentRoute: typeof SecBRoute } - '/_layout/alpha': { - id: '/_layout/alpha' - path: '/alpha' - fullPath: '/alpha' - preLoaderRoute: typeof LayoutAlphaRouteImport - parentRoute: typeof LayoutRoute + '/sec-b/$id': { + id: '/sec-b/$id' + path: '/$id' + fullPath: '/sec-b/$id' + preLoaderRoute: typeof SecBIdRouteImport + parentRoute: typeof SecBRoute } - '/(marketing)/promo': { - id: '/(marketing)/promo' - path: '/promo' - fullPath: '/promo' - preLoaderRoute: typeof marketingPromoRouteImport - parentRoute: typeof rootRouteImport + '/sec-b/about': { + id: '/sec-b/about' + path: '/about' + fullPath: '/sec-b/about' + preLoaderRoute: typeof SecBAboutRouteImport + parentRoute: typeof SecBRoute } - '/(marketing)/pricing': { - id: '/(marketing)/pricing' - path: '/pricing' - fullPath: '/pricing' - preLoaderRoute: typeof marketingPricingRouteImport - parentRoute: typeof rootRouteImport + '/sec-b/settings': { + id: '/sec-b/settings' + path: '/settings' + fullPath: '/sec-b/settings' + preLoaderRoute: typeof SecBSettingsRouteImport + parentRoute: typeof SecBRoute + } + '/sec-c/': { + id: '/sec-c/' + path: '/' + fullPath: '/sec-c/' + preLoaderRoute: typeof SecCIndexRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/$id': { + id: '/sec-c/$id' + path: '/$id' + fullPath: '/sec-c/$id' + preLoaderRoute: typeof SecCIdRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/about': { + id: '/sec-c/about' + path: '/about' + fullPath: '/sec-c/about' + preLoaderRoute: typeof SecCAboutRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/settings': { + id: '/sec-c/settings' + path: '/settings' + fullPath: '/sec-c/settings' + preLoaderRoute: typeof SecCSettingsRouteImport + parentRoute: typeof SecCRoute + } + '/sec-d/': { + id: '/sec-d/' + path: '/' + fullPath: '/sec-d/' + preLoaderRoute: typeof SecDIndexRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/$id': { + id: '/sec-d/$id' + path: '/$id' + fullPath: '/sec-d/$id' + preLoaderRoute: typeof SecDIdRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/about': { + id: '/sec-d/about' + path: '/about' + fullPath: '/sec-d/about' + preLoaderRoute: typeof SecDAboutRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/settings': { + id: '/sec-d/settings' + path: '/settings' + fullPath: '/sec-d/settings' + preLoaderRoute: typeof SecDSettingsRouteImport + parentRoute: typeof SecDRoute + } + '/sec-e/': { + id: '/sec-e/' + path: '/' + fullPath: '/sec-e/' + preLoaderRoute: typeof SecEIndexRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/$id': { + id: '/sec-e/$id' + path: '/$id' + fullPath: '/sec-e/$id' + preLoaderRoute: typeof SecEIdRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/about': { + id: '/sec-e/about' + path: '/about' + fullPath: '/sec-e/about' + preLoaderRoute: typeof SecEAboutRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/settings': { + id: '/sec-e/settings' + path: '/settings' + fullPath: '/sec-e/settings' + preLoaderRoute: typeof SecESettingsRouteImport + parentRoute: typeof SecERoute + } + '/sec-f/': { + id: '/sec-f/' + path: '/' + fullPath: '/sec-f/' + preLoaderRoute: typeof SecFIndexRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/$id': { + id: '/sec-f/$id' + path: '/$id' + fullPath: '/sec-f/$id' + preLoaderRoute: typeof SecFIdRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/about': { + id: '/sec-f/about' + path: '/about' + fullPath: '/sec-f/about' + preLoaderRoute: typeof SecFAboutRouteImport + parentRoute: typeof SecFRoute + } + '/sec-f/settings': { + id: '/sec-f/settings' + path: '/settings' + fullPath: '/sec-f/settings' + preLoaderRoute: typeof SecFSettingsRouteImport + parentRoute: typeof SecFRoute } } } diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/vite.config.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/vite.config.ts index a547406198..189ba1de99 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/vite.config.ts @@ -4,6 +4,7 @@ import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -37,6 +38,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav route-tree-scale (vue)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts b/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts index c534611bd0..0b38f7bddb 100644 --- a/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-search-params', () => { - const test = setup() +test('client-search-params', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-search-params navigation loop (react)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/search-params/react/src/main.tsx b/benchmarks/client-nav/scenarios/search-params/react/src/main.tsx index a68ef7bbb2..b10d53554b 100644 --- a/benchmarks/client-nav/scenarios/search-params/react/src/main.tsx +++ b/benchmarks/client-nav/scenarios/search-params/react/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import { RouterProvider, createRouter } from '@tanstack/react-router' import { createRoot } from 'react-dom/client' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -21,8 +23,8 @@ declare module '@tanstack/react-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const reactRoot = createRoot(container) reactRoot.render() diff --git a/benchmarks/client-nav/scenarios/search-params/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/search-params/react/src/routeTree.gen.ts index 7380b704e1..cff9dca167 100644 --- a/benchmarks/client-nav/scenarios/search-params/react/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/search-params/react/src/routeTree.gen.ts @@ -9,13 +9,13 @@ // 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 ProductsRouteImport } from './routes/products' -import { Route as CatalogRouteImport } from './routes/catalog' import { Route as IndexRouteImport } from './routes/index' +import { Route as CatalogRouteImport } from './routes/catalog' +import { Route as ProductsRouteImport } from './routes/products' -const ProductsRoute = ProductsRouteImport.update({ - id: '/products', - path: '/products', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const CatalogRoute = CatalogRouteImport.update({ @@ -23,9 +23,9 @@ const CatalogRoute = CatalogRouteImport.update({ path: '/catalog', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ProductsRoute = ProductsRouteImport.update({ + id: '/products', + path: '/products', getParentRoute: () => rootRouteImport, } as any) @@ -61,11 +61,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/products': { - id: '/products' - path: '/products' - fullPath: '/products' - preLoaderRoute: typeof ProductsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/catalog': { @@ -75,11 +75,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof CatalogRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/products': { + id: '/products' + path: '/products' + fullPath: '/products' + preLoaderRoute: typeof ProductsRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/client-nav/scenarios/search-params/react/vite.config.ts b/benchmarks/client-nav/scenarios/search-params/react/vite.config.ts index b220ae7d0d..0318a10815 100644 --- a/benchmarks/client-nav/scenarios/search-params/react/vite.config.ts +++ b/benchmarks/client-nav/scenarios/search-params/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import react from '@vitejs/plugin-react' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -32,6 +33,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav search-params (react)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts index df6a24dc15..caa626c596 100644 --- a/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-search-params', () => { - const test = setup() +test('client-search-params', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-search-params navigation loop (solid)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/search-params/solid/src/main.tsx b/benchmarks/client-nav/scenarios/search-params/solid/src/main.tsx index e95846e12d..25071f7979 100644 --- a/benchmarks/client-nav/scenarios/search-params/solid/src/main.tsx +++ b/benchmarks/client-nav/scenarios/search-params/solid/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import { render } from 'solid-js/web' import { RouterProvider, createRouter } from '@tanstack/solid-router' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -21,8 +23,8 @@ declare module '@tanstack/solid-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const unmount = render(() => , container) diff --git a/benchmarks/client-nav/scenarios/search-params/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/search-params/solid/src/routeTree.gen.ts index 96d211d64c..b15beed09b 100644 --- a/benchmarks/client-nav/scenarios/search-params/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/search-params/solid/src/routeTree.gen.ts @@ -9,13 +9,13 @@ // 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 ProductsRouteImport } from './routes/products' -import { Route as CatalogRouteImport } from './routes/catalog' import { Route as IndexRouteImport } from './routes/index' +import { Route as CatalogRouteImport } from './routes/catalog' +import { Route as ProductsRouteImport } from './routes/products' -const ProductsRoute = ProductsRouteImport.update({ - id: '/products', - path: '/products', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const CatalogRoute = CatalogRouteImport.update({ @@ -23,9 +23,9 @@ const CatalogRoute = CatalogRouteImport.update({ path: '/catalog', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ProductsRoute = ProductsRouteImport.update({ + id: '/products', + path: '/products', getParentRoute: () => rootRouteImport, } as any) @@ -61,11 +61,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/products': { - id: '/products' - path: '/products' - fullPath: '/products' - preLoaderRoute: typeof ProductsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/catalog': { @@ -75,11 +75,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof CatalogRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/products': { + id: '/products' + path: '/products' + fullPath: '/products' + preLoaderRoute: typeof ProductsRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/client-nav/scenarios/search-params/solid/vite.config.ts b/benchmarks/client-nav/scenarios/search-params/solid/vite.config.ts index c2f4b32806..511fd49466 100644 --- a/benchmarks/client-nav/scenarios/search-params/solid/vite.config.ts +++ b/benchmarks/client-nav/scenarios/search-params/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import solid from 'vite-plugin-solid' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -35,6 +36,7 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav search-params (solid)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts index 0b394bbe27..728d2779e8 100644 --- a/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -describe('client-search-params', () => { - const test = setup() +test('client-search-params', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-search-params navigation loop (vue)', + benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await test.tick() + await scenario.tick() } + await scenario.finishBatch() }, - { - ...benchOptions, - setup: test.before, - teardown: test.after, - }, - ) + ).run(benchOptions) }) diff --git a/benchmarks/client-nav/scenarios/search-params/vue/src/main.tsx b/benchmarks/client-nav/scenarios/search-params/vue/src/main.tsx index 1454b8d547..65bade775c 100644 --- a/benchmarks/client-nav/scenarios/search-params/vue/src/main.tsx +++ b/benchmarks/client-nav/scenarios/search-params/vue/src/main.tsx @@ -1,10 +1,12 @@ +import type { RouterHistory } from '@tanstack/history' import * as Vue from 'vue' import { RouterProvider, createRouter } from '@tanstack/vue-router' import { routeTree } from './routeTree.gen' -export function createTestRouter() { +export function createTestRouter(history: RouterHistory) { return createRouter({ routeTree, + history, scrollRestoration: true, // Key the scroll-restoration cache by pathname instead of the default // random per-entry location key: with push navigations the default mints @@ -21,8 +23,8 @@ declare module '@tanstack/vue-router' { } } -export function mountTestApp(container: HTMLElement) { - const router = createTestRouter() +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) const component = const app = Vue.createApp({ diff --git a/benchmarks/client-nav/scenarios/search-params/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/search-params/vue/src/routeTree.gen.ts index b95b667803..f73b84ebe7 100644 --- a/benchmarks/client-nav/scenarios/search-params/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/search-params/vue/src/routeTree.gen.ts @@ -9,13 +9,13 @@ // 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 ProductsRouteImport } from './routes/products' -import { Route as CatalogRouteImport } from './routes/catalog' import { Route as IndexRouteImport } from './routes/index' +import { Route as CatalogRouteImport } from './routes/catalog' +import { Route as ProductsRouteImport } from './routes/products' -const ProductsRoute = ProductsRouteImport.update({ - id: '/products', - path: '/products', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const CatalogRoute = CatalogRouteImport.update({ @@ -23,9 +23,9 @@ const CatalogRoute = CatalogRouteImport.update({ path: '/catalog', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ProductsRoute = ProductsRouteImport.update({ + id: '/products', + path: '/products', getParentRoute: () => rootRouteImport, } as any) @@ -61,11 +61,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/products': { - id: '/products' - path: '/products' - fullPath: '/products' - preLoaderRoute: typeof ProductsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/catalog': { @@ -75,11 +75,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof CatalogRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/products': { + id: '/products' + path: '/products' + fullPath: '/products' + preLoaderRoute: typeof ProductsRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/client-nav/scenarios/search-params/vue/vite.config.ts b/benchmarks/client-nav/scenarios/search-params/vue/vite.config.ts index 9a3b82d066..27490b276a 100644 --- a/benchmarks/client-nav/scenarios/search-params/vue/vite.config.ts +++ b/benchmarks/client-nav/scenarios/search-params/vue/vite.config.ts @@ -4,6 +4,7 @@ import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackRouter } from '@tanstack/router-plugin/vite' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -34,6 +35,7 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav search-params (vue)', watch: false, environment: 'jsdom', diff --git a/benchmarks/client-nav/solid/speed.bench.ts b/benchmarks/client-nav/solid/speed.bench.ts index 34791180ce..d629da17a8 100644 --- a/benchmarks/client-nav/solid/speed.bench.ts +++ b/benchmarks/client-nav/solid/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' import { setup } from './setup' -describe('client-nav', () => { - const test = setup() +test('client-nav', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-side navigation loop (solid)', + { beforeAll: scenario.before, afterAll: scenario.after }, async () => { for (let i = 0; i < 10; i++) { - await test.tick() + await scenario.tick() } }, - { - warmupIterations: 100, - time: 10_000, - setup: test.before, - teardown: test.after, - }, - ) + ).run({ + warmupIterations: 100, + time: 10_000, + }) }) diff --git a/benchmarks/client-nav/solid/vite.config.ts b/benchmarks/client-nav/solid/vite.config.ts index bd11fe8de9..0c26b32f5f 100644 --- a/benchmarks/client-nav/solid/vite.config.ts +++ b/benchmarks/client-nav/solid/vite.config.ts @@ -2,6 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import solid from 'vite-plugin-solid' import codspeedPlugin from '@codspeed/vitest-plugin' +import { cpuSimulationExecArgv } from '../../cpu-simulation' // Anchor the project root to the package directory so this config resolves // identically when run directly and as part of an aggregate `projects` config. @@ -31,10 +32,12 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav (solid)', watch: false, environment: 'jsdom', setupFiles: [`${rootDir}vitest.setup.ts`], + benchmark: { include: ['solid/speed.bench.ts'] }, server: { deps: { inline: [/@solidjs/, /@tanstack\/solid-store/], diff --git a/benchmarks/client-nav/vue/speed.bench.ts b/benchmarks/client-nav/vue/speed.bench.ts index f9e532f5ba..503e91e7b7 100644 --- a/benchmarks/client-nav/vue/speed.bench.ts +++ b/benchmarks/client-nav/vue/speed.bench.ts @@ -1,34 +1,19 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' +import { test } from 'vitest' import { setup } from './setup' -describe('client-nav', () => { - const test = setup() +test('client-nav', async ({ bench }) => { + const scenario = setup() - /** - * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, - * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. - * - * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, - * but it does support `beforeAll` and `afterAll`. - * - * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. - */ - - beforeAll(test.before) - afterAll(test.after) - - bench( + await bench( 'client-side navigation loop (vue)', + { beforeAll: scenario.before, afterAll: scenario.after }, async () => { for (let i = 0; i < 10; i++) { - await test.tick() + await scenario.tick() } }, - { - warmupIterations: 100, - time: 10_000, - setup: test.before, - teardown: test.after, - }, - ) + ).run({ + warmupIterations: 100, + time: 10_000, + }) }) diff --git a/benchmarks/client-nav/vue/vite.config.ts b/benchmarks/client-nav/vue/vite.config.ts index 4c44c09fdd..78d8ae5638 100644 --- a/benchmarks/client-nav/vue/vite.config.ts +++ b/benchmarks/client-nav/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' import codspeedPlugin from '@codspeed/vitest-plugin' +import { cpuSimulationExecArgv } from '../../cpu-simulation' // Anchor the project root to the package directory so this config resolves // identically when run directly and as part of an aggregate `projects` config. @@ -30,9 +31,11 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav (vue)', watch: false, environment: 'jsdom', setupFiles: [`${rootDir}vitest.setup.ts`], + benchmark: { include: ['vue/speed.bench.ts'] }, }, }) diff --git a/benchmarks/cpu-simulation.ts b/benchmarks/cpu-simulation.ts new file mode 100644 index 0000000000..9b8859f74d --- /dev/null +++ b/benchmarks/cpu-simulation.ts @@ -0,0 +1,53 @@ +function codspeedRunnerMode() { + return process.env.CODSPEED_ENV === undefined + ? undefined + : process.env.CODSPEED_RUNNER_MODE +} + +/** + * Whether CodSpeed's simulation or memory instrument drives the run. Both + * measure one invocation after a few warmup calls instead of sampling. + */ +export function isCodSpeedAnalysis() { + const mode = codspeedRunnerMode() + return ( + mode === 'simulation' || mode === 'instrumentation' || mode === 'memory' + ) +} + +/** Extra worker flags for CodSpeed CPU simulation, not walltime benchmarks. */ +export function cpuSimulationExecArgv() { + const mode = codspeedRunnerMode() + if (mode === 'simulation' || mode === 'instrumentation') { + // CodSpeed supplies --no-opt, which only disables TurboFan on Node 24. + // Maglev can still compile and inline hot functions between measured runs. + // Compile baseline code on first use, so warmup does not leave functions + // near Sparkplug's later tier-up/batch-compilation thresholds. + // V8 renamed --scavenge-task in Node 20; CodSpeed's old flag is omitted. + // Keep minor GC tied to allocations instead of scheduled foreground tasks. + // Fix the initial/minimum old-generation allocation budget. This can skip + // automatic full collections below the budget; minor GC remains enabled. + return [ + '--no-maglev', + '--always-sparkplug', + '--no-minor-gc-task', + '--initial-old-space-size=512', + ] + } + return [] +} + +/** + * Per-bench lifecycle for apps that a bench prepares and disposes outside + * timing. CodSpeed measures one invocation, so each invocation gets fresh + * state. Tinybench samples thousands of iterations and keeps one instance per + * warmup/run phase instead of preparing it for every iteration. + */ +export function benchLifecycle(hooks: { + before: () => Promise | void + after: () => Promise | void +}) { + return isCodSpeedAnalysis() + ? { beforeEach: hooks.before, afterEach: hooks.after } + : { beforeAll: hooks.before, afterAll: hooks.after } +} diff --git a/benchmarks/memory/README.md b/benchmarks/memory/README.md index cf871f3439..18b68768f9 100644 --- a/benchmarks/memory/README.md +++ b/benchmarks/memory/README.md @@ -2,7 +2,7 @@ Dedicated memory benchmarks for TanStack Router / Start, measured with the CodSpeed **memory instrument** (`mode: memory` in -`.github/workflows/client-nav-benchmarks.yml`). The workflow runs on every +`.github/workflows/benchmarks.yml`). The workflow runs on every push to `main` except docs/examples/e2e-only pushes: CodSpeed compares a PR against the run on its merge-base commit, and a main commit without a run makes CodSpeed silently fall back to an older base — a single outlier base run then @@ -34,8 +34,8 @@ benchmarks/memory// One app per scenario; apps and bench names are stable once landed (CodSpeed continuity). Never grow an existing scenario for a new case — add a scenario. `setup.ts` imports the built app and exports the concrete workload; -`memory.bench.ts` registers `bench(...)` directly, and `memory.flame.ts` runs the -same workload through the Flame profiler. +`memory.bench.ts` registers it with Vitest's `bench` test fixture, and +`memory.flame.ts` runs the same workload through the Flame profiler. ## How the memory instrument executes a bench @@ -43,40 +43,98 @@ same workload through the Flame profiler. after a forced GC. Under plain `vitest bench` the suites only smoke-test: timing output is meaningless; real numbers come from CodSpeed. - Under CodSpeed the bench fn runs several warmup invocations plus the - measured one **on the same mount**, so bench fns must be idempotent and - module-level counters/LCGs are used where ids must never repeat across - invocations. -- Plain `vitest bench` never runs suite hooks (`beforeAll`/`afterAll`) and - only honors tinybench's `setup`/`teardown` options; the CodSpeed runner - does the exact opposite. Client benches therefore register **both** — in - any given mode exactly one pair runs. -- The process runs with V8 determinism flags (predictable GC schedule, - `--no-opt`). Never call `global.gc()` manually in **churn** scenarios — - their signal is accumulation across iterations, which a forced collection - masks. **Peak** scenarios do the opposite: they set - `pinGcBetweenIterations` on the request loop so a collection runs between - iterations. Their signal is the footprint of a single request, and without - pinned GC points the measured peak flips by a whole payload depending on - whether iteration i's garbage is collected before iteration i+1 allocates. - Because of `--no-opt`, allocation counts overstate production; numbers are - for regression tracking, not absolute claims. + measured one. The bench's `beforeEach`/`afterEach` hooks + (`memoryBenchHooks`) run around every invocation, outside the measurement + window: client workloads mount a fresh app before each invocation and tear + it down afterward. This prevents warmup navigation history and caches from + changing the starting state. Plain `vitest bench` runs the same hooks around + its warmup and measured iteration. Module-level counters/LCGs keep generated + URLs unique across invocations. +- Workload `run` functions must be `async` functions. CodSpeed's Vitest 5 + provider awaits only `AsyncFunction`s; a plain function that returns a + promise would be measured only up to its first suspension. +- Worker flags live in `runtime.ts` and apply only to the CodSpeed memory + instrument. They supplement the integration's predictable execution flags; + the retained overrides are described below. +- Before each CodSpeed invocation, the `beforeEach` hook yields to the event + loop, outside the measurement marker and before CodSpeed forces GC. Promise-only + warmup chains can keep WeakRef targets alive through a collection in the same + job. Client app setup also runs before the forced GC. +- Do not force GC inside a measured request loop or poll `heapUsed` to choose + how much work to do. Both introduce allocator activity from the harness into + the measurement. Footprint scenarios run exactly one large request per + invocation; churn scenarios retain their fixed sequential request counts. +- Error-path cases use separate isolated workers so one case's module and + allocator history cannot contaminate the next case. - Keep each bench under **~1.5M allocations** (instrument overhead grows past 2M); this is the main constraint when tuning iteration counts. +## Worker settings + +All scenarios use [`memoryConfig`](./runtime.ts). It adds these flags only in +memory mode: + +- `--no-maglev` +- `--no-flush-bytecode` +- `--no-minor-gc-task` +- `--no-incremental-marking` +- `--initial-old-space-size=512` + +`--jitless` was removed after repeated CI comparisons. Ten unchanged-commit +repetitions with the last four flags kept all 48 peak-memory results within 1% +(worst spread: 0.834%). With JIT enabled, all 16 subsets of the four flags were +tested. Removing bytecode, minor-GC-task, incremental-marking, or heap-budget +overrides from this profile produced worst client peak spreads of 6.616%, 2.714%, +2.109%, and 10.669%, respectively. Smaller combinations also exceeded 1% in at +least one tracked metric. This supports retaining the four-flag profile; it does +not establish that every override is required in every individual scenario. + +A server-only heap-budget profile initially passed five repetitions, but further +confirmation produced a 24.46% server peak outlier. That configuration was +rejected. Allocated bytes and allocation counts remain imperfectly repeatable: +a client confirmation with the retained four flags showed a 6.77% allocated-byte +spread and a 5.91% allocation-count spread. Client peaks remained within 0.834% +across all 15 observations with the retained profile. Experiment details and CI runs are recorded in +[PR #8260](https://github.com/TanStack/router/pull/8260). + +These settings trade production GC behavior for repeatable regression signals. +They suppress bytecode reclamation and change collection scheduling. The 512 MiB +initial/minimum old-generation allocation budget can postpone automatic full +collections. This does not preallocate 512 MiB, and the smallest sufficient budget +was not determined. Results describe this controlled worker profile, not a +production application's absolute memory footprint. + +CodSpeed's `--no-opt` only disables TurboFan on Node 24 (V8 13); Maglev still +compiles. Under CodSpeed's `--predictable` there is no background compilation, +so Maglev compiles run synchronously inside whichever request triggers them, and +the forced GC before the measured call can discard optimized code so recompiles +land inside the measured window. Maglev's malloc'd Zone scratch (32 KiB +segments) then dominates allocation metrics, and its size depends on +per-process feedback state. `--no-maglev` was added for this: the bimodal ++32,792 B / +1 allocation in `mem server error-paths unmatched (react)` was one +Maglev Zone segment allocated while compiling React Fizz's per-request stream +`write` closure, and compiler scratch made up ~97% of that bench's allocated +bytes. Retained-object measurements are unaffected because Zone memory is freed +after each compile. The repeatability figures above predate this flag. + ## Bench shapes and signals -- **Churn (leak detector):** N sequential iterations at steady state. If one - iteration leaks L bytes, peak grows by ~N·L; healthy builds show a flat - timeline floor independent of N. Tuning check: doubling N must leave peak - roughly unchanged. -- **Peak (footprint):** one (or very few) large operations; peak memory - scaling with the workload is the signal. +- **Churn:** a fixed number of sequential operations, measuring native + allocation activity and peak outstanding native allocations. +- **Peak (footprint):** one large operation, measuring its native footprint. + +CodSpeed reports native allocator activity, not individual JavaScript object +allocations or retained JS heap size. V8 can reuse heap pages without a visible +native allocation. These benchmarks can detect native buffering and allocator +regressions, but a flat graph does not establish that route data or JS objects +are collectable. Absolute numbers include Node/framework/jsdom activity under +benchmark-specific V8 settings; compare identical harness versions. ## Scenarios ### Server -| Scenario | Shape | Guards against | +| Scenario | Shape | Exercises | | ----------------------- | ----- | --------------------------------------------------------- | | `request-churn` | churn | cross-request retention in document SSR (unique URLs) | | `server-fn-churn` | churn | retention in the server-function RPC path | @@ -88,7 +146,7 @@ same workload through the Flame profiler. ### Client -| Scenario | Shape | Guards against | +| Scenario | Shape | Exercises | | ------------------------- | ----- | -------------------------------------------------------- | | `navigation-churn` | churn | per-navigation retention at steady state | | `unique-location-churn` | churn | unbounded href/search-keyed caches (never-repeated URLs) | @@ -103,14 +161,10 @@ same workload through the Flame profiler. server response is fully consumed before the next request. Pairing a single navigation with its render signal via `Promise.all([navigate, rendered])` is fine — never overlap distinct work items. -- Randomness only via the seeded LCG in `bench-utils.ts`; no `Math.random`, - `Date.now`, or timers with a nonzero delay — anywhere async ordering must be - staged (`streaming-peak`'s deferred sections, `aborted-requests`' deferred - loader data and post-abort drain), chain **0ms `setTimeout` hops** and count - event-loop turns instead. A wall-clock delay races renderer work differently - depending on runner load and instrumentation overhead, which makes the - single measured run non-reproducible; 0ms hops fire in registration order in - the timers phase, so the interleaving is a pure function of the schedule. +- Randomness only via the seeded LCG in `bench-utils.ts`. Deferred streaming + uses counted zero-delay timer hops to stage work. Timers still depend on the + event loop, so validate repeatability on CI instead of assuming deterministic + ordering from a zero delay alone. - Sanity assertions run once at module load and throw on wrong status/markers, so a bench can never silently measure the wrong thing. - Server requests follow `benchmarks/ssr` conventions: document GETs send @@ -184,7 +238,7 @@ pnpm --filter @benchmarks/memory-client clean:profiles ``` Client memory benches are useful for regression tracking of router/React/jsdom -integration behavior, especially retained route/cache data. They are not pure +integration behavior and native allocation activity. They are not pure browser-memory measurements, and local Flame attribution can include jsdom, React DOM, and profiler shutdown frames. @@ -200,3 +254,20 @@ WITH_INSTRUMENTATION=1 codspeed run --mode memory -- pnpm nx run @benchmarks/mem WITH_INSTRUMENTATION=1 codspeed run --mode memory -- pnpm nx run @benchmarks/memory-client:test:perf:solid WITH_INSTRUMENTATION=1 codspeed run --mode memory -- pnpm nx run @benchmarks/memory-client:test:perf:vue ``` + +Run the benchmark workflow on an experiment branch: + +```bash +gh workflow run benchmarks.yml --ref +``` + +Repeat at the same commit, using distinct branch names if runs should overlap +(the workflow serializes runs on the same ref). Compare all 48 fresh memory +results: 18 client and 30 server. Exclude CPU simulation results, inherited +CodSpeed results, and failed or incomplete repetitions. For each workload, calculate +`100 * (max / min - 1)` across runs for peak bytes, allocated bytes, and +allocation counts; aggregate averages hide unstable cases. + +Observed spreads below 1% establish repeatability in the tested sample, not a +bound on future runs. Changes to worker flags or workload lifecycles establish +new measurement baselines. diff --git a/benchmarks/memory/client/bench-utils.ts b/benchmarks/memory/client/bench-utils.ts index 0cbaedbd71..785e8fac7f 100644 --- a/benchmarks/memory/client/bench-utils.ts +++ b/benchmarks/memory/client/bench-utils.ts @@ -1,3 +1,5 @@ +export { memoryBenchHooks } from '../turn' + export const memoryBenchOptions = { iterations: 1, warmupIterations: 1, diff --git a/benchmarks/memory/client/benchmark.ts b/benchmarks/memory/client/benchmark.ts index 8b877b0740..463047f4d9 100644 --- a/benchmarks/memory/client/benchmark.ts +++ b/benchmarks/memory/client/benchmark.ts @@ -1,6 +1,10 @@ export interface ClientMemoryWorkload { name: string before?: () => Promise | void + /** + * Must be an `async` function: CodSpeed's Vitest 5 provider awaits only + * `AsyncFunction`s and otherwise measures just the synchronous part. + */ run: () => Promise | void sanity: () => Promise | void after?: () => Promise | void diff --git a/benchmarks/memory/client/package.json b/benchmarks/memory/client/package.json index 2624b9e4e5..4dc6246183 100644 --- a/benchmarks/memory/client/package.json +++ b/benchmarks/memory/client/package.json @@ -22,7 +22,7 @@ "vue": "^3.5.16" }, "devDependencies": { - "@codspeed/vitest-plugin": "^5.5.0", + "@codspeed/vitest-plugin": "^6.0.1", "@datadog/pprof": "^5.13.2", "@platformatic/flame": "^1.6.0", "@testing-library/react": "^16.2.0", @@ -30,11 +30,14 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "@types/jsdom": "28.0.0", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", "jsdom": "29.1.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11", - "vitest": "^4.1.4" + "vitest": "catalog:" }, "nx": { "targets": { @@ -199,7 +202,7 @@ "build:react" ], "options": { - "command": "NODE_ENV=production vitest bench --config ./vitest.react.config.ts", + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.react.config.ts", "cwd": "benchmarks/memory/client" } }, @@ -211,7 +214,7 @@ "build:solid" ], "options": { - "command": "NODE_ENV=production vitest bench --config ./vitest.solid.config.ts", + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.solid.config.ts", "cwd": "benchmarks/memory/client" } }, @@ -223,12 +226,12 @@ "build:vue" ], "options": { - "command": "NODE_ENV=production vitest bench --config ./vitest.vue.config.ts", + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.vue.config.ts", "cwd": "benchmarks/memory/client" } }, "test:types": { - "executor": "nx:noop", + "executor": "nx:run-commands", "dependsOn": [ { "projects": [ @@ -253,6 +256,17 @@ ], "target": "test:types:client" } + ], + "options": { + "command": "tsc -p ./tsconfig.json --noEmit", + "cwd": "benchmarks/memory/client" + }, + "inputs": [ + "default", + "^production", + "{workspaceRoot}/eslint.config.js", + "dependentTaskOutputs", + "{workspaceRoot}/benchmarks/memory/*.ts" ] } } diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.bench.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.bench.ts index e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -describe('memory', () => { - if (workload.before && workload.after) { - beforeAll(workload.before) - afterAll(workload.after) - - bench(workload.name, workload.run, { - ...memoryBenchOptions, - setup: workload.before, - teardown: workload.after, - }) - return - } - - bench(workload.name, workload.run, memoryBenchOptions) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).run( + memoryBenchOptions, + ) }) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/react/vite.config.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/react/vite.config.ts index 048a9cc833..0f05cedf40 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/vite.config.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/react/vite.config.ts @@ -2,6 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), name: '@benchmarks/memory-client interrupted-navigations (react)', watch: false, environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.bench.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.bench.ts index e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -describe('memory', () => { - if (workload.before && workload.after) { - beforeAll(workload.before) - afterAll(workload.after) - - bench(workload.name, workload.run, { - ...memoryBenchOptions, - setup: workload.before, - teardown: workload.after, - }) - return - } - - bench(workload.name, workload.run, memoryBenchOptions) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).run( + memoryBenchOptions, + ) }) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/vite.config.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/vite.config.ts index e710e0fd12..26ff0b5c8c 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/vite.config.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/vite.config.ts @@ -2,6 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), name: '@benchmarks/memory-client interrupted-navigations (solid)', watch: false, environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.bench.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.bench.ts index e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -describe('memory', () => { - if (workload.before && workload.after) { - beforeAll(workload.before) - afterAll(workload.after) - - bench(workload.name, workload.run, { - ...memoryBenchOptions, - setup: workload.before, - teardown: workload.after, - }) - return - } - - bench(workload.name, workload.run, memoryBenchOptions) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).run( + memoryBenchOptions, + ) }) diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/fast.$id.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/fast.$id.tsx index 3bd820bd07..f6dc9ac3bd 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/fast.$id.tsx +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/fast.$id.tsx @@ -1,6 +1,19 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { fixedTimestamp } from '../../../slow-loaders' +const FastComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+ {`${data.value.kind}:${data.value.id}:${data.value.ts}`} +
+ ) + }, +}) + export const Route = createFileRoute('/fast/$id')({ loader: ({ params }: { params: { id: string } }) => ({ id: params.id, @@ -9,13 +22,3 @@ export const Route = createFileRoute('/fast/$id')({ }), component: FastComponent, }) - -function FastComponent() { - const data = Route.useLoaderData() - - return ( -
- {`${data.value.kind}:${data.value.id}:${data.value.ts}`} -
- ) -} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/slow.$id.tsx b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/slow.$id.tsx index 68885fb918..3b5bb75ede 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/slow.$id.tsx +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/src/routes/slow.$id.tsx @@ -1,6 +1,19 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { getSlowLoaderDeferred } from '../../../slow-loaders' +const SlowComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+ {`${data.value.kind}:${data.value.id}:${data.value.ts}`} +
+ ) + }, +}) + export const Route = createFileRoute('/slow/$id')({ loader: async ({ params }: { params: { id: string } }) => { const deferred = getSlowLoaderDeferred(params.id) @@ -9,13 +22,3 @@ export const Route = createFileRoute('/slow/$id')({ }, component: SlowComponent, }) - -function SlowComponent() { - const data = Route.useLoaderData() - - return ( -
- {`${data.value.kind}:${data.value.id}:${data.value.ts}`} -
- ) -} diff --git a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/vite.config.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/vite.config.ts index b2912ce9d1..02574908d2 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/vite.config.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -28,9 +29,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), name: '@benchmarks/memory-client interrupted-navigations (vue)', watch: false, environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/memory.bench.ts b/benchmarks/memory/client/scenarios/loader-data-retention/react/memory.bench.ts index e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/loader-data-retention/react/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -describe('memory', () => { - if (workload.before && workload.after) { - beforeAll(workload.before) - afterAll(workload.after) - - bench(workload.name, workload.run, { - ...memoryBenchOptions, - setup: workload.before, - teardown: workload.after, - }) - return - } - - bench(workload.name, workload.run, memoryBenchOptions) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).run( + memoryBenchOptions, + ) }) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/react/vite.config.ts b/benchmarks/memory/client/scenarios/loader-data-retention/react/vite.config.ts index 555e5f5612..8630417936 100644 --- a/benchmarks/memory/client/scenarios/loader-data-retention/react/vite.config.ts +++ b/benchmarks/memory/client/scenarios/loader-data-retention/react/vite.config.ts @@ -2,6 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), name: '@benchmarks/memory-client loader-data-retention (react)', watch: false, environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/memory.bench.ts b/benchmarks/memory/client/scenarios/loader-data-retention/solid/memory.bench.ts index e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/loader-data-retention/solid/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -describe('memory', () => { - if (workload.before && workload.after) { - beforeAll(workload.before) - afterAll(workload.after) - - bench(workload.name, workload.run, { - ...memoryBenchOptions, - setup: workload.before, - teardown: workload.after, - }) - return - } - - bench(workload.name, workload.run, memoryBenchOptions) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).run( + memoryBenchOptions, + ) }) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/solid/vite.config.ts b/benchmarks/memory/client/scenarios/loader-data-retention/solid/vite.config.ts index 58d6b77acc..5dfd5b53fe 100644 --- a/benchmarks/memory/client/scenarios/loader-data-retention/solid/vite.config.ts +++ b/benchmarks/memory/client/scenarios/loader-data-retention/solid/vite.config.ts @@ -2,6 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), name: '@benchmarks/memory-client loader-data-retention (solid)', watch: false, environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/memory.bench.ts b/benchmarks/memory/client/scenarios/loader-data-retention/vue/memory.bench.ts index e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/loader-data-retention/vue/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -describe('memory', () => { - if (workload.before && workload.after) { - beforeAll(workload.before) - afterAll(workload.after) - - bench(workload.name, workload.run, { - ...memoryBenchOptions, - setup: workload.before, - teardown: workload.after, - }) - return - } - - bench(workload.name, workload.run, memoryBenchOptions) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).run( + memoryBenchOptions, + ) }) diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/page.$id.tsx b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/page.$id.tsx index 9f4b3c4470..38f1d2614c 100644 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/page.$id.tsx +++ b/benchmarks/memory/client/scenarios/loader-data-retention/vue/src/routes/page.$id.tsx @@ -1,22 +1,25 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { createLoaderData } from '../../../loader-data' +const PageComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+ {`${data.value.id}:${data.value.records.length}`} +
+ ) + }, +}) + export const Route = createFileRoute('/page/$id')({ loader: ({ params }: { params: { id: string } }) => createLoaderData(params.id), component: PageComponent, }) - -function PageComponent() { - const data = Route.useLoaderData() - - return ( -
- {`${data.value.id}:${data.value.records.length}`} -
- ) -} diff --git a/benchmarks/memory/client/scenarios/loader-data-retention/vue/vite.config.ts b/benchmarks/memory/client/scenarios/loader-data-retention/vue/vite.config.ts index bbf2fd02d8..006636eaa0 100644 --- a/benchmarks/memory/client/scenarios/loader-data-retention/vue/vite.config.ts +++ b/benchmarks/memory/client/scenarios/loader-data-retention/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -28,9 +29,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), name: '@benchmarks/memory-client loader-data-retention (vue)', watch: false, environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/memory.bench.ts b/benchmarks/memory/client/scenarios/mount-unmount/react/memory.bench.ts index e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/mount-unmount/react/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -describe('memory', () => { - if (workload.before && workload.after) { - beforeAll(workload.before) - afterAll(workload.after) - - bench(workload.name, workload.run, { - ...memoryBenchOptions, - setup: workload.before, - teardown: workload.after, - }) - return - } - - bench(workload.name, workload.run, memoryBenchOptions) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).run( + memoryBenchOptions, + ) }) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/react/vite.config.ts b/benchmarks/memory/client/scenarios/mount-unmount/react/vite.config.ts index bb0f3c2e0a..a08352a837 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/vite.config.ts +++ b/benchmarks/memory/client/scenarios/mount-unmount/react/vite.config.ts @@ -2,6 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), name: '@benchmarks/memory-client mount-unmount (react)', watch: false, environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.bench.ts b/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.bench.ts index e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -describe('memory', () => { - if (workload.before && workload.after) { - beforeAll(workload.before) - afterAll(workload.after) - - bench(workload.name, workload.run, { - ...memoryBenchOptions, - setup: workload.before, - teardown: workload.after, - }) - return - } - - bench(workload.name, workload.run, memoryBenchOptions) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).run( + memoryBenchOptions, + ) }) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/solid/vite.config.ts b/benchmarks/memory/client/scenarios/mount-unmount/solid/vite.config.ts index 5f0ab26252..33699639de 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/vite.config.ts +++ b/benchmarks/memory/client/scenarios/mount-unmount/solid/vite.config.ts @@ -2,6 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), name: '@benchmarks/memory-client mount-unmount (solid)', watch: false, environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.bench.ts b/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.bench.ts index e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -describe('memory', () => { - if (workload.before && workload.after) { - beforeAll(workload.before) - afterAll(workload.after) - - bench(workload.name, workload.run, { - ...memoryBenchOptions, - setup: workload.before, - teardown: workload.after, - }) - return - } - - bench(workload.name, workload.run, memoryBenchOptions) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).run( + memoryBenchOptions, + ) }) diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routes/a.tsx b/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routes/a.tsx index cbcd543ce5..0dd650e1dd 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routes/a.tsx +++ b/benchmarks/memory/client/scenarios/mount-unmount/vue/src/routes/a.tsx @@ -1,12 +1,15 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' +const AComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () =>
{data.value.id}
+ }, +}) + export const Route = createFileRoute('/a')({ loader: () => ({ id: 'a' }), component: AComponent, }) - -function AComponent() { - const data = Route.useLoaderData() - - return
{data.value.id}
-} diff --git a/benchmarks/memory/client/scenarios/mount-unmount/vue/vite.config.ts b/benchmarks/memory/client/scenarios/mount-unmount/vue/vite.config.ts index 0f7573a408..a3f0eeaa8c 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/vite.config.ts +++ b/benchmarks/memory/client/scenarios/mount-unmount/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -28,9 +29,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), name: '@benchmarks/memory-client mount-unmount (vue)', watch: false, environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/memory.bench.ts b/benchmarks/memory/client/scenarios/navigation-churn/react/memory.bench.ts index e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/navigation-churn/react/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -describe('memory', () => { - if (workload.before && workload.after) { - beforeAll(workload.before) - afterAll(workload.after) - - bench(workload.name, workload.run, { - ...memoryBenchOptions, - setup: workload.before, - teardown: workload.after, - }) - return - } - - bench(workload.name, workload.run, memoryBenchOptions) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).run( + memoryBenchOptions, + ) }) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/react/vite.config.ts b/benchmarks/memory/client/scenarios/navigation-churn/react/vite.config.ts index b05b999297..eef60a658e 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/vite.config.ts +++ b/benchmarks/memory/client/scenarios/navigation-churn/react/vite.config.ts @@ -2,6 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), name: '@benchmarks/memory-client navigation-churn (react)', watch: false, environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.bench.ts b/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.bench.ts index e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -describe('memory', () => { - if (workload.before && workload.after) { - beforeAll(workload.before) - afterAll(workload.after) - - bench(workload.name, workload.run, { - ...memoryBenchOptions, - setup: workload.before, - teardown: workload.after, - }) - return - } - - bench(workload.name, workload.run, memoryBenchOptions) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).run( + memoryBenchOptions, + ) }) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/solid/vite.config.ts b/benchmarks/memory/client/scenarios/navigation-churn/solid/vite.config.ts index 6b6735891a..7dfb186b2e 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/vite.config.ts +++ b/benchmarks/memory/client/scenarios/navigation-churn/solid/vite.config.ts @@ -2,6 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), name: '@benchmarks/memory-client navigation-churn (solid)', watch: false, environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.bench.ts b/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.bench.ts index e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -describe('memory', () => { - if (workload.before && workload.after) { - beforeAll(workload.before) - afterAll(workload.after) - - bench(workload.name, workload.run, { - ...memoryBenchOptions, - setup: workload.before, - teardown: workload.after, - }) - return - } - - bench(workload.name, workload.run, memoryBenchOptions) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).run( + memoryBenchOptions, + ) }) diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/a.tsx b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/a.tsx index 183228e748..c1a9cfb244 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/a.tsx +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/a.tsx @@ -1,16 +1,19 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' const fixedTimestamp = 1_700_000_000_000 +const AComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
{`${data.value.name}:${data.value.ts}`}
+ ) + }, +}) + export const Route = createFileRoute('/a')({ loader: () => ({ name: 'a', ts: fixedTimestamp }), component: AComponent, }) - -function AComponent() { - const data = Route.useLoaderData() - - return ( -
{`${data.value.name}:${data.value.ts}`}
- ) -} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/b.tsx b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/b.tsx index 3a18ec97a9..3a20799f3b 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/b.tsx +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/src/routes/b.tsx @@ -1,16 +1,19 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' const fixedTimestamp = 1_700_000_000_000 +const BComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
{`${data.value.name}:${data.value.ts}`}
+ ) + }, +}) + export const Route = createFileRoute('/b')({ loader: () => ({ name: 'b', ts: fixedTimestamp }), component: BComponent, }) - -function BComponent() { - const data = Route.useLoaderData() - - return ( -
{`${data.value.name}:${data.value.ts}`}
- ) -} diff --git a/benchmarks/memory/client/scenarios/navigation-churn/vue/vite.config.ts b/benchmarks/memory/client/scenarios/navigation-churn/vue/vite.config.ts index d26ce23d07..b3bdd39dd2 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/vite.config.ts +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -28,9 +29,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), name: '@benchmarks/memory-client navigation-churn (vue)', watch: false, environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/memory.bench.ts b/benchmarks/memory/client/scenarios/preload-churn/react/memory.bench.ts index e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/react/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/react/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -describe('memory', () => { - if (workload.before && workload.after) { - beforeAll(workload.before) - afterAll(workload.after) - - bench(workload.name, workload.run, { - ...memoryBenchOptions, - setup: workload.before, - teardown: workload.after, - }) - return - } - - bench(workload.name, workload.run, memoryBenchOptions) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).run( + memoryBenchOptions, + ) }) diff --git a/benchmarks/memory/client/scenarios/preload-churn/react/vite.config.ts b/benchmarks/memory/client/scenarios/preload-churn/react/vite.config.ts index f9c426656b..c12995f68e 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/react/vite.config.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/react/vite.config.ts @@ -2,6 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), name: '@benchmarks/memory-client preload-churn (react)', watch: false, environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/preload-churn/shared.ts b/benchmarks/memory/client/scenarios/preload-churn/shared.ts index 8cea4aca81..68fdfedd3f 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/shared.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/shared.ts @@ -35,18 +35,14 @@ type PreloadRouter = { subscribe: (event: 'onRendered', listener: () => void) => () => void } -// Fixed id for the eviction navigations interleaved into the bench loop; its -// payload is a constant-size steady-state resident, never part of the signal. +// Reuse one navigation target while evicting the distinct preloaded routes. const evictionItemId = 'nav-evict' const preloadChurnIterations = 200 // A navigation commit is what triggers the router's clearExpiredCache -- // preloaded matches (defaultPreloadGcTime: 0) are only evicted then, never -// during a preload-only loop. Interleaving a navigation every few preloads is -// what makes the flat floor assert "eviction releases preloaded payloads". +// during a preload-only loop. Interleave navigation to exercise eviction. const preloadsPerEvictionNavigation = 10 -// Module-level so ids stay unique across runner invocations on one mount; a -// per-invocation LCG would replay identical ids, and every preload after the -// first invocation would dedupe against cachedMatches instead of doing work. +// Keep generated URLs unique across warmup and measured invocations. const benchmarkRandom = createDeterministicRandom(0x706c6f61) let preloadCounter = 0 diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/memory.bench.ts b/benchmarks/memory/client/scenarios/preload-churn/solid/memory.bench.ts index e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/solid/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -describe('memory', () => { - if (workload.before && workload.after) { - beforeAll(workload.before) - afterAll(workload.after) - - bench(workload.name, workload.run, { - ...memoryBenchOptions, - setup: workload.before, - teardown: workload.after, - }) - return - } - - bench(workload.name, workload.run, memoryBenchOptions) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).run( + memoryBenchOptions, + ) }) diff --git a/benchmarks/memory/client/scenarios/preload-churn/solid/vite.config.ts b/benchmarks/memory/client/scenarios/preload-churn/solid/vite.config.ts index c86a6fcbb3..efc75d2b93 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/vite.config.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/solid/vite.config.ts @@ -2,6 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), name: '@benchmarks/memory-client preload-churn (solid)', watch: false, environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/memory.bench.ts b/benchmarks/memory/client/scenarios/preload-churn/vue/memory.bench.ts index e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/vue/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -describe('memory', () => { - if (workload.before && workload.after) { - beforeAll(workload.before) - afterAll(workload.after) - - bench(workload.name, workload.run, { - ...memoryBenchOptions, - setup: workload.before, - teardown: workload.after, - }) - return - } - - bench(workload.name, workload.run, memoryBenchOptions) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).run( + memoryBenchOptions, + ) }) diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/items.$id.tsx b/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/items.$id.tsx index 2a29245926..08254e173e 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/items.$id.tsx +++ b/benchmarks/memory/client/scenarios/preload-churn/vue/src/routes/items.$id.tsx @@ -1,6 +1,19 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { createItemPayload, trackItemLoaderCall } from '../../../item-payload' +const ItemComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+ {`${data.value.id}:${data.value.byteLength}`} +
+ ) + }, +}) + export const Route = createFileRoute('/items/$id')({ loader: ({ params }: { params: { id: string } }) => { trackItemLoaderCall(params.id) @@ -8,13 +21,3 @@ export const Route = createFileRoute('/items/$id')({ }, component: ItemComponent, }) - -function ItemComponent() { - const data = Route.useLoaderData() - - return ( -
- {`${data.value.id}:${data.value.byteLength}`} -
- ) -} diff --git a/benchmarks/memory/client/scenarios/preload-churn/vue/vite.config.ts b/benchmarks/memory/client/scenarios/preload-churn/vue/vite.config.ts index ea7ed7b695..3d56089ba7 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/vite.config.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -28,9 +29,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), name: '@benchmarks/memory-client preload-churn (vue)', watch: false, environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/react/memory.bench.ts b/benchmarks/memory/client/scenarios/unique-location-churn/react/memory.bench.ts index e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/unique-location-churn/react/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -describe('memory', () => { - if (workload.before && workload.after) { - beforeAll(workload.before) - afterAll(workload.after) - - bench(workload.name, workload.run, { - ...memoryBenchOptions, - setup: workload.before, - teardown: workload.after, - }) - return - } - - bench(workload.name, workload.run, memoryBenchOptions) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).run( + memoryBenchOptions, + ) }) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/react/vite.config.ts b/benchmarks/memory/client/scenarios/unique-location-churn/react/vite.config.ts index f424c57cef..7ee67bfe30 100644 --- a/benchmarks/memory/client/scenarios/unique-location-churn/react/vite.config.ts +++ b/benchmarks/memory/client/scenarios/unique-location-churn/react/vite.config.ts @@ -2,6 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), name: '@benchmarks/memory-client unique-location-churn (react)', watch: false, environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/solid/memory.bench.ts b/benchmarks/memory/client/scenarios/unique-location-churn/solid/memory.bench.ts index e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/unique-location-churn/solid/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -describe('memory', () => { - if (workload.before && workload.after) { - beforeAll(workload.before) - afterAll(workload.after) - - bench(workload.name, workload.run, { - ...memoryBenchOptions, - setup: workload.before, - teardown: workload.after, - }) - return - } - - bench(workload.name, workload.run, memoryBenchOptions) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).run( + memoryBenchOptions, + ) }) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/solid/vite.config.ts b/benchmarks/memory/client/scenarios/unique-location-churn/solid/vite.config.ts index d4acf0019a..4db90da2d2 100644 --- a/benchmarks/memory/client/scenarios/unique-location-churn/solid/vite.config.ts +++ b/benchmarks/memory/client/scenarios/unique-location-churn/solid/vite.config.ts @@ -2,6 +2,7 @@ import { fileURLToPath } from 'node:url' import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -26,9 +27,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), name: '@benchmarks/memory-client unique-location-churn (solid)', watch: false, environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/memory.bench.ts b/benchmarks/memory/client/scenarios/unique-location-churn/vue/memory.bench.ts index e645ab38f1..43ab822de3 100644 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/unique-location-churn/vue/memory.bench.ts @@ -1,21 +1,14 @@ -import { afterAll, beforeAll, bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-client/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -describe('memory', () => { - if (workload.before && workload.after) { - beforeAll(workload.before) - afterAll(workload.after) - - bench(workload.name, workload.run, { - ...memoryBenchOptions, - setup: workload.before, - teardown: workload.after, - }) - return - } - - bench(workload.name, workload.run, memoryBenchOptions) +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(workload), workload.run).run( + memoryBenchOptions, + ) }) diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routes/items.$id.tsx b/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routes/items.$id.tsx index 1854367142..e796ee14d1 100644 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routes/items.$id.tsx +++ b/benchmarks/memory/client/scenarios/unique-location-churn/vue/src/routes/items.$id.tsx @@ -1,9 +1,22 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' type ItemSearch = { q: string } +const ItemComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
{`${data.value.id}:${data.value.q}:${data.value.checksum}`}
+ ) + }, +}) + export const Route = createFileRoute('/items/$id')({ validateSearch: (search: Record): ItemSearch => ({ q: typeof search.q === 'string' ? search.q : '', @@ -22,13 +35,3 @@ export const Route = createFileRoute('/items/$id')({ }), component: ItemComponent, }) - -function ItemComponent() { - const data = Route.useLoaderData() - - return ( -
{`${data.value.id}:${data.value.q}:${data.value.checksum}`}
- ) -} diff --git a/benchmarks/memory/client/scenarios/unique-location-churn/vue/vite.config.ts b/benchmarks/memory/client/scenarios/unique-location-churn/vue/vite.config.ts index 423126019b..d074d571b9 100644 --- a/benchmarks/memory/client/scenarios/unique-location-churn/vue/vite.config.ts +++ b/benchmarks/memory/client/scenarios/unique-location-churn/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import vue from '@vitejs/plugin-vue' import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -28,9 +29,9 @@ export default defineConfig({ }, }, test: { + ...memoryConfig('client'), name: '@benchmarks/memory-client unique-location-churn (vue)', watch: false, environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], }, }) diff --git a/benchmarks/memory/client/tsconfig.json b/benchmarks/memory/client/tsconfig.json index 9280d5c42f..eefc5c581e 100644 --- a/benchmarks/memory/client/tsconfig.json +++ b/benchmarks/memory/client/tsconfig.json @@ -3,5 +3,10 @@ "compilerOptions": { "types": ["node", "vite/client", "vitest/globals"] }, - "include": ["bench-utils.ts", "lifecycle.ts", "vitest.setup.ts"] + "include": [ + "bench-utils.ts", + "lifecycle.ts", + "vitest.setup.ts", + "scenarios/*/shared.ts" + ] } diff --git a/benchmarks/memory/runtime.ts b/benchmarks/memory/runtime.ts new file mode 100644 index 0000000000..010149b4df --- /dev/null +++ b/benchmarks/memory/runtime.ts @@ -0,0 +1,36 @@ +import { fileURLToPath } from 'node:url' +import { isMemoryInstrumented } from './turn' + +/** Worker settings for the CodSpeed memory instrument. */ +export function memoryExecArgv() { + if (!isMemoryInstrumented()) { + return [] + } + + // CodSpeed supplies --no-opt, which only disables TurboFan on Node 24. + // Under --predictable, Maglev compilations run synchronously inside the + // request that triggers them, and the forced GC before the measured call can + // discard optimized code so recompiles land in the measured window. Their + // malloc'd Zone scratch (32 KiB segments) then dominates allocation metrics + // and depends on per-process feedback state. + // Limit variation from GC scheduling and bytecode reclamation; keep a + // fixed initial old-generation budget. + return [ + '--no-maglev', + '--no-flush-bytecode', + '--no-minor-gc-task', + '--no-incremental-marking', + '--initial-old-space-size=512', + ] +} + +export function memoryConfig(side: 'client' | 'server') { + const execArgv = memoryExecArgv() + return { + execArgv, + setupFiles: + side === 'client' + ? [fileURLToPath(new URL('./client/vitest.setup.ts', import.meta.url))] + : [], + } +} diff --git a/benchmarks/memory/server/bench-utils.ts b/benchmarks/memory/server/bench-utils.ts index b8a09fdd8e..9caaf63384 100644 --- a/benchmarks/memory/server/bench-utils.ts +++ b/benchmarks/memory/server/bench-utils.ts @@ -1,3 +1,5 @@ +export { memoryBenchHooks } from '../turn' + export interface StartRequestHandler { fetch: (request: Request) => Promise | Response } @@ -17,24 +19,6 @@ export type RunSequentialRequestLoopOptions = iterations?: number buildRequest: (random: () => number, index: number) => Request validateResponse?: (response: Response, request: Request) => void - // Whether V8 collects iteration i's garbage before iteration i+1 - // allocates its payload is not reproducible run to run — the measured - // peak flips by a whole payload depending on GC timing, which shifts - // with runner hardware. Forcing a collection between iterations pins - // the GC points so peak deterministically measures the largest - // single-iteration footprint plus any reachable accumulation. - // Accumulation signals stay visible: leaked or cached objects are - // still referenced, so a forced collection cannot reclaim them — it - // only removes floating garbage, whose collection timing is the - // dominant cross-run noise source. - pinGcBetweenIterations?: boolean - // For peak-shape scenarios ONLY (flat inter-iteration heap floor): - // verify each pinned collection actually returned the heap to the - // floor, extending the barrier when a runner's late teardown holds the - // payload past the fixed window. Churn/abort scenarios must not set - // this: their floor legitimately drifts, so the verification caps out - // chronically and the extra collections it fires destabilize the peak. - verifyGcFloor?: boolean } export const memoryBenchOptions = { @@ -66,7 +50,7 @@ export async function drainResponse(response: Response) { } try { - while (true) { + for (;;) { const result = await reader.read() if (result.done) { @@ -82,13 +66,7 @@ export async function runSequentialRequestLoop( handler: StartRequestHandler, options: RunSequentialRequestLoopOptions, ) { - const { - iterations = 10, - buildRequest, - validateResponse, - pinGcBetweenIterations = false, - verifyGcFloor = false, - } = options + const { iterations = 10, buildRequest, validateResponse } = options const random = options.seed !== undefined ? createDeterministicRandom(options.seed) @@ -103,8 +81,6 @@ export async function runSequentialRequestLoop( } }) - const gcPinState = verifyGcFloor ? createGcPinState() : undefined - for (let index = 0; index < iterations; index++) { const request = buildRequest(random, index) const response = await handler.fetch(request) @@ -112,89 +88,12 @@ export async function runSequentialRequestLoop( validate(response, request) await drainResponse(response) - - if (pinGcBetweenIterations) { - await settleAndPinGc(gcPinState) - } } } -// Renderer/stream teardown spans several event-loop turns (React and Vue -// need more than the two turns the original barrier allowed for), and a -// too-short settle window leaks a whole payload of garbage past the -// collection point, flipping the measured peak bimodally between runs. -// The settle length is a fixed count on purpose: an adaptive exit (collect -// until the post-GC heap size stops moving) makes the collection points -// land at data-dependent turns, which re-introduces exactly the run-to-run -// variance this barrier exists to remove — heap-size readings never fully -// stabilize under the instrumented CI environment, so the exit point (and -// with it every subsequent GC point) shifted between identical runs. -const settleTurnsBeforeGc = 16 -const maxSettleTurns = 64 -// Below every scenario's payload size, above normal inter-iteration jitter. -const settledHeapSlackBytes = 256 * 1024 - -// Tracks the smallest post-collection heap size seen in a workload run: -// the inter-iteration floor the heap must return to before the next -// iteration may start. -export interface GcPinState { - floorHeapUsed: number -} - -export function createGcPinState(): GcPinState { - return { floorHeapUsed: Infinity } -} - -// Settle trailing renderer/stream teardown with a fixed number of 0ms timer -// hops (one full event-loop turn each, microtasks flushing between hops), -// then pin a collection point. The second collection one turn later picks -// up whatever the first collection's finalizers released. gc() is present -// under CodSpeed (--expose-gc); in plain smoke runs there is nothing to -// pin, so only the settle hops run. -// -// The collection is then verified against the inter-iteration heap floor: -// on some runners the response teardown holds the payload past the fixed -// settle window (released only by a later internal timer), and that one -// still-reachable payload survives the collection and bleeds into the next -// iteration's measured peak. When the post-collection heap has not returned -// to the floor, keep hopping and collecting — bounded — until the payload -// is actually released, so the barrier self-heals in exactly the case where -// the fixed-count barrier fails. A workload that genuinely accumulates -// reachable memory raises the floor as it goes (the floor is the minimum -// seen), so accumulation still measures; it only pays the turn cap. -export async function settleAndPinGc(state?: GcPinState) { - for (let turn = 0; turn < settleTurnsBeforeGc; turn++) { +// Cancellation can leave deferred loaders and renderer teardown queued. +export async function settle() { + for (let turn = 0; turn < 16; turn++) { await new Promise((resolve) => setTimeout(resolve, 0)) } - - const gc = (globalThis as { gc?: () => void }).gc - - if (!gc) { - return - } - - gc() - await new Promise((resolve) => setTimeout(resolve, 0)) - gc() - - if (!state) { - return - } - - let heapUsed = process.memoryUsage().heapUsed - - for ( - let turn = settleTurnsBeforeGc; - turn < maxSettleTurns && - heapUsed > state.floorHeapUsed + settledHeapSlackBytes; - turn++ - ) { - await new Promise((resolve) => setTimeout(resolve, 0)) - gc() - heapUsed = process.memoryUsage().heapUsed - } - - if (heapUsed < state.floorHeapUsed) { - state.floorHeapUsed = heapUsed - } } diff --git a/benchmarks/memory/server/benchmark.ts b/benchmarks/memory/server/benchmark.ts index 301a9f956d..9b8dc2c76f 100644 --- a/benchmarks/memory/server/benchmark.ts +++ b/benchmarks/memory/server/benchmark.ts @@ -1,5 +1,9 @@ export interface ServerMemoryWorkload { name: string + /** + * Must be an `async` function: CodSpeed's Vitest 5 provider awaits only + * `AsyncFunction`s and otherwise measures just the synchronous part. + */ run: () => Promise | void } diff --git a/benchmarks/memory/server/package.json b/benchmarks/memory/server/package.json index 68ba6b3c32..d09343c7b6 100644 --- a/benchmarks/memory/server/package.json +++ b/benchmarks/memory/server/package.json @@ -23,15 +23,18 @@ "vue": "^3.5.16" }, "devDependencies": { - "@codspeed/vitest-plugin": "^5.5.0", + "@codspeed/vitest-plugin": "^6.0.1", "@datadog/pprof": "^5.13.2", "@platformatic/flame": "^1.6.0", "@vitejs/plugin-react": "^6.0.1", "@vitejs/plugin-vue-jsx": "^5.1.5", - "typescript": "^6.0.2", + "@types/react": "catalog:", + "@typescript/native": "npm:typescript@^7.0.2", + "jsdom": "29.1.1", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11", - "vitest": "^4.1.4" + "vitest": "catalog:" }, "nx": { "targets": { @@ -205,7 +208,7 @@ "build:react" ], "options": { - "command": "NODE_ENV=production vitest bench --config ./vitest.react.config.ts", + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.react.config.ts", "cwd": "benchmarks/memory/server" } }, @@ -217,7 +220,7 @@ "build:solid" ], "options": { - "command": "NODE_ENV=production vitest bench --config ./vitest.solid.config.ts", + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.solid.config.ts", "cwd": "benchmarks/memory/server" } }, @@ -229,12 +232,12 @@ "build:vue" ], "options": { - "command": "NODE_ENV=production vitest bench --config ./vitest.vue.config.ts", + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.vue.config.ts", "cwd": "benchmarks/memory/server" } }, "test:types": { - "executor": "nx:noop", + "executor": "nx:run-commands", "dependsOn": [ { "projects": [ @@ -262,6 +265,17 @@ ], "target": "test:types:ssr" } + ], + "options": { + "command": "tsc -p ./tsconfig.json --noEmit", + "cwd": "benchmarks/memory/server" + }, + "inputs": [ + "default", + "^production", + "{workspaceRoot}/eslint.config.js", + "dependentTaskOutputs", + "{workspaceRoot}/benchmarks/memory/*.ts" ] } } diff --git a/benchmarks/memory/server/scenarios/aborted-requests/deferred-records.ts b/benchmarks/memory/server/scenarios/aborted-requests/deferred-records.ts index 4886e3ee80..7a1cd6d254 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/deferred-records.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/deferred-records.ts @@ -16,3 +16,42 @@ export function makeAbortedRequestRecords( label: `deferred-${group}-${id}-${index}`, })) } + +// Abort probes keep their deferred payload pending until the request is +// cancelled. Timer chains can outlive cancellation and spill into the next +// measured request; route-loader signals stop observing the request after load. +export function makeDeferredRecords( + id: string, + group: RecordGroup, + signal: AbortSignal, +): Promise> { + return new Promise((resolve) => { + if (signal.aborted) { + resolve([]) + return + } + + let timeoutId: ReturnType | undefined + const onAbort = () => { + clearTimeout(timeoutId) + resolve([]) + } + signal.addEventListener('abort', onAbort, { once: true }) + + if (id === 'sanity-mid-stream' || id.startsWith('abort-')) { + return + } + + let remaining = group === 'alpha' ? 4 : 6 + const step = () => { + remaining -= 1 + if (remaining === 0) { + signal.removeEventListener('abort', onAbort) + resolve(makeAbortedRequestRecords(id, group)) + return + } + timeoutId = setTimeout(step, 0) + } + timeoutId = setTimeout(step, 0) + }) +} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/memory.bench.ts b/benchmarks/memory/server/scenarios/aborted-requests/react/memory.bench.ts index 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/react/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) } }) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/react/vite.config.ts b/benchmarks/memory/server/scenarios/aborted-requests/react/vite.config.ts index 2ce925e406..eff0d0e043 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/vite.config.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // Keep lazily-compiled code alive for the whole run: the pinned - // collections age code fast enough for V8 to flush unused bytecode, - // and the mid-measurement recompile injects a multi-MB allocation - // burst at a run-dependent time. - execArgv: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), name: '@benchmarks/memory-server aborted-requests (react)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/aborted-requests/shared.ts b/benchmarks/memory/server/scenarios/aborted-requests/shared.ts index f7f63c17e6..29eca99e00 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/shared.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/shared.ts @@ -1,4 +1,4 @@ -import { settleAndPinGc } from '#memory-server/bench-utils' +import { settle } from '#memory-server/bench-utils' import type { StartRequestHandler } from '#memory-server/bench-utils' export type { StartRequestHandler } @@ -6,13 +6,6 @@ export type { StartRequestHandler } type Framework = 'react' | 'solid' | 'vue' type AbortedRequestReadMode = 'first-chunk' | 'shell-before-deferred' -type AbortedRequestCancelMode = 'plain' | 'swallow-abort-error' - -type AbortedRequestMode = { - readMode: AbortedRequestReadMode - cancelMode: AbortedRequestCancelMode -} - const abortedRequestIterations = 40 let abortedRequestCounter = 0 const eagerMarker = 'data-bench="aborted-requests-eager"' @@ -24,19 +17,10 @@ const betaFirstRecord = (id: string) => `deferred-beta-${id}-0` const betaLastRecord = (id: string) => `deferred-beta-${id}-19` const textDecoder = new TextDecoder() -const abortedRequestModes: Record = { - react: { - readMode: 'first-chunk', - cancelMode: 'plain', - }, - solid: { - readMode: 'first-chunk', - cancelMode: 'plain', - }, - vue: { - readMode: 'shell-before-deferred', - cancelMode: 'swallow-abort-error', - }, +const abortedRequestModes: Record = { + react: 'first-chunk', + solid: 'first-chunk', + vue: 'shell-before-deferred', } const documentRequestInit = { @@ -96,7 +80,7 @@ async function readShellBeforeDeferred( const reader = response.body.getReader() let text = '' - while (true) { + for (;;) { const result = await reader.read() const value = result.value @@ -137,10 +121,10 @@ async function readShellBeforeDeferred( async function readSanityStream( response: Response, request: Request, - mode: AbortedRequestMode, + mode: AbortedRequestReadMode, id: string, ) { - if (mode.readMode === 'shell-before-deferred') { + if (mode === 'shell-before-deferred') { return readShellBeforeDeferred(response, request, id) } @@ -165,36 +149,19 @@ function readLoopStream( return readFirstChunk(response, request) } -async function cancelReader( - reader: ReadableStreamDefaultReader, - mode: AbortedRequestCancelMode, -) { - if (mode === 'swallow-abort-error') { - try { - await reader.cancel() - } catch (error) { - if (!(error instanceof DOMException && error.name === 'AbortError')) { - throw error - } +async function cancelReader(reader: ReadableStreamDefaultReader) { + try { + await reader.cancel() + } catch (error) { + if (!(error instanceof DOMException && error.name === 'AbortError')) { + throw error } - - return } - - await reader.cancel() -} - -// Post-abort settlement barrier. Settles renderer teardown across a fixed -// number of event-loop turns, then (under CodSpeed) pins a collection point -// after every aborted request, so the measured peak cannot drift with how -// much floating garbage the previous iterations happened to leave behind. -async function drainCancellation() { - await settleAndPinGc() } async function assertAbortedRequestsSanity( handler: StartRequestHandler, - mode: AbortedRequestMode, + mode: AbortedRequestReadMode, ) { const fullId = 'sanity-full' const fullRequest = buildStreamRequest(fullId) @@ -227,13 +194,13 @@ async function assertAbortedRequestsSanity( // reader.cancel() is the response-stream cancellation path if the handler // does not observe Request.signal for this in-process request. controller.abort() - await cancelReader(reader, mode.cancelMode) - await drainCancellation() + await cancelReader(reader) + await settle() } async function runAbortedRequestLoop( handler: StartRequestHandler, - mode: AbortedRequestMode, + mode: AbortedRequestReadMode, ) { for (let index = 0; index < abortedRequestIterations; index++) { const controller = new AbortController() @@ -242,15 +209,10 @@ async function runAbortedRequestLoop( const response = await handler.fetch(request) validateDocumentResponse(response, request) - const { reader } = await readLoopStream( - mode.readMode, - response, - request, - id, - ) + const { reader } = await readLoopStream(mode, response, request, id) controller.abort() - await cancelReader(reader, mode.cancelMode) - await drainCancellation() + await cancelReader(reader) + await settle() } } @@ -259,7 +221,7 @@ export function createWorkloadGroup( handler: StartRequestHandler, ) { const mode = abortedRequestModes[framework] - const run = () => runAbortedRequestLoop(handler, mode) + const run = async () => runAbortedRequestLoop(handler, mode) return { sanity: () => assertAbortedRequestsSanity(handler, mode), diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.bench.ts index 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) } }) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/stream.$id.tsx b/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/stream.$id.tsx index b47f25a405..bf6af17f31 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/stream.$id.tsx +++ b/benchmarks/memory/server/scenarios/aborted-requests/solid/src/routes/stream.$id.tsx @@ -1,90 +1,17 @@ +import { createServerOnlyFn } from '@tanstack/solid-start' +import { getRequest } from '@tanstack/solid-start/server' import { createFileRoute } from '@tanstack/solid-router' import { Show, Suspense, createResource } from 'solid-js' -import { - makeAbortedRequestRecords, - type DeferredRecord, - type RecordGroup, -} from '../../../deferred-records' +import { makeDeferredRecords } from '../../../deferred-records' +import type { DeferredRecord } from '../../../deferred-records' -const alphaResolveTicks = 4 -const betaResolveTicks = 6 -const abortProbeAlphaResolveTicks = 40 -const abortProbeBetaResolveTicks = 60 - -function isAbortProbeId(id: string) { - return id === 'sanity-mid-stream' || id.startsWith('abort-') -} - -function getResolveTicks(id: string, group: RecordGroup) { - if (isAbortProbeId(id)) { - return group === 'alpha' - ? abortProbeAlphaResolveTicks - : abortProbeBetaResolveTicks - } - - return group === 'alpha' ? alphaResolveTicks : betaResolveTicks -} - -// One tick = one 0ms timers-phase hop. Counting event-loop turns instead of -// milliseconds keeps the resolve/abort interleaving a pure function of the -// event-loop schedule: a wall-clock delay races the abort differently -// depending on runner load and instrumentation overhead, which made this -// benchmark's single measured run swing between runs. -function resolveAfterTicks( - ticks: number, - signal: AbortSignal, - value: () => T, - abortedValue: () => T, -) { - return new Promise((resolve) => { - if (signal.aborted) { - resolve(abortedValue()) - return - } - - let remaining = ticks - let timeoutId: ReturnType - - const onAbort = () => { - clearTimeout(timeoutId) - resolve(abortedValue()) - } - - const step = () => { - remaining -= 1 - - if (remaining <= 0) { - signal.removeEventListener('abort', onAbort) - resolve(value()) - return - } - - timeoutId = setTimeout(step, 0) - } - - signal.addEventListener('abort', onAbort, { once: true }) - timeoutId = setTimeout(step, 0) - }) -} - -function makeDeferredRecords( - id: string, - group: RecordGroup, - signal: AbortSignal, -) { - return resolveAfterTicks( - getResolveTicks(id, group), - signal, - () => makeAbortedRequestRecords(id, group), - () => [], - ) -} +const getRequestSignal = createServerOnlyFn(() => getRequest().signal) export const Route = createFileRoute('/stream/$id')({ - loader: ({ params, abortController }) => ({ + loader: ({ params }) => ({ eager: `eager-${params.id}`, - alpha: makeDeferredRecords(params.id, 'alpha', abortController.signal), - beta: makeDeferredRecords(params.id, 'beta', abortController.signal), + alpha: makeDeferredRecords(params.id, 'alpha', getRequestSignal()), + beta: makeDeferredRecords(params.id, 'beta', getRequestSignal()), }), component: StreamComponent, }) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/vite.config.ts b/benchmarks/memory/server/scenarios/aborted-requests/solid/vite.config.ts index 5ee4e152af..d7fd3459ee 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/vite.config.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // Keep lazily-compiled code alive for the whole run: the pinned - // collections age code fast enough for V8 to flush unused bytecode, - // and the mid-measurement recompile injects a multi-MB allocation - // burst at a run-dependent time. - execArgv: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), name: '@benchmarks/memory-server aborted-requests (solid)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.bench.ts index 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) } }) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/stream.$id.tsx b/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/stream.$id.tsx index b723c7f69e..e41af03c16 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/stream.$id.tsx +++ b/benchmarks/memory/server/scenarios/aborted-requests/vue/src/routes/stream.$id.tsx @@ -1,136 +1,65 @@ +import { createServerOnlyFn } from '@tanstack/vue-start' +import { getRequest } from '@tanstack/vue-start/server' import { Await, createFileRoute } from '@tanstack/vue-router' -import { Suspense } from 'vue' -import { - makeAbortedRequestRecords, - type DeferredRecord, - type RecordGroup, -} from '../../../deferred-records' +import { Suspense, defineComponent } from 'vue' +import { makeDeferredRecords } from '../../../deferred-records' +import type { DeferredRecord } from '../../../deferred-records' -const alphaResolveTicks = 4 -const betaResolveTicks = 6 -const abortProbeAlphaResolveTicks = 40 -const abortProbeBetaResolveTicks = 60 +const getRequestSignal = createServerOnlyFn(() => getRequest().signal) -function isAbortProbeId(id: string) { - return id === 'sanity-mid-stream' || id.startsWith('abort-') -} +const StreamComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() -function getResolveTicks(id: string, group: RecordGroup) { - if (isAbortProbeId(id)) { - return group === 'alpha' - ? abortProbeAlphaResolveTicks - : abortProbeBetaResolveTicks - } - - return group === 'alpha' ? alphaResolveTicks : betaResolveTicks -} - -// One tick = one 0ms timers-phase hop. Counting event-loop turns instead of -// milliseconds keeps the resolve/abort interleaving a pure function of the -// event-loop schedule: a wall-clock delay races the abort differently -// depending on runner load and instrumentation overhead, which made this -// benchmark's single measured run swing between runs. -function resolveAfterTicks( - ticks: number, - signal: AbortSignal, - value: () => T, - abortedValue: () => T, -) { - return new Promise((resolve) => { - if (signal.aborted) { - resolve(abortedValue()) - return - } - - let remaining = ticks - let timeoutId: ReturnType - - const onAbort = () => { - clearTimeout(timeoutId) - resolve(abortedValue()) - } - - const step = () => { - remaining -= 1 - - if (remaining <= 0) { - signal.removeEventListener('abort', onAbort) - resolve(value()) - return - } - - timeoutId = setTimeout(step, 0) - } - - signal.addEventListener('abort', onAbort, { once: true }) - timeoutId = setTimeout(step, 0) - }) -} - -function makeDeferredRecords( - id: string, - group: RecordGroup, - signal: AbortSignal, -) { - return resolveAfterTicks( - getResolveTicks(id, group), - signal, - () => makeAbortedRequestRecords(id, group), - () => [], - ) -} + return () => ( +
+

{data.value.eager}

+

loading-alpha

+

loading-beta

+ + {{ + default: () => ( + ) => ( +
    + {records.map((record) => ( +
  • {record.label}
  • + ))} +
+ )} + /> + ), + fallback: () => null, + }} +
+ + {{ + default: () => ( + ) => ( +
    + {records.map((record) => ( +
  • {record.label}
  • + ))} +
+ )} + /> + ), + fallback: () => null, + }} +
+
+ ) + }, +}) export const Route = createFileRoute('/stream/$id')({ - loader: ({ params, abortController }) => ({ + loader: ({ params }) => ({ eager: `eager-${params.id}`, - alpha: makeDeferredRecords(params.id, 'alpha', abortController.signal), - beta: makeDeferredRecords(params.id, 'beta', abortController.signal), + alpha: makeDeferredRecords(params.id, 'alpha', getRequestSignal()), + beta: makeDeferredRecords(params.id, 'beta', getRequestSignal()), }), component: StreamComponent, }) - -function StreamComponent() { - const data = Route.useLoaderData() - - return ( -
-

{data.value.eager}

-

loading-alpha

-

loading-beta

- - {{ - default: () => ( - ) => ( -
    - {records.map((record) => ( -
  • {record.label}
  • - ))} -
- )} - /> - ), - fallback: () => null, - }} -
- - {{ - default: () => ( - ) => ( -
    - {records.map((record) => ( -
  • {record.label}
  • - ))} -
- )} - /> - ), - fallback: () => null, - }} -
-
- ) -} diff --git a/benchmarks/memory/server/scenarios/aborted-requests/vue/vite.config.ts b/benchmarks/memory/server/scenarios/aborted-requests/vue/vite.config.ts index 5ccc9f5d1d..e4e1eb66d4 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/vite.config.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // Keep lazily-compiled code alive for the whole run: the pinned - // collections age code fast enough for V8 to flush unused bytecode, - // and the mid-measurement recompile injects a multi-MB allocation - // burst at a run-dependent time. - execArgv: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), name: '@benchmarks/memory-server aborted-requests (vue)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/error-paths/react/memory.bench.ts b/benchmarks/memory/server/scenarios/error-paths/react/memory.bench.ts index 9a5c211fee..a6f07b97be 100644 --- a/benchmarks/memory/server/scenarios/error-paths/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/react/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { - for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) - } +const workload = workloadGroup.workloads[0]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) }) diff --git a/benchmarks/memory/server/scenarios/error-paths/react/memory.error.bench.ts b/benchmarks/memory/server/scenarios/error-paths/react/memory.error.bench.ts new file mode 100644 index 0000000000..89071137c3 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/memory.error.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +const workload = workloadGroup.workloads[2]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/react/memory.not-found.bench.ts b/benchmarks/memory/server/scenarios/error-paths/react/memory.not-found.bench.ts new file mode 100644 index 0000000000..fa6a6693ed --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/memory.not-found.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +const workload = workloadGroup.workloads[1]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/react/memory.unmatched.bench.ts b/benchmarks/memory/server/scenarios/error-paths/react/memory.unmatched.bench.ts new file mode 100644 index 0000000000..b2c3d24200 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/react/memory.unmatched.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +const workload = workloadGroup.workloads[3]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/react/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/error-paths/react/src/routeTree.gen.ts index fd373be6b4..4e8e4ce0e4 100644 --- a/benchmarks/memory/server/scenarios/error-paths/react/src/routeTree.gen.ts +++ b/benchmarks/memory/server/scenarios/error-paths/react/src/routeTree.gen.ts @@ -10,24 +10,19 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as TargetIdRouteImport } from './routes/target.$id' -import { Route as MissingIdRouteImport } from './routes/missing.$id' -import { Route as FromIdRouteImport } from './routes/from.$id' import { Route as BoomIdRouteImport } from './routes/boom.$id' +import { Route as FromIdRouteImport } from './routes/from.$id' +import { Route as MissingIdRouteImport } from './routes/missing.$id' +import { Route as TargetIdRouteImport } from './routes/target.$id' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const TargetIdRoute = TargetIdRouteImport.update({ - id: '/target/$id', - path: '/target/$id', - getParentRoute: () => rootRouteImport, -} as any) -const MissingIdRoute = MissingIdRouteImport.update({ - id: '/missing/$id', - path: '/missing/$id', +const BoomIdRoute = BoomIdRouteImport.update({ + id: '/boom/$id', + path: '/boom/$id', getParentRoute: () => rootRouteImport, } as any) const FromIdRoute = FromIdRouteImport.update({ @@ -35,9 +30,14 @@ const FromIdRoute = FromIdRouteImport.update({ path: '/from/$id', getParentRoute: () => rootRouteImport, } as any) -const BoomIdRoute = BoomIdRouteImport.update({ - id: '/boom/$id', - path: '/boom/$id', +const MissingIdRoute = MissingIdRouteImport.update({ + id: '/missing/$id', + path: '/missing/$id', + getParentRoute: () => rootRouteImport, +} as any) +const TargetIdRoute = TargetIdRouteImport.update({ + id: '/target/$id', + path: '/target/$id', getParentRoute: () => rootRouteImport, } as any) @@ -94,18 +94,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/target/$id': { - id: '/target/$id' - path: '/target/$id' - fullPath: '/target/$id' - preLoaderRoute: typeof TargetIdRouteImport - parentRoute: typeof rootRouteImport - } - '/missing/$id': { - id: '/missing/$id' - path: '/missing/$id' - fullPath: '/missing/$id' - preLoaderRoute: typeof MissingIdRouteImport + '/boom/$id': { + id: '/boom/$id' + path: '/boom/$id' + fullPath: '/boom/$id' + preLoaderRoute: typeof BoomIdRouteImport parentRoute: typeof rootRouteImport } '/from/$id': { @@ -115,11 +108,18 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof FromIdRouteImport parentRoute: typeof rootRouteImport } - '/boom/$id': { - id: '/boom/$id' - path: '/boom/$id' - fullPath: '/boom/$id' - preLoaderRoute: typeof BoomIdRouteImport + '/missing/$id': { + id: '/missing/$id' + path: '/missing/$id' + fullPath: '/missing/$id' + preLoaderRoute: typeof MissingIdRouteImport + parentRoute: typeof rootRouteImport + } + '/target/$id': { + id: '/target/$id' + path: '/target/$id' + fullPath: '/target/$id' + preLoaderRoute: typeof TargetIdRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/memory/server/scenarios/error-paths/react/tsconfig.json b/benchmarks/memory/server/scenarios/error-paths/react/tsconfig.json index 11ddcce4ea..2dba47fc99 100644 --- a/benchmarks/memory/server/scenarios/error-paths/react/tsconfig.json +++ b/benchmarks/memory/server/scenarios/error-paths/react/tsconfig.json @@ -7,7 +7,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "memory.bench.ts", + "memory*.bench.ts", "memory.flame.ts", "setup.ts", "vite.config.ts", diff --git a/benchmarks/memory/server/scenarios/error-paths/react/vite.config.ts b/benchmarks/memory/server/scenarios/error-paths/react/vite.config.ts index bc67b1cfc7..c00de7727a 100644 --- a/benchmarks/memory/server/scenarios/error-paths/react/vite.config.ts +++ b/benchmarks/memory/server/scenarios/error-paths/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,8 @@ export default defineConfig({ minify: false, }, test: { - // Keep lazily-compiled code alive for the whole run: the pinned - // collections age code fast enough for V8 to flush unused bytecode, - // and the mid-measurement recompile injects a multi-MB allocation - // burst at a run-dependent time. - execArgv: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + isolate: true, + ...memoryConfig('server'), name: '@benchmarks/memory-server error-paths (react)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/error-paths/shared.ts b/benchmarks/memory/server/scenarios/error-paths/shared.ts index 57e229b7e3..11ed293d22 100644 --- a/benchmarks/memory/server/scenarios/error-paths/shared.ts +++ b/benchmarks/memory/server/scenarios/error-paths/shared.ts @@ -9,8 +9,6 @@ export type { StartRequestHandler } type Framework = 'react' | 'solid' | 'vue' -// Sized to sit just above the 2s measured-run floor on CI (per-iteration -// cost with the pinned collection is ~0.13-0.19s across frameworks). const errorPathsIterations = 18 const redirectSeed = 0xdecafbad const notFoundSeed = 0xdecafb0d @@ -138,40 +136,36 @@ export function createWorkloadGroup( framework: Framework, handler: StartRequestHandler, ) { - const runRedirect = () => + const runRedirect = async () => runSequentialRequestLoop(handler, { random: redirectRandom, iterations: errorPathsIterations, buildRequest: buildRedirectRequest, validateResponse: validateRedirectResponse, - pinGcBetweenIterations: true, }) - const runNotFound = () => + const runNotFound = async () => runSequentialRequestLoop(handler, { random: notFoundRandom, iterations: errorPathsIterations, buildRequest: buildNotFoundRequest, validateResponse: validateNotFoundResponse, - pinGcBetweenIterations: true, }) - const runError = () => + const runError = async () => runSequentialRequestLoop(handler, { random: errorRandom, iterations: errorPathsIterations, buildRequest: buildErrorRequest, validateResponse: validateErrorResponse, - pinGcBetweenIterations: true, }) - const runUnmatched = () => + const runUnmatched = async () => runSequentialRequestLoop(handler, { random: unmatchedRandom, iterations: errorPathsIterations, buildRequest: buildUnmatchedRequest, validateResponse: validateNotFoundResponse, - pinGcBetweenIterations: true, }) return { diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/error-paths/solid/memory.bench.ts index 9a5c211fee..a6f07b97be 100644 --- a/benchmarks/memory/server/scenarios/error-paths/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/solid/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { - for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) - } +const workload = workloadGroup.workloads[0]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) }) diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/memory.error.bench.ts b/benchmarks/memory/server/scenarios/error-paths/solid/memory.error.bench.ts new file mode 100644 index 0000000000..89071137c3 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/memory.error.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +const workload = workloadGroup.workloads[2]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/memory.not-found.bench.ts b/benchmarks/memory/server/scenarios/error-paths/solid/memory.not-found.bench.ts new file mode 100644 index 0000000000..fa6a6693ed --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/memory.not-found.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +const workload = workloadGroup.workloads[1]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/memory.unmatched.bench.ts b/benchmarks/memory/server/scenarios/error-paths/solid/memory.unmatched.bench.ts new file mode 100644 index 0000000000..b2c3d24200 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/solid/memory.unmatched.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +const workload = workloadGroup.workloads[3]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/tsconfig.json b/benchmarks/memory/server/scenarios/error-paths/solid/tsconfig.json index 4b61264e11..1e8103127a 100644 --- a/benchmarks/memory/server/scenarios/error-paths/solid/tsconfig.json +++ b/benchmarks/memory/server/scenarios/error-paths/solid/tsconfig.json @@ -7,7 +7,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "memory.bench.ts", + "memory*.bench.ts", "memory.flame.ts", "setup.ts", "vite.config.ts", diff --git a/benchmarks/memory/server/scenarios/error-paths/solid/vite.config.ts b/benchmarks/memory/server/scenarios/error-paths/solid/vite.config.ts index 401d1e5f25..d7a0bb51b0 100644 --- a/benchmarks/memory/server/scenarios/error-paths/solid/vite.config.ts +++ b/benchmarks/memory/server/scenarios/error-paths/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,8 @@ export default defineConfig({ minify: false, }, test: { - // Keep lazily-compiled code alive for the whole run: the pinned - // collections age code fast enough for V8 to flush unused bytecode, - // and the mid-measurement recompile injects a multi-MB allocation - // burst at a run-dependent time. - execArgv: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + isolate: true, + ...memoryConfig('server'), name: '@benchmarks/memory-server error-paths (solid)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/error-paths/vue/memory.bench.ts index 9a5c211fee..a6f07b97be 100644 --- a/benchmarks/memory/server/scenarios/error-paths/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/vue/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { - for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) - } +const workload = workloadGroup.workloads[0]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) }) diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/memory.error.bench.ts b/benchmarks/memory/server/scenarios/error-paths/vue/memory.error.bench.ts new file mode 100644 index 0000000000..89071137c3 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/memory.error.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +const workload = workloadGroup.workloads[2]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/memory.not-found.bench.ts b/benchmarks/memory/server/scenarios/error-paths/vue/memory.not-found.bench.ts new file mode 100644 index 0000000000..fa6a6693ed --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/memory.not-found.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +const workload = workloadGroup.workloads[1]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/memory.unmatched.bench.ts b/benchmarks/memory/server/scenarios/error-paths/vue/memory.unmatched.bench.ts new file mode 100644 index 0000000000..b2c3d24200 --- /dev/null +++ b/benchmarks/memory/server/scenarios/error-paths/vue/memory.unmatched.bench.ts @@ -0,0 +1,16 @@ +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' +import { workloadGroup } from './setup' + +await workloadGroup.sanity() + +const workload = workloadGroup.workloads[3]! + +test('memory', async ({ bench }) => { + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) +}) diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/target.$id.tsx b/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/target.$id.tsx index 17ade6bf5b..0bbf4a3dc6 100644 --- a/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/target.$id.tsx +++ b/benchmarks/memory/server/scenarios/error-paths/vue/src/routes/target.$id.tsx @@ -1,11 +1,14 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' +const TargetComponent = defineComponent({ + setup() { + const params = Route.useParams() + + return () =>
{`target-${params.value.id}`}
+ }, +}) + export const Route = createFileRoute('/target/$id')({ component: TargetComponent, }) - -function TargetComponent() { - const params = Route.useParams() - - return
{`target-${params.value.id}`}
-} diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/tsconfig.json b/benchmarks/memory/server/scenarios/error-paths/vue/tsconfig.json index 9ad6481342..af8b83005c 100644 --- a/benchmarks/memory/server/scenarios/error-paths/vue/tsconfig.json +++ b/benchmarks/memory/server/scenarios/error-paths/vue/tsconfig.json @@ -7,7 +7,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "memory.bench.ts", + "memory*.bench.ts", "memory.flame.ts", "setup.ts", "vite.config.ts", diff --git a/benchmarks/memory/server/scenarios/error-paths/vue/vite.config.ts b/benchmarks/memory/server/scenarios/error-paths/vue/vite.config.ts index 9a0ca28a25..3dc0762aa0 100644 --- a/benchmarks/memory/server/scenarios/error-paths/vue/vite.config.ts +++ b/benchmarks/memory/server/scenarios/error-paths/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,8 @@ export default defineConfig({ minify: false, }, test: { - // Keep lazily-compiled code alive for the whole run: the pinned - // collections age code fast enough for V8 to flush unused bytecode, - // and the mid-measurement recompile injects a multi-MB allocation - // burst at a run-dependent time. - execArgv: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + isolate: true, + ...memoryConfig('server'), name: '@benchmarks/memory-server error-paths (vue)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/memory.bench.ts b/benchmarks/memory/server/scenarios/peak-large-page/react/memory.bench.ts index 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) } }) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routeTree.gen.ts b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routeTree.gen.ts index 60a1bd1fbc..6004590f9b 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/src/routeTree.gen.ts +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/src/routeTree.gen.ts @@ -9,8 +9,8 @@ // 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 L1RouteImport } from './routes/l1' import { Route as IndexRouteImport } from './routes/index' +import { Route as L1RouteImport } from './routes/l1' import { Route as L1L2RouteImport } from './routes/l1.l2' import { Route as L1L2L3RouteImport } from './routes/l1.l2.l3' import { Route as L1L2L3L4RouteImport } from './routes/l1.l2.l3.l4' @@ -19,16 +19,16 @@ import { Route as L1L2L3L4L5L6RouteImport } from './routes/l1.l2.l3.l4.l5.l6' import { Route as L1L2L3L4L5L6L7RouteImport } from './routes/l1.l2.l3.l4.l5.l6.l7' import { Route as L1L2L3L4L5L6L7L8RouteImport } from './routes/l1.l2.l3.l4.l5.l6.l7.l8' -const L1Route = L1RouteImport.update({ - id: '/l1', - path: '/l1', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const L1Route = L1RouteImport.update({ + id: '/l1', + path: '/l1', + getParentRoute: () => rootRouteImport, +} as any) const L1L2Route = L1L2RouteImport.update({ id: '/l2', path: '/l2', @@ -142,13 +142,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/l1': { - id: '/l1' - path: '/l1' - fullPath: '/l1' - preLoaderRoute: typeof L1RouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -156,6 +149,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/l1': { + id: '/l1' + path: '/l1' + fullPath: '/l1' + preLoaderRoute: typeof L1RouteImport + parentRoute: typeof rootRouteImport + } '/l1/l2': { id: '/l1/l2' path: '/l2' diff --git a/benchmarks/memory/server/scenarios/peak-large-page/react/vite.config.ts b/benchmarks/memory/server/scenarios/peak-large-page/react/vite.config.ts index adaacda86e..dcfcf1f92b 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/react/vite.config.ts +++ b/benchmarks/memory/server/scenarios/peak-large-page/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // Keep lazily-compiled code alive for the whole run: the pinned - // collections age code fast enough for V8 to flush unused bytecode, - // and the mid-measurement recompile injects a multi-MB allocation - // burst at a run-dependent time. - execArgv: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), name: '@benchmarks/memory-server peak-large-page (react)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/peak-large-page/shared.ts b/benchmarks/memory/server/scenarios/peak-large-page/shared.ts index 578fc9c5a2..085e576244 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/shared.ts +++ b/benchmarks/memory/server/scenarios/peak-large-page/shared.ts @@ -6,7 +6,7 @@ export type { StartRequestHandler } type Framework = 'react' | 'solid' | 'vue' const benchmarkSeed = 0x5eed_0005 -const peakLargePageIterations = 20 +const peakLargePageIterations = 1 const peakLargePageUrl = 'http://localhost/l1/l2/l3/l4/l5/l6/l7/l8' const levelEightMarker = 'data-bench="peak-large-page-level-8"' @@ -48,14 +48,12 @@ export function createWorkloadGroup( framework: Framework, handler: StartRequestHandler, ) { - const run = () => + const run = async () => runSequentialRequestLoop(handler, { seed: benchmarkSeed, iterations: peakLargePageIterations, buildRequest: buildPeakLargePageRequest, validateResponse: validatePeakLargePageResponse, - pinGcBetweenIterations: true, - verifyGcFloor: true, }) return { diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/peak-large-page/solid/memory.bench.ts index 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/peak-large-page/solid/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) } }) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/solid/vite.config.ts b/benchmarks/memory/server/scenarios/peak-large-page/solid/vite.config.ts index 27d4dd65f7..15b8c3a571 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/solid/vite.config.ts +++ b/benchmarks/memory/server/scenarios/peak-large-page/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // Keep lazily-compiled code alive for the whole run: the pinned - // collections age code fast enough for V8 to flush unused bytecode, - // and the mid-measurement recompile injects a multi-MB allocation - // burst at a run-dependent time. - execArgv: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), name: '@benchmarks/memory-server peak-large-page (solid)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/peak-large-page/vue/memory.bench.ts index 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) } }) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx index bd079aa1a0..7f7a42d645 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.l8.tsx @@ -1,28 +1,34 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { makeLargePageHead, makeLargePageLevelData, } from '../../../large-page-data' +const LevelEightComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => { + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+
+ ) + } + }, +}) + export const Route = createFileRoute('/l1/l2/l3/l4/l5/l6/l7/l8')({ loader: () => makeLargePageLevelData(8, 0x5eed_1008), head: ({ loaderData }) => makeLargePageHead(loaderData), component: LevelEightComponent, }) - -function LevelEightComponent() { - const data = Route.useLoaderData() - const first = data.value.records[0]! - - return ( -
-

{data.value.marker}

-

records: {data.value.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
-
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx index 7f69f6f438..a99c56e529 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.l7.tsx @@ -1,29 +1,35 @@ +import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { makeLargePageHead, makeLargePageLevelData, } from '../../../large-page-data' +const LevelSevenComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => { + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) + } + }, +}) + export const Route = createFileRoute('/l1/l2/l3/l4/l5/l6/l7')({ loader: () => makeLargePageLevelData(7, 0x5eed_1007), head: ({ loaderData }) => makeLargePageHead(loaderData), component: LevelSevenComponent, }) - -function LevelSevenComponent() { - const data = Route.useLoaderData() - const first = data.value.records[0]! - - return ( -
-

{data.value.marker}

-

records: {data.value.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
- -
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.tsx index 75a7c717e3..3de3f03427 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.tsx +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.l6.tsx @@ -1,29 +1,35 @@ +import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { makeLargePageHead, makeLargePageLevelData, } from '../../../large-page-data' +const LevelSixComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => { + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) + } + }, +}) + export const Route = createFileRoute('/l1/l2/l3/l4/l5/l6')({ loader: () => makeLargePageLevelData(6, 0x5eed_1006), head: ({ loaderData }) => makeLargePageHead(loaderData), component: LevelSixComponent, }) - -function LevelSixComponent() { - const data = Route.useLoaderData() - const first = data.value.records[0]! - - return ( -
-

{data.value.marker}

-

records: {data.value.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
- -
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.tsx index f390ae3db3..5d936f83b5 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.tsx +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.l5.tsx @@ -1,29 +1,35 @@ +import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { makeLargePageHead, makeLargePageLevelData, } from '../../../large-page-data' +const LevelFiveComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => { + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) + } + }, +}) + export const Route = createFileRoute('/l1/l2/l3/l4/l5')({ loader: () => makeLargePageLevelData(5, 0x5eed_1005), head: ({ loaderData }) => makeLargePageHead(loaderData), component: LevelFiveComponent, }) - -function LevelFiveComponent() { - const data = Route.useLoaderData() - const first = data.value.records[0]! - - return ( -
-

{data.value.marker}

-

records: {data.value.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
- -
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.tsx index 6b30bd50dc..8e10331f2d 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.tsx +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.l4.tsx @@ -1,29 +1,35 @@ +import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { makeLargePageHead, makeLargePageLevelData, } from '../../../large-page-data' +const LevelFourComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => { + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) + } + }, +}) + export const Route = createFileRoute('/l1/l2/l3/l4')({ loader: () => makeLargePageLevelData(4, 0x5eed_1004), head: ({ loaderData }) => makeLargePageHead(loaderData), component: LevelFourComponent, }) - -function LevelFourComponent() { - const data = Route.useLoaderData() - const first = data.value.records[0]! - - return ( -
-

{data.value.marker}

-

records: {data.value.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
- -
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.tsx index 6ec6f32fea..d69529c50c 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.tsx +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.l3.tsx @@ -1,29 +1,35 @@ +import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { makeLargePageHead, makeLargePageLevelData, } from '../../../large-page-data' +const LevelThreeComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => { + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) + } + }, +}) + export const Route = createFileRoute('/l1/l2/l3')({ loader: () => makeLargePageLevelData(3, 0x5eed_1003), head: ({ loaderData }) => makeLargePageHead(loaderData), component: LevelThreeComponent, }) - -function LevelThreeComponent() { - const data = Route.useLoaderData() - const first = data.value.records[0]! - - return ( -
-

{data.value.marker}

-

records: {data.value.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
- -
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.tsx index e5b4cf0de1..d04bc7f827 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.tsx +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.l2.tsx @@ -1,29 +1,35 @@ +import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { makeLargePageHead, makeLargePageLevelData, } from '../../../large-page-data' +const LevelTwoComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => { + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) + } + }, +}) + export const Route = createFileRoute('/l1/l2')({ loader: () => makeLargePageLevelData(2, 0x5eed_1002), head: ({ loaderData }) => makeLargePageHead(loaderData), component: LevelTwoComponent, }) - -function LevelTwoComponent() { - const data = Route.useLoaderData() - const first = data.value.records[0]! - - return ( -
-

{data.value.marker}

-

records: {data.value.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
- -
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.tsx b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.tsx index a29e465cd4..a95ae7f9b0 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.tsx +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/src/routes/l1.tsx @@ -1,29 +1,35 @@ +import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { makeLargePageHead, makeLargePageLevelData, } from '../../../large-page-data' +const LevelOneComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => { + const first = data.value.records[0]! + + return ( +
+

{data.value.marker}

+

records: {data.value.records.length}

+
+

{first.name}

+

{first.id}

+

{first.description}

+
+ +
+ ) + } + }, +}) + export const Route = createFileRoute('/l1')({ loader: () => makeLargePageLevelData(1, 0x5eed_1001), head: ({ loaderData }) => makeLargePageHead(loaderData), component: LevelOneComponent, }) - -function LevelOneComponent() { - const data = Route.useLoaderData() - const first = data.value.records[0]! - - return ( -
-

{data.value.marker}

-

records: {data.value.records.length}

-
-

{first.name}

-

{first.id}

-

{first.description}

-
- -
- ) -} diff --git a/benchmarks/memory/server/scenarios/peak-large-page/vue/vite.config.ts b/benchmarks/memory/server/scenarios/peak-large-page/vue/vite.config.ts index 0f238bd7f7..3fab2aff9e 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/vue/vite.config.ts +++ b/benchmarks/memory/server/scenarios/peak-large-page/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // Keep lazily-compiled code alive for the whole run: the pinned - // collections age code fast enough for V8 to flush unused bytecode, - // and the mid-measurement recompile injects a multi-MB allocation - // burst at a run-dependent time. - execArgv: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), name: '@benchmarks/memory-server peak-large-page (vue)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/request-churn/react/memory.bench.ts b/benchmarks/memory/server/scenarios/request-churn/react/memory.bench.ts index 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/request-churn/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/request-churn/react/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) } }) diff --git a/benchmarks/memory/server/scenarios/request-churn/react/vite.config.ts b/benchmarks/memory/server/scenarios/request-churn/react/vite.config.ts index 1e956958ec..35adf6a249 100644 --- a/benchmarks/memory/server/scenarios/request-churn/react/vite.config.ts +++ b/benchmarks/memory/server/scenarios/request-churn/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // Keep lazily-compiled code alive for the whole run: the pinned - // collections age code fast enough for V8 to flush unused bytecode, - // and the mid-measurement recompile injects a multi-MB allocation - // burst at a run-dependent time. - execArgv: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), name: '@benchmarks/memory-server request-churn (react)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/request-churn/shared.ts b/benchmarks/memory/server/scenarios/request-churn/shared.ts index a196eec8b5..b200c96ed6 100644 --- a/benchmarks/memory/server/scenarios/request-churn/shared.ts +++ b/benchmarks/memory/server/scenarios/request-churn/shared.ts @@ -62,13 +62,12 @@ export function createWorkloadGroup( return new Request(`http://localhost/items/${id}?q=${q}`, requestInit) } - const run = () => + const run = async () => runSequentialRequestLoop(handler, { random: benchmarkRandom, iterations: requestChurnIterations, buildRequest: buildItemRequest, validateResponse: validateItemResponse, - pinGcBetweenIterations: true, }) return { diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/request-churn/solid/memory.bench.ts index 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/request-churn/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/request-churn/solid/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) } }) diff --git a/benchmarks/memory/server/scenarios/request-churn/solid/vite.config.ts b/benchmarks/memory/server/scenarios/request-churn/solid/vite.config.ts index fbf8df9491..6601309a74 100644 --- a/benchmarks/memory/server/scenarios/request-churn/solid/vite.config.ts +++ b/benchmarks/memory/server/scenarios/request-churn/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // Keep lazily-compiled code alive for the whole run: the pinned - // collections age code fast enough for V8 to flush unused bytecode, - // and the mid-measurement recompile injects a multi-MB allocation - // burst at a run-dependent time. - execArgv: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), name: '@benchmarks/memory-server request-churn (solid)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/request-churn/vue/memory.bench.ts index 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/request-churn/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/request-churn/vue/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) } }) diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/items.$id.tsx b/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/items.$id.tsx index a98d036565..570561f2a8 100644 --- a/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/items.$id.tsx +++ b/benchmarks/memory/server/scenarios/request-churn/vue/src/routes/items.$id.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' const itemIndexes = Array.from({ length: 5 }, (_, index) => index) @@ -6,6 +7,24 @@ type ItemSearch = { q: string } +const ItemComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+

{data.value.title}

+

{data.value.q}

+
    + {data.value.items.map((item) => ( +
  • {item.label}
  • + ))} +
+
+ ) + }, +}) + export const Route = createFileRoute('/items/$id')({ validateSearch: (search: Record): ItemSearch => ({ q: typeof search.q === 'string' ? search.q : '', @@ -22,19 +41,3 @@ export const Route = createFileRoute('/items/$id')({ }), component: ItemComponent, }) - -function ItemComponent() { - const data = Route.useLoaderData() - - return ( -
-

{data.value.title}

-

{data.value.q}

-
    - {data.value.items.map((item) => ( -
  • {item.label}
  • - ))} -
-
- ) -} diff --git a/benchmarks/memory/server/scenarios/request-churn/vue/vite.config.ts b/benchmarks/memory/server/scenarios/request-churn/vue/vite.config.ts index a551a96e2f..7f15c5c7af 100644 --- a/benchmarks/memory/server/scenarios/request-churn/vue/vite.config.ts +++ b/benchmarks/memory/server/scenarios/request-churn/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // Keep lazily-compiled code alive for the whole run: the pinned - // collections age code fast enough for V8 to flush unused bytecode, - // and the mid-measurement recompile injects a multi-MB allocation - // burst at a run-dependent time. - execArgv: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), name: '@benchmarks/memory-server request-churn (vue)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/serialization-payload/react/memory.bench.ts b/benchmarks/memory/server/scenarios/serialization-payload/react/memory.bench.ts index 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/react/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) } }) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/react/vite.config.ts b/benchmarks/memory/server/scenarios/serialization-payload/react/vite.config.ts index de5549de3b..1ed3bcc335 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/vite.config.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // Keep lazily-compiled code alive for the whole run: the pinned - // collections age code fast enough for V8 to flush unused bytecode, - // and the mid-measurement recompile injects a multi-MB allocation - // burst at a run-dependent time. - execArgv: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), name: '@benchmarks/memory-server serialization-payload (react)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/serialization-payload/shared.ts b/benchmarks/memory/server/scenarios/serialization-payload/shared.ts index ce095b5e10..14ec8f7e0a 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/shared.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/shared.ts @@ -9,7 +9,7 @@ export type { StartRequestHandler } type Framework = 'react' | 'solid' | 'vue' const benchmarkSeed = 0x51eaa11 -const serializationPayloadIterations = 12 +const serializationPayloadIterations = 1 const payloadPageMarker = 'data-bench="serialization-payload"' const requestInit = { @@ -55,14 +55,12 @@ export function createWorkloadGroup( framework: Framework, handler: StartRequestHandler, ) { - const run = () => + const run = async () => runSequentialRequestLoop(handler, { seed: benchmarkSeed, iterations: serializationPayloadIterations, buildRequest: buildPayloadRequest, validateResponse: validatePayloadResponse, - pinGcBetweenIterations: true, - verifyGcFloor: true, }) return { diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.bench.ts index 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) } }) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/solid/vite.config.ts b/benchmarks/memory/server/scenarios/serialization-payload/solid/vite.config.ts index 926646ee12..a2d04b986c 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/vite.config.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // Keep lazily-compiled code alive for the whole run: the pinned - // collections age code fast enough for V8 to flush unused bytecode, - // and the mid-measurement recompile injects a multi-MB allocation - // burst at a run-dependent time. - execArgv: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), name: '@benchmarks/memory-server serialization-payload (solid)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.bench.ts index 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) } }) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routes/data.$id.tsx b/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routes/data.$id.tsx index e6b4cfadfb..37b1a590e4 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routes/data.$id.tsx +++ b/benchmarks/memory/server/scenarios/serialization-payload/vue/src/routes/data.$id.tsx @@ -1,17 +1,20 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { makeSerializationPayload } from '../../../serialization-payload' +const DataComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+ Map size: {data.value.lookup.size} +
+ ) + }, +}) + export const Route = createFileRoute('/data/$id')({ loader: ({ params }) => makeSerializationPayload(params.id), component: DataComponent, }) - -function DataComponent() { - const data = Route.useLoaderData() - - return ( -
- Map size: {data.value.lookup.size} -
- ) -} diff --git a/benchmarks/memory/server/scenarios/serialization-payload/vue/vite.config.ts b/benchmarks/memory/server/scenarios/serialization-payload/vue/vite.config.ts index 41a5596adf..b63a561228 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/vite.config.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // Keep lazily-compiled code alive for the whole run: the pinned - // collections age code fast enough for V8 to flush unused bytecode, - // and the mid-measurement recompile injects a multi-MB allocation - // burst at a run-dependent time. - execArgv: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), name: '@benchmarks/memory-server serialization-payload (vue)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/memory.bench.ts b/benchmarks/memory/server/scenarios/server-fn-churn/react/memory.bench.ts index 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/server-fn-churn/react/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) } }) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/react/vite.config.ts b/benchmarks/memory/server/scenarios/server-fn-churn/react/vite.config.ts index 68d9ed839b..f72cc53d6f 100644 --- a/benchmarks/memory/server/scenarios/server-fn-churn/react/vite.config.ts +++ b/benchmarks/memory/server/scenarios/server-fn-churn/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // Keep lazily-compiled code alive for the whole run: the pinned - // collections age code fast enough for V8 to flush unused bytecode, - // and the mid-measurement recompile injects a multi-MB allocation - // burst at a run-dependent time. - execArgv: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), name: '@benchmarks/memory-server server-fn-churn (react)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts b/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts index 6e2959e757..167b24d3b6 100644 --- a/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts +++ b/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts @@ -38,8 +38,6 @@ type SerovalNode = const benchmarkSeed = 0xdecafbad const payloadSeed = 0x51f0cafe const fixtureCount = 16 -// Sized to sit just above the 2s measured-run floor on CI (per-iteration -// cost with the pinned collection is ~0.08-0.11s across frameworks). const serverFnChurnIterations = 30 const origin = 'http://localhost' const tssContentTypeFramed = 'application/x-tss-framed' @@ -204,11 +202,10 @@ export async function createWorkloadGroup( handler: StartRequestHandler, ) { const urls = await discoverUrls(handler) - const run = () => + const run = async () => runSequentialRequestLoop(handler, { seed: benchmarkSeed, iterations: serverFnChurnIterations, - pinGcBetweenIterations: true, buildRequest: (_random, index) => { const fixtureIndex = Math.floor(index / 2) % fixtureCount diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/server-fn-churn/solid/memory.bench.ts index 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/server-fn-churn/solid/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) } }) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/solid/vite.config.ts b/benchmarks/memory/server/scenarios/server-fn-churn/solid/vite.config.ts index 8d6d226e97..4fba196bd2 100644 --- a/benchmarks/memory/server/scenarios/server-fn-churn/solid/vite.config.ts +++ b/benchmarks/memory/server/scenarios/server-fn-churn/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // Keep lazily-compiled code alive for the whole run: the pinned - // collections age code fast enough for V8 to flush unused bytecode, - // and the mid-measurement recompile injects a multi-MB allocation - // burst at a run-dependent time. - execArgv: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), name: '@benchmarks/memory-server server-fn-churn (solid)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/server-fn-churn/vue/memory.bench.ts index 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/server-fn-churn/vue/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) } }) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/vue/vite.config.ts b/benchmarks/memory/server/scenarios/server-fn-churn/vue/vite.config.ts index 0e249b9f3b..5ab5ec37e3 100644 --- a/benchmarks/memory/server/scenarios/server-fn-churn/vue/vite.config.ts +++ b/benchmarks/memory/server/scenarios/server-fn-churn/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // Keep lazily-compiled code alive for the whole run: the pinned - // collections age code fast enough for V8 to flush unused bytecode, - // and the mid-measurement recompile injects a multi-MB allocation - // burst at a run-dependent time. - execArgv: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), name: '@benchmarks/memory-server server-fn-churn (vue)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/memory.bench.ts b/benchmarks/memory/server/scenarios/streaming-peak/react/memory.bench.ts index 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/react/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) } }) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/react/vite.config.ts b/benchmarks/memory/server/scenarios/streaming-peak/react/vite.config.ts index 5af0f0d138..5d555441b6 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/vite.config.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // Keep lazily-compiled code alive for the whole run: the pinned - // collections age code fast enough for V8 to flush unused bytecode, - // and the mid-measurement recompile injects a multi-MB allocation - // burst at a run-dependent time. - execArgv: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), name: '@benchmarks/memory-server streaming-peak (react)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/streaming-peak/shared.ts b/benchmarks/memory/server/scenarios/streaming-peak/shared.ts index 6b45470329..c027047408 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/shared.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/shared.ts @@ -9,7 +9,7 @@ export type { StartRequestHandler } type Framework = 'react' | 'solid' | 'vue' const benchmarkSeed = 0xdecafbad -const streamingPeakIterations = 20 +const streamingPeakIterations = 1 const fallbackMarker = 'streaming-peak-fallback-0' const requestInit = { @@ -50,7 +50,7 @@ async function readStreamingBody(response: Response) { let body = '' let chunkCount = 0 - while (true) { + for (;;) { const result = await reader.read() if (result.done) { @@ -92,18 +92,21 @@ export function createWorkloadGroup( framework: Framework, handler: StartRequestHandler, ) { - const run = () => + const run = async () => runSequentialRequestLoop(handler, { seed: benchmarkSeed, iterations: streamingPeakIterations, buildRequest: buildStreamingRequest, validateResponse: validateStreamingResponse, - pinGcBetweenIterations: true, - verifyGcFloor: true, }) return { - sanity: () => assertStreamingPeakSanity(handler), + sanity: async () => { + // Import the route chunks before checking streaming. Cold disk I/O can + // otherwise outlast the deferred payload and collapse the first response. + await run() + await assertStreamingPeakSanity(handler) + }, workloads: [ { name: `mem server streaming-peak chunked (${framework})`, diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.bench.ts index 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) } }) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/solid/vite.config.ts b/benchmarks/memory/server/scenarios/streaming-peak/solid/vite.config.ts index 18bf5b2d04..5fbdb48c23 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/vite.config.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // Keep lazily-compiled code alive for the whole run: the pinned - // collections age code fast enough for V8 to flush unused bytecode, - // and the mid-measurement recompile injects a multi-MB allocation - // burst at a run-dependent time. - execArgv: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), name: '@benchmarks/memory-server streaming-peak (solid)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.bench.ts b/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.bench.ts index 9a5c211fee..8b5f16ad63 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.bench.ts @@ -1,11 +1,16 @@ -import { bench, describe } from 'vitest' -import { memoryBenchOptions } from '#memory-server/bench-utils' +import { test } from 'vitest' +import { + memoryBenchHooks, + memoryBenchOptions, +} from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -describe('memory', () => { +test('memory', async ({ bench }) => { for (const workload of workloadGroup.workloads) { - bench(workload.name, workload.run, memoryBenchOptions) + await bench(workload.name, memoryBenchHooks(), workload.run).run( + memoryBenchOptions, + ) } }) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/stream.$id.tsx b/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/stream.$id.tsx index 0c71a8d3a0..750d1cb47d 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/stream.$id.tsx +++ b/benchmarks/memory/server/scenarios/streaming-peak/vue/src/routes/stream.$id.tsx @@ -1,5 +1,5 @@ import { Await, createFileRoute } from '@tanstack/vue-router' -import { Suspense } from 'vue' +import { Suspense, defineComponent } from 'vue' import { makeDeferredSectionPayload, type DeferredSectionPayload, @@ -7,6 +7,47 @@ import { const fallbackFlushTicks = 20 +const StreamComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => { + const deferredSections = [ + { index: 0, promise: data.value.deferred0 }, + { index: 1, promise: data.value.deferred1 }, + { index: 2, promise: data.value.deferred2 }, + { index: 3, promise: data.value.deferred3 }, + ] as const + + return ( +
+

{data.value.eager}

+ {deferredSections.map(({ index, promise }) => ( + <> +

+ streaming-peak-fallback-{index} +

+ + {{ + default: () => ( + ( + + )} + /> + ), + fallback: () => null, + }} + + + ))} +
+ ) + } + }, +}) + export const Route = createFileRoute('/stream/$id')({ loader: ({ params }) => ({ eager: `streaming-peak-eager-${params.id}`, @@ -48,42 +89,6 @@ function makeDeferredSection(id: string, sectionIndex: number) { ) } -function StreamComponent() { - const data = Route.useLoaderData() - const deferredSections = [ - { index: 0, promise: data.value.deferred0 }, - { index: 1, promise: data.value.deferred1 }, - { index: 2, promise: data.value.deferred2 }, - { index: 3, promise: data.value.deferred3 }, - ] as const - - return ( -
-

{data.value.eager}

- {deferredSections.map(({ index, promise }) => ( - <> -

- streaming-peak-fallback-{index} -

- - {{ - default: () => ( - ( - - )} - /> - ), - fallback: () => null, - }} - - - ))} -
- ) -} - function DeferredSection({ section }: { section: DeferredSectionPayload }) { const marker = `streaming-peak-deferred-${section.index}` diff --git a/benchmarks/memory/server/scenarios/streaming-peak/vue/vite.config.ts b/benchmarks/memory/server/scenarios/streaming-peak/vue/vite.config.ts index 7cd481da0b..cd848584a5 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/vite.config.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' +import { memoryConfig } from '../../../../runtime' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,19 +23,7 @@ export default defineConfig({ minify: false, }, test: { - // Keep lazily-compiled code alive for the whole run: the pinned - // collections age code fast enough for V8 to flush unused bytecode, - // and the mid-measurement recompile injects a multi-MB allocation - // burst at a run-dependent time. - execArgv: [ - '--no-flush-bytecode', - // Pre-size the V8 heap so no space has to grow mid-measurement: - // heap-growth events allocate several MB at a run-dependent moment, - // which flips the measured peak bimodally between identical runs. - '--initial-old-space-size=64', - '--min-semi-space-size=16', - '--max-semi-space-size=16', - ], + ...memoryConfig('server'), name: '@benchmarks/memory-server streaming-peak (vue)', watch: false, environment: 'node', diff --git a/benchmarks/memory/server/tsconfig.json b/benchmarks/memory/server/tsconfig.json index 5d5dcbf825..86d36f047a 100644 --- a/benchmarks/memory/server/tsconfig.json +++ b/benchmarks/memory/server/tsconfig.json @@ -3,5 +3,10 @@ "compilerOptions": { "types": ["node", "vite/client", "vitest/globals"] }, - "include": ["bench-utils.ts"] + "include": [ + "bench-utils.ts", + "scenarios/*/shared.ts", + "../runtime.ts", + "vitest.setup.ts" + ] } diff --git a/benchmarks/memory/tsconfig.json b/benchmarks/memory/tsconfig.json new file mode 100644 index 0000000000..5a325f3b6c --- /dev/null +++ b/benchmarks/memory/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "types": ["node"] + }, + "include": ["runtime.ts"] +} diff --git a/benchmarks/memory/turn.ts b/benchmarks/memory/turn.ts new file mode 100644 index 0000000000..08729685fe --- /dev/null +++ b/benchmarks/memory/turn.ts @@ -0,0 +1,34 @@ +export function isMemoryInstrumented() { + return ( + process.env.CODSPEED_ENV !== undefined && + process.env.CODSPEED_RUNNER_MODE === 'memory' + ) +} + +// CodSpeed calls beforeEach before its forced GC and measurement marker. End +// the previous warmup's job so WeakRef targets can be released by that GC. +export function endMemoryTurn() { + return new Promise((resolve) => setImmediate(resolve)) +} + +/** + * Per-invocation bench hooks. CodSpeed runs them around every warmup + * invocation and the measured one, outside the measurement marker: the turn + * ends first, then the workload prepares fresh state before the forced GC. + */ +export function memoryBenchHooks( + workload: { + before?: () => Promise | void + after?: () => Promise | void + } = {}, +) { + return { + async beforeEach() { + if (isMemoryInstrumented()) { + await endMemoryTurn() + } + await workload.before?.() + }, + afterEach: workload.after, + } +} diff --git a/benchmarks/ssr/README.md b/benchmarks/ssr/README.md index 625e1006c5..3d90af1598 100644 --- a/benchmarks/ssr/README.md +++ b/benchmarks/ssr/README.md @@ -98,3 +98,18 @@ Use `react`, `solid`, or `vue` for ``. The baseline projects use `@be - Server-function loops must include `sec-fetch-site: same-origin` so the default CSRF middleware accepts the request. - Loops that expect non-200 responses pass a custom `validateResponse` to `runRequestLoop`. - Bench loops must build deterministic requests from the seeded random helper and consume response bodies through `runRequestLoop` or `runSsrRequestLoop`. + +## Optional React Link workloads + +The [opt-in Link suite](../client-nav/README.md#opt-in-react-link-performance-suite) +adds focused standalone React Router SSR coverage for params/updaters, +inheritance, search middlewares, optional/splat segments, encoding, masks, +rewrites, and active props. Each timed batch creates four fresh routers and +renders their Links to HTML; it does not measure Start HTTP/streaming overhead. + +```bash +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:perf:ssr --outputStyle=stream --skipRemoteCache -- --run +``` + +These cases are excluded from this directory's aggregate projects and normal +CodSpeed dependency graph; they only run through the dedicated target above. diff --git a/benchmarks/ssr/bench-utils.test.ts b/benchmarks/ssr/bench-utils.test.ts new file mode 100644 index 0000000000..c6a520447b --- /dev/null +++ b/benchmarks/ssr/bench-utils.test.ts @@ -0,0 +1,145 @@ +import { describe, expect, it } from 'vitest' +import { buildRequestSequences, runRequestLoop } from './bench-utils' +import type { StartRequestHandler } from './bench-utils' + +function deferred() { + let resolve = () => {} + const promise = new Promise((resolvePromise) => { + resolve = resolvePromise + }) + return { promise, resolve } +} + +describe('runRequestLoop', () => { + it('caps fixed concurrency and waits for every streaming body', async () => { + const concurrency = 4 + const totalRequests = 20 + const firstWaveStarted = deferred() + let builtRequests = 0 + let executedRequests = 0 + let validatedResponses = 0 + let finishedBodies = 0 + let inFlightRequests = 0 + let maximumInFlightRequests = 0 + + const handler: StartRequestHandler = { + fetch() { + expect(builtRequests).toBe(totalRequests) + executedRequests += 1 + inFlightRequests += 1 + maximumInFlightRequests = Math.max( + maximumInFlightRequests, + inFlightRequests, + ) + + if (inFlightRequests === concurrency) { + firstWaveStarted.resolve() + } + + const body = new ReadableStream({ + async start(controller) { + await firstWaveStarted.promise + controller.enqueue(new Uint8Array([1])) + controller.close() + finishedBodies += 1 + inFlightRequests -= 1 + }, + }) + + return new Response(body) + }, + } + + await runRequestLoop(handler, { + seed: 123, + concurrency, + totalRequests, + buildRequest: (_random, index) => { + builtRequests += 1 + return new Request(`http://localhost/request/${index}`) + }, + validateResponse: () => { + validatedResponses += 1 + }, + }) + + expect(builtRequests).toBe(totalRequests) + expect(executedRequests).toBe(totalRequests) + expect(validatedResponses).toBe(totalRequests) + expect(maximumInFlightRequests).toBe(concurrency) + expect(inFlightRequests).toBe(0) + expect(finishedBodies).toBe(totalRequests) + }) + + it('builds identical predetermined worker sequences from identical seeds', () => { + const buildSequences = (seed: number) => + buildRequestSequences({ + seed, + concurrency: 4, + totalRequests: 12, + buildRequest: (random, index) => + new Request( + `http://localhost/request/${index}?value=${random().toString(36)}`, + ), + }).map((requests) => requests.map((request) => request.url)) + + const first = buildSequences(456) + const second = buildSequences(456) + + expect(second).toEqual(first) + expect(first.map((requests) => requests.map(requestIndex))).toEqual([ + [0, 4, 8], + [1, 5, 9], + [2, 6, 10], + [3, 7, 11], + ]) + }) + + it('drains every started body before reporting a worker failure', async () => { + const concurrency = 4 + const firstWaveStarted = deferred() + let executedRequests = 0 + let finishedBodies = 0 + let inFlightRequests = 0 + + const handler: StartRequestHandler = { + fetch(request) { + executedRequests += 1 + inFlightRequests += 1 + if (inFlightRequests === concurrency) { + firstWaveStarted.resolve() + } + + const body = new ReadableStream({ + async start(controller) { + await firstWaveStarted.promise + controller.close() + finishedBodies += 1 + inFlightRequests -= 1 + }, + }) + + return new Response(body, { + status: request.url.endsWith('/0') ? 500 : 200, + }) + }, + } + + await expect( + runRequestLoop(handler, { + seed: 789, + concurrency, + totalRequests: 12, + buildRequest: (_random, index) => + new Request(`http://localhost/request/${index}`), + }), + ).rejects.toThrow('non-200 status 500') + + expect(finishedBodies).toBe(executedRequests) + expect(inFlightRequests).toBe(0) + }) +}) + +function requestIndex(url: string) { + return Number(new URL(url).pathname.split('/').at(-1)) +} diff --git a/benchmarks/ssr/bench-utils.ts b/benchmarks/ssr/bench-utils.ts index 353c56cb4b..7a54fce897 100644 --- a/benchmarks/ssr/bench-utils.ts +++ b/benchmarks/ssr/bench-utils.ts @@ -9,7 +9,8 @@ export interface RunSsrRequestLoopOptions { export interface RunRequestLoopOptions { seed: number - iterations?: number + concurrency: number + totalRequests: number buildRequest: (random: () => number, index: number) => Request validateResponse?: (response: Response, request: Request) => void } @@ -99,13 +100,18 @@ export async function runRequestLoop( handler: StartRequestHandler, { seed, - iterations = 10, + concurrency, + totalRequests, buildRequest, validateResponse, }: RunRequestLoopOptions, ) { - const random = createDeterministicRandom(seed) - const pendingBodyReads: Array> = [] + const requestSequences = buildRequestSequences({ + seed, + concurrency, + totalRequests, + buildRequest, + }) const validate = validateResponse ?? ((response: Response, request: Request) => { @@ -116,20 +122,84 @@ export async function runRequestLoop( } }) - for (let index = 0; index < iterations; index++) { - const request = buildRequest(random, index) - const response = await handler.fetch(request) + let startWorkers = () => {} + const startBarrier = new Promise((resolve) => { + startWorkers = resolve + }) - try { - validate(response, request) - } catch (error) { - await Promise.allSettled(pendingBodyReads) + const workers = requestSequences.map(async (requests) => { + await startBarrier - throw error + for (const request of requests) { + const response = await handler.fetch(request) + let validationFailure: { error: unknown } | undefined + + try { + validate(response, request) + } catch (error) { + validationFailure = { error } + } + + await drainResponse(response) + + if (validationFailure) { + throw validationFailure.error + } } + }) - pendingBodyReads.push(drainResponse(response)) + startWorkers() + const results = await Promise.allSettled(workers) + const failedWorker = results.find( + (result): result is PromiseRejectedResult => result.status === 'rejected', + ) + + if (failedWorker) { + throw failedWorker.reason + } +} + +export type BuildRequestSequencesOptions = Pick< + RunRequestLoopOptions, + 'seed' | 'concurrency' | 'totalRequests' | 'buildRequest' +> + +/** + * Build the entire seeded workload before any request starts, then partition + * it round-robin so completion timing can never change a worker's next input. + */ +export function buildRequestSequences({ + seed, + concurrency, + totalRequests, + buildRequest, +}: BuildRequestSequencesOptions): Array> { + assertPositiveInteger('concurrency', concurrency) + assertPositiveInteger('totalRequests', totalRequests) + + if (concurrency > totalRequests) { + throw new RangeError( + `concurrency (${concurrency}) cannot exceed totalRequests (${totalRequests})`, + ) } - await Promise.all(pendingBodyReads) + const random = createDeterministicRandom(seed) + const requestSequences = Array.from( + { length: concurrency }, + () => new Array(), + ) + + for (let index = 0; index < totalRequests; index++) { + requestSequences[index % concurrency]!.push(buildRequest(random, index)) + } + + return requestSequences +} + +function assertPositiveInteger(name: string, value: number) { + if (!Number.isSafeInteger(value) || value < 1) { + throw new RangeError( + `${name} must be a positive integer; received ${value}`, + ) + } } diff --git a/benchmarks/ssr/package.json b/benchmarks/ssr/package.json index 40cd97df5e..20c1837468 100644 --- a/benchmarks/ssr/package.json +++ b/benchmarks/ssr/package.json @@ -15,14 +15,17 @@ "vue": "^3.5.16" }, "devDependencies": { - "@codspeed/vitest-plugin": "^5.5.0", + "@codspeed/vitest-plugin": "^6.0.1", "@vitejs/plugin-react": "^6.0.1", "@vitejs/plugin-vue-jsx": "^5.1.5", - "seroval": "^1.5.4", - "typescript": "^6.0.2", + "@types/react": "catalog:", + "seroval": "^1.6.7", + "@typescript/native": "npm:typescript@^7.0.2", + "jsdom": "29.1.1", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11", - "vitest": "^4.1.4" + "vitest": "catalog:" }, "nx": { "targets": { @@ -113,7 +116,14 @@ "build:vue" ], "options": { - "command": "NODE_ENV=production vitest bench", + "command": "NODE_ENV=production vitest bench --mode benchmark", + "cwd": "benchmarks/ssr" + } + }, + "test:unit": { + "executor": "nx:run-commands", + "options": { + "command": "vitest run --config ./vitest.unit.config.ts", "cwd": "benchmarks/ssr" } }, @@ -124,7 +134,7 @@ "build:react" ], "options": { - "command": "NODE_ENV=production vitest bench --config ./vitest.react.config.ts", + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.react.config.ts", "cwd": "benchmarks/ssr" } }, @@ -135,7 +145,7 @@ "build:solid" ], "options": { - "command": "NODE_ENV=production vitest bench --config ./vitest.solid.config.ts", + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.solid.config.ts", "cwd": "benchmarks/ssr" } }, @@ -146,12 +156,16 @@ "build:vue" ], "options": { - "command": "NODE_ENV=production vitest bench --config ./vitest.vue.config.ts", + "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.vue.config.ts", "cwd": "benchmarks/ssr" } }, "test:types": { - "executor": "nx:noop", + "executor": "nx:run-commands", + "options": { + "command": "tsc -p ./tsconfig.json --noEmit", + "cwd": "benchmarks/ssr" + }, "dependsOn": [ { "projects": [ @@ -203,6 +217,13 @@ ], "target": "test:types:ssr" } + ], + "inputs": [ + "default", + "^production", + "{workspaceRoot}/eslint.config.js", + "{workspaceRoot}/benchmarks/cpu-simulation.ts", + "dependentTaskOutputs" ] } } diff --git a/benchmarks/ssr/react/speed.bench.ts b/benchmarks/ssr/react/speed.bench.ts index 419b1ccb36..6825a7ddfb 100644 --- a/benchmarks/ssr/react/speed.bench.ts +++ b/benchmarks/ssr/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { runSsrRequestLoop } from '../bench-utils' import type { StartRequestHandler } from '../bench-utils' @@ -11,14 +11,12 @@ const { default: handler } = (await import( default: StartRequestHandler } -describe('ssr', () => { - bench( - 'ssr request loop (react)', - () => runSsrRequestLoop(handler, { seed: benchmarkSeed }), - { - warmupIterations: 100, - time: 10_000, - throws: true, - }, - ) +test('ssr', async ({ bench }) => { + await bench('ssr request loop (react)', async () => + runSsrRequestLoop(handler, { seed: benchmarkSeed }), + ).run({ + warmupIterations: 100, + time: 10_000, + throws: true, + }) }) diff --git a/benchmarks/ssr/react/vite.config.ts b/benchmarks/ssr/react/vite.config.ts index 04f15c3959..e607db366b 100644 --- a/benchmarks/ssr/react/vite.config.ts +++ b/benchmarks/ssr/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/assets/react/speed.assets-linked-css-control.bench.ts b/benchmarks/ssr/scenarios/assets/react/speed.assets-linked-css-control.bench.ts new file mode 100644 index 0000000000..0496613afb --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/react/speed.assets-linked-css-control.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertAssetsScenario, + assetsBenchOptions, + runAssetsLinkedControlLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertAssetsScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr assets linked-css control (react)', async () => + runAssetsLinkedControlLoop(handler), + ).run(assetsBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/assets/react/speed.bench.ts b/benchmarks/ssr/scenarios/assets/react/speed.bench.ts index a54042cd86..7dc57d89f1 100644 --- a/benchmarks/ssr/scenarios/assets/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/assets/react/speed.bench.ts @@ -1,11 +1,10 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertAssetsScenario, assetsBenchOptions, runAssetsInlineLoop, - runAssetsLinkedControlLoop, - type StartRequestHandler, } from '../shared' +import type { StartRequestHandler } from '../shared' const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href @@ -17,15 +16,8 @@ const { default: handler } = (await import( await assertAssetsScenario(handler) -describe('ssr', () => { - bench( - 'ssr assets inline-css cdn (react)', - () => runAssetsInlineLoop(handler), - assetsBenchOptions, - ) - bench( - 'ssr assets linked-css control (react)', - () => runAssetsLinkedControlLoop(handler), - assetsBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr assets inline-css cdn (react)', async () => + runAssetsInlineLoop(handler), + ).run(assetsBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/assets/react/tsconfig.json b/benchmarks/ssr/scenarios/assets/react/tsconfig.json index 91027bfc88..cf14e1d440 100644 --- a/benchmarks/ssr/scenarios/assets/react/tsconfig.json +++ b/benchmarks/ssr/scenarios/assets/react/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/assets/react/vite.config.ts b/benchmarks/ssr/scenarios/assets/react/vite.config.ts index 91534d3de8..5990bba6d3 100644 --- a/benchmarks/ssr/scenarios/assets/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/assets/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -27,6 +28,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr assets (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/assets/shared.ts b/benchmarks/ssr/scenarios/assets/shared.ts index 3974988698..ec811794e3 100644 --- a/benchmarks/ssr/scenarios/assets/shared.ts +++ b/benchmarks/ssr/scenarios/assets/shared.ts @@ -7,8 +7,8 @@ export type { StartRequestHandler } const benchmarkSeed = 0xdecafbad const origin = 'http://localhost' const cdnOrigin = 'https://cdn.example.com' -const inlineCssLoopIterations = 25 -const linkedCssLoopIterations = 30 +const inlineCssLoopTotalRequests = 32 +const linkedCssLoopTotalRequests = 32 const inlineRequestInit = { method: 'GET', @@ -41,7 +41,8 @@ function buildAssetsRequest(random: () => number, requestInit: RequestInit) { export function runAssetsInlineLoop(handler: StartRequestHandler) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: inlineCssLoopIterations, + concurrency: 16, + totalRequests: inlineCssLoopTotalRequests, buildRequest: (random) => buildAssetsRequest(random, inlineRequestInit), }) } @@ -49,7 +50,8 @@ export function runAssetsInlineLoop(handler: StartRequestHandler) { export function runAssetsLinkedControlLoop(handler: StartRequestHandler) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: linkedCssLoopIterations, + concurrency: 16, + totalRequests: linkedCssLoopTotalRequests, buildRequest: (random) => buildAssetsRequest(random, linkedRequestInit), }) } diff --git a/benchmarks/ssr/scenarios/assets/solid/speed.assets-linked-css-control.bench.ts b/benchmarks/ssr/scenarios/assets/solid/speed.assets-linked-css-control.bench.ts new file mode 100644 index 0000000000..d159124a04 --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/solid/speed.assets-linked-css-control.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertAssetsScenario, + assetsBenchOptions, + runAssetsLinkedControlLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertAssetsScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr assets linked-css control (solid)', async () => + runAssetsLinkedControlLoop(handler), + ).run(assetsBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/assets/solid/speed.bench.ts b/benchmarks/ssr/scenarios/assets/solid/speed.bench.ts index 49d7722163..47f483df11 100644 --- a/benchmarks/ssr/scenarios/assets/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/assets/solid/speed.bench.ts @@ -1,11 +1,10 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertAssetsScenario, assetsBenchOptions, runAssetsInlineLoop, - runAssetsLinkedControlLoop, - type StartRequestHandler, } from '../shared' +import type { StartRequestHandler } from '../shared' const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href @@ -17,15 +16,8 @@ const { default: handler } = (await import( await assertAssetsScenario(handler) -describe('ssr', () => { - bench( - 'ssr assets inline-css cdn (solid)', - () => runAssetsInlineLoop(handler), - assetsBenchOptions, - ) - bench( - 'ssr assets linked-css control (solid)', - () => runAssetsLinkedControlLoop(handler), - assetsBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr assets inline-css cdn (solid)', async () => + runAssetsInlineLoop(handler), + ).run(assetsBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/assets/solid/tsconfig.json b/benchmarks/ssr/scenarios/assets/solid/tsconfig.json index b1806caa67..42c3a2160f 100644 --- a/benchmarks/ssr/scenarios/assets/solid/tsconfig.json +++ b/benchmarks/ssr/scenarios/assets/solid/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/assets/solid/vite.config.ts b/benchmarks/ssr/scenarios/assets/solid/vite.config.ts index 788ac1f5b8..3ee54e5ae2 100644 --- a/benchmarks/ssr/scenarios/assets/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/assets/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -27,6 +28,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr assets (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/assets/vue/speed.assets-linked-css-control.bench.ts b/benchmarks/ssr/scenarios/assets/vue/speed.assets-linked-css-control.bench.ts new file mode 100644 index 0000000000..e56d41df6b --- /dev/null +++ b/benchmarks/ssr/scenarios/assets/vue/speed.assets-linked-css-control.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertAssetsScenario, + assetsBenchOptions, + runAssetsLinkedControlLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertAssetsScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr assets linked-css control (vue)', async () => + runAssetsLinkedControlLoop(handler), + ).run(assetsBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/assets/vue/speed.bench.ts b/benchmarks/ssr/scenarios/assets/vue/speed.bench.ts index 01eb3b9d5a..3f77a0dcc1 100644 --- a/benchmarks/ssr/scenarios/assets/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/assets/vue/speed.bench.ts @@ -1,11 +1,10 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertAssetsScenario, assetsBenchOptions, runAssetsInlineLoop, - runAssetsLinkedControlLoop, - type StartRequestHandler, } from '../shared' +import type { StartRequestHandler } from '../shared' const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href @@ -17,15 +16,8 @@ const { default: handler } = (await import( await assertAssetsScenario(handler) -describe('ssr', () => { - bench( - 'ssr assets inline-css cdn (vue)', - () => runAssetsInlineLoop(handler), - assetsBenchOptions, - ) - bench( - 'ssr assets linked-css control (vue)', - () => runAssetsLinkedControlLoop(handler), - assetsBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr assets inline-css cdn (vue)', async () => + runAssetsInlineLoop(handler), + ).run(assetsBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.$y.tsx b/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.$y.tsx index a20e292938..a29fe59f22 100644 --- a/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.$y.tsx +++ b/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.$y.tsx @@ -1,6 +1,21 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import '../styles/assets-leaf.css' +const LeafComponent = defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
+

+ assets-leaf-{params.value.x}-{params.value.y} +

+
+ ) + }, +}) + export const Route = createFileRoute('/a/$x/$y')({ head: ({ params }) => ({ meta: [{ title: `SSR Assets ${params.x} ${params.y}` }], @@ -12,15 +27,3 @@ export const Route = createFileRoute('/a/$x/$y')({ }), component: LeafComponent, }) - -function LeafComponent() { - const params = Route.useParams() - - return ( -
-

- assets-leaf-{params.value.x}-{params.value.y} -

-
- ) -} diff --git a/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.tsx b/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.tsx index f8038f6f28..e1fe0418e4 100644 --- a/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.tsx +++ b/benchmarks/ssr/scenarios/assets/vue/src/routes/a.$x.tsx @@ -1,6 +1,20 @@ +import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import '../styles/assets-a.css' +const LevelAComponent = defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
+

assets-level-a-{params.value.x}

+ +
+ ) + }, +}) + export const Route = createFileRoute('/a/$x')({ head: ({ params }) => ({ meta: [{ title: `SSR Assets ${params.x}` }], @@ -12,14 +26,3 @@ export const Route = createFileRoute('/a/$x')({ }), component: LevelAComponent, }) - -function LevelAComponent() { - const params = Route.useParams() - - return ( -
-

assets-level-a-{params.value.x}

- -
- ) -} diff --git a/benchmarks/ssr/scenarios/assets/vue/tsconfig.json b/benchmarks/ssr/scenarios/assets/vue/tsconfig.json index 4fe3ccecb1..08c94853f4 100644 --- a/benchmarks/ssr/scenarios/assets/vue/tsconfig.json +++ b/benchmarks/ssr/scenarios/assets/vue/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/assets/vue/vite.config.ts b/benchmarks/ssr/scenarios/assets/vue/vite.config.ts index 8beb38c972..e664b9b02b 100644 --- a/benchmarks/ssr/scenarios/assets/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/assets/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -27,6 +28,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr assets (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/before-load/react/speed.bench.ts b/benchmarks/ssr/scenarios/before-load/react/speed.bench.ts index 09073687c0..8a4355a168 100644 --- a/benchmarks/ssr/scenarios/before-load/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/before-load/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertBeforeLoadScenario, beforeLoadBenchOptions, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertBeforeLoadScenario(handler) -describe('ssr', () => { - bench( - 'ssr before-load chain (react)', - () => runBeforeLoadLoop(handler), - beforeLoadBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr before-load chain (react)', async () => + runBeforeLoadLoop(handler), + ).run(beforeLoadBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/before-load/react/vite.config.ts b/benchmarks/ssr/scenarios/before-load/react/vite.config.ts index 2767b85787..3fd72c5f1d 100644 --- a/benchmarks/ssr/scenarios/before-load/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/before-load/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr before-load (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/before-load/shared-bench.ts b/benchmarks/ssr/scenarios/before-load/shared-bench.ts index 39579fc818..cf3a02f114 100644 --- a/benchmarks/ssr/scenarios/before-load/shared-bench.ts +++ b/benchmarks/ssr/scenarios/before-load/shared-bench.ts @@ -5,7 +5,7 @@ import type { StartRequestHandler } from '../../bench-utils' export type { StartRequestHandler } const benchmarkSeed = 0xdecafbad -const beforeLoadLoopIterations = 30 +const beforeLoadLoopTotalRequests = 32 const requestInit = { method: 'GET', @@ -57,7 +57,8 @@ export const beforeLoadBenchOptions = { export function runBeforeLoadLoop(handler: StartRequestHandler) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: beforeLoadLoopIterations, + concurrency: 16, + totalRequests: beforeLoadLoopTotalRequests, buildRequest: buildBeforeLoadRequest, }) } diff --git a/benchmarks/ssr/scenarios/before-load/solid/speed.bench.ts b/benchmarks/ssr/scenarios/before-load/solid/speed.bench.ts index 5f6e8baf8a..27e0d3a64c 100644 --- a/benchmarks/ssr/scenarios/before-load/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/before-load/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertBeforeLoadScenario, beforeLoadBenchOptions, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertBeforeLoadScenario(handler) -describe('ssr', () => { - bench( - 'ssr before-load chain (solid)', - () => runBeforeLoadLoop(handler), - beforeLoadBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr before-load chain (solid)', async () => + runBeforeLoadLoop(handler), + ).run(beforeLoadBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/before-load/solid/vite.config.ts b/benchmarks/ssr/scenarios/before-load/solid/vite.config.ts index ea0177e059..a20e32742e 100644 --- a/benchmarks/ssr/scenarios/before-load/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/before-load/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr before-load (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/before-load/vue/speed.bench.ts b/benchmarks/ssr/scenarios/before-load/vue/speed.bench.ts index d2cfd6814b..8684c159eb 100644 --- a/benchmarks/ssr/scenarios/before-load/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/before-load/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertBeforeLoadScenario, beforeLoadBenchOptions, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertBeforeLoadScenario(handler) -describe('ssr', () => { - bench( - 'ssr before-load chain (vue)', - () => runBeforeLoadLoop(handler), - beforeLoadBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr before-load chain (vue)', async () => + runBeforeLoadLoop(handler), + ).run(beforeLoadBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.$b.$c.tsx b/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.$b.$c.tsx index 118e16553b..178d4071eb 100644 --- a/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.$b.$c.tsx +++ b/benchmarks/ssr/scenarios/before-load/vue/src/routes/$a.$b.$c.tsx @@ -1,6 +1,15 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { makeBeforeLoadMarker, type BeforeLoadContext } from '../../../shared' +const LevelCComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () =>
{data.value.marker}
+ }, +}) + export const Route = createFileRoute('/$a/$b/$c')({ beforeLoad: ({ params, context }) => { const parent = context as BeforeLoadContext @@ -15,9 +24,3 @@ export const Route = createFileRoute('/$a/$b/$c')({ }), component: LevelCComponent, }) - -function LevelCComponent() { - const data = Route.useLoaderData() - - return
{data.value.marker}
-} diff --git a/benchmarks/ssr/scenarios/before-load/vue/vite.config.ts b/benchmarks/ssr/scenarios/before-load/vue/vite.config.ts index 181200a004..093776869f 100644 --- a/benchmarks/ssr/scenarios/before-load/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/before-load/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr before-load (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts b/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts index 4fca8eb477..899f400799 100644 --- a/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts @@ -1,12 +1,8 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, - runErrorLoop, - runNotFoundLoop, runRedirectLoop, - runRouteHeadersLoop, - runUnmatchedLoop, } from '../shared' import type { StartRequestHandler } from '../shared' @@ -20,34 +16,8 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -describe('ssr', () => { - bench( - 'ssr redirect (react)', - () => runRedirectLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr not-found (react)', - () => runNotFoundLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr control-flow error 500 (react)', - () => runErrorLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr control-flow unmatched 404 (react)', - () => runUnmatchedLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr control-flow route headers (react)', - () => runRouteHeadersLoop(handler), +test('ssr', async ({ bench }) => { + await bench('ssr redirect (react)', async () => runRedirectLoop(handler)).run( controlFlowBenchOptions, ) }) diff --git a/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-error-500.bench.ts b/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-error-500.bench.ts new file mode 100644 index 0000000000..0a93c5eac3 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-error-500.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runErrorLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow error 500 (react)', async () => + runErrorLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-route-headers.bench.ts b/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-route-headers.bench.ts new file mode 100644 index 0000000000..53e09fd34e --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-route-headers.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runRouteHeadersLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow route headers (react)', async () => + runRouteHeadersLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-unmatched-404.bench.ts b/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-unmatched-404.bench.ts new file mode 100644 index 0000000000..1cd7c1044c --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/speed.control-flow-unmatched-404.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runUnmatchedLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow unmatched 404 (react)', async () => + runUnmatchedLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/react/speed.not-found.bench.ts b/benchmarks/ssr/scenarios/control-flow/react/speed.not-found.bench.ts new file mode 100644 index 0000000000..1e8abfd318 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/react/speed.not-found.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runNotFoundLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr not-found (react)', async () => + runNotFoundLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/control-flow/react/src/routeTree.gen.ts index ed682bf62f..4d4424c222 100644 --- a/benchmarks/ssr/scenarios/control-flow/react/src/routeTree.gen.ts +++ b/benchmarks/ssr/scenarios/control-flow/react/src/routeTree.gen.ts @@ -10,30 +10,20 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as TargetIdRouteImport } from './routes/target.$id' -import { Route as MissingIdRouteImport } from './routes/missing.$id' -import { Route as HeadersIdRouteImport } from './routes/headers.$id' -import { Route as FromIdRouteImport } from './routes/from.$id' import { Route as BoomIdRouteImport } from './routes/boom.$id' +import { Route as FromIdRouteImport } from './routes/from.$id' +import { Route as HeadersIdRouteImport } from './routes/headers.$id' +import { Route as MissingIdRouteImport } from './routes/missing.$id' +import { Route as TargetIdRouteImport } from './routes/target.$id' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const TargetIdRoute = TargetIdRouteImport.update({ - id: '/target/$id', - path: '/target/$id', - getParentRoute: () => rootRouteImport, -} as any) -const MissingIdRoute = MissingIdRouteImport.update({ - id: '/missing/$id', - path: '/missing/$id', - getParentRoute: () => rootRouteImport, -} as any) -const HeadersIdRoute = HeadersIdRouteImport.update({ - id: '/headers/$id', - path: '/headers/$id', +const BoomIdRoute = BoomIdRouteImport.update({ + id: '/boom/$id', + path: '/boom/$id', getParentRoute: () => rootRouteImport, } as any) const FromIdRoute = FromIdRouteImport.update({ @@ -41,9 +31,19 @@ const FromIdRoute = FromIdRouteImport.update({ path: '/from/$id', getParentRoute: () => rootRouteImport, } as any) -const BoomIdRoute = BoomIdRouteImport.update({ - id: '/boom/$id', - path: '/boom/$id', +const HeadersIdRoute = HeadersIdRouteImport.update({ + id: '/headers/$id', + path: '/headers/$id', + getParentRoute: () => rootRouteImport, +} as any) +const MissingIdRoute = MissingIdRouteImport.update({ + id: '/missing/$id', + path: '/missing/$id', + getParentRoute: () => rootRouteImport, +} as any) +const TargetIdRoute = TargetIdRouteImport.update({ + id: '/target/$id', + path: '/target/$id', getParentRoute: () => rootRouteImport, } as any) @@ -117,25 +117,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/target/$id': { - id: '/target/$id' - path: '/target/$id' - fullPath: '/target/$id' - preLoaderRoute: typeof TargetIdRouteImport - parentRoute: typeof rootRouteImport - } - '/missing/$id': { - id: '/missing/$id' - path: '/missing/$id' - fullPath: '/missing/$id' - preLoaderRoute: typeof MissingIdRouteImport - parentRoute: typeof rootRouteImport - } - '/headers/$id': { - id: '/headers/$id' - path: '/headers/$id' - fullPath: '/headers/$id' - preLoaderRoute: typeof HeadersIdRouteImport + '/boom/$id': { + id: '/boom/$id' + path: '/boom/$id' + fullPath: '/boom/$id' + preLoaderRoute: typeof BoomIdRouteImport parentRoute: typeof rootRouteImport } '/from/$id': { @@ -145,11 +131,25 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof FromIdRouteImport parentRoute: typeof rootRouteImport } - '/boom/$id': { - id: '/boom/$id' - path: '/boom/$id' - fullPath: '/boom/$id' - preLoaderRoute: typeof BoomIdRouteImport + '/headers/$id': { + id: '/headers/$id' + path: '/headers/$id' + fullPath: '/headers/$id' + preLoaderRoute: typeof HeadersIdRouteImport + parentRoute: typeof rootRouteImport + } + '/missing/$id': { + id: '/missing/$id' + path: '/missing/$id' + fullPath: '/missing/$id' + preLoaderRoute: typeof MissingIdRouteImport + parentRoute: typeof rootRouteImport + } + '/target/$id': { + id: '/target/$id' + path: '/target/$id' + fullPath: '/target/$id' + preLoaderRoute: typeof TargetIdRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/ssr/scenarios/control-flow/react/tsconfig.json b/benchmarks/ssr/scenarios/control-flow/react/tsconfig.json index 91027bfc88..cf14e1d440 100644 --- a/benchmarks/ssr/scenarios/control-flow/react/tsconfig.json +++ b/benchmarks/ssr/scenarios/control-flow/react/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/control-flow/react/vite.config.ts b/benchmarks/ssr/scenarios/control-flow/react/vite.config.ts index b15f7bc530..273d7d9d80 100644 --- a/benchmarks/ssr/scenarios/control-flow/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/control-flow/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr control-flow (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/control-flow/shared.ts b/benchmarks/ssr/scenarios/control-flow/shared.ts index 7b79683785..307665d59d 100644 --- a/benchmarks/ssr/scenarios/control-flow/shared.ts +++ b/benchmarks/ssr/scenarios/control-flow/shared.ts @@ -5,11 +5,11 @@ import type { StartRequestHandler } from '../../bench-utils' export type { StartRequestHandler } const benchmarkSeed = 0xdecafbad -const redirectLoopIterations = 100 -const notFoundLoopIterations = 45 -const errorLoopIterations = 45 -const unmatchedLoopIterations = 60 -const routeHeadersLoopIterations = 50 +const redirectLoopTotalRequests = 112 +const notFoundLoopTotalRequests = 48 +const errorLoopTotalRequests = 48 +const unmatchedLoopTotalRequests = 64 +const routeHeadersLoopTotalRequests = 64 // Pinned to the current built handler responses for these control-flow routes. const OK_STATUS = 200 @@ -124,7 +124,8 @@ function validateRouteHeadersResponse(response: Response, request: Request) { export function runRedirectLoop(handler: StartRequestHandler) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: redirectLoopIterations, + concurrency: 16, + totalRequests: redirectLoopTotalRequests, buildRequest: buildRedirectRequest, validateResponse: validateRedirectResponse, }) @@ -133,7 +134,8 @@ export function runRedirectLoop(handler: StartRequestHandler) { export function runNotFoundLoop(handler: StartRequestHandler) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: notFoundLoopIterations, + concurrency: 16, + totalRequests: notFoundLoopTotalRequests, buildRequest: buildNotFoundRequest, validateResponse: validateNotFoundResponse, }) @@ -142,7 +144,8 @@ export function runNotFoundLoop(handler: StartRequestHandler) { export function runErrorLoop(handler: StartRequestHandler) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: errorLoopIterations, + concurrency: 16, + totalRequests: errorLoopTotalRequests, buildRequest: buildErrorRequest, validateResponse: validateErrorResponse, }) @@ -151,7 +154,8 @@ export function runErrorLoop(handler: StartRequestHandler) { export function runUnmatchedLoop(handler: StartRequestHandler) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: unmatchedLoopIterations, + concurrency: 16, + totalRequests: unmatchedLoopTotalRequests, buildRequest: buildUnmatchedRequest, validateResponse: validateUnmatchedResponse, }) @@ -160,7 +164,8 @@ export function runUnmatchedLoop(handler: StartRequestHandler) { export function runRouteHeadersLoop(handler: StartRequestHandler) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: routeHeadersLoopIterations, + concurrency: 16, + totalRequests: routeHeadersLoopTotalRequests, buildRequest: buildRouteHeadersRequest, validateResponse: validateRouteHeadersResponse, }) diff --git a/benchmarks/ssr/scenarios/control-flow/solid/speed.bench.ts b/benchmarks/ssr/scenarios/control-flow/solid/speed.bench.ts index ed23ed45d7..904b693e25 100644 --- a/benchmarks/ssr/scenarios/control-flow/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/solid/speed.bench.ts @@ -1,12 +1,8 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, - runErrorLoop, - runNotFoundLoop, runRedirectLoop, - runRouteHeadersLoop, - runUnmatchedLoop, } from '../shared' import type { StartRequestHandler } from '../shared' @@ -20,34 +16,8 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -describe('ssr', () => { - bench( - 'ssr redirect (solid)', - () => runRedirectLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr not-found (solid)', - () => runNotFoundLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr control-flow error 500 (solid)', - () => runErrorLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr control-flow unmatched 404 (solid)', - () => runUnmatchedLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr control-flow route headers (solid)', - () => runRouteHeadersLoop(handler), +test('ssr', async ({ bench }) => { + await bench('ssr redirect (solid)', async () => runRedirectLoop(handler)).run( controlFlowBenchOptions, ) }) diff --git a/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-error-500.bench.ts b/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-error-500.bench.ts new file mode 100644 index 0000000000..57a2f0fbe9 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-error-500.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runErrorLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow error 500 (solid)', async () => + runErrorLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-route-headers.bench.ts b/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-route-headers.bench.ts new file mode 100644 index 0000000000..6581e92b39 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-route-headers.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runRouteHeadersLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow route headers (solid)', async () => + runRouteHeadersLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-unmatched-404.bench.ts b/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-unmatched-404.bench.ts new file mode 100644 index 0000000000..40f1679320 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/speed.control-flow-unmatched-404.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runUnmatchedLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow unmatched 404 (solid)', async () => + runUnmatchedLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/solid/speed.not-found.bench.ts b/benchmarks/ssr/scenarios/control-flow/solid/speed.not-found.bench.ts new file mode 100644 index 0000000000..efcb7cc229 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/solid/speed.not-found.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runNotFoundLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr not-found (solid)', async () => + runNotFoundLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/control-flow/solid/src/routeTree.gen.ts index 5e7342c172..3cec17d9c8 100644 --- a/benchmarks/ssr/scenarios/control-flow/solid/src/routeTree.gen.ts +++ b/benchmarks/ssr/scenarios/control-flow/solid/src/routeTree.gen.ts @@ -10,30 +10,20 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as TargetIdRouteImport } from './routes/target.$id' -import { Route as MissingIdRouteImport } from './routes/missing.$id' -import { Route as HeadersIdRouteImport } from './routes/headers.$id' -import { Route as FromIdRouteImport } from './routes/from.$id' import { Route as BoomIdRouteImport } from './routes/boom.$id' +import { Route as FromIdRouteImport } from './routes/from.$id' +import { Route as HeadersIdRouteImport } from './routes/headers.$id' +import { Route as MissingIdRouteImport } from './routes/missing.$id' +import { Route as TargetIdRouteImport } from './routes/target.$id' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const TargetIdRoute = TargetIdRouteImport.update({ - id: '/target/$id', - path: '/target/$id', - getParentRoute: () => rootRouteImport, -} as any) -const MissingIdRoute = MissingIdRouteImport.update({ - id: '/missing/$id', - path: '/missing/$id', - getParentRoute: () => rootRouteImport, -} as any) -const HeadersIdRoute = HeadersIdRouteImport.update({ - id: '/headers/$id', - path: '/headers/$id', +const BoomIdRoute = BoomIdRouteImport.update({ + id: '/boom/$id', + path: '/boom/$id', getParentRoute: () => rootRouteImport, } as any) const FromIdRoute = FromIdRouteImport.update({ @@ -41,9 +31,19 @@ const FromIdRoute = FromIdRouteImport.update({ path: '/from/$id', getParentRoute: () => rootRouteImport, } as any) -const BoomIdRoute = BoomIdRouteImport.update({ - id: '/boom/$id', - path: '/boom/$id', +const HeadersIdRoute = HeadersIdRouteImport.update({ + id: '/headers/$id', + path: '/headers/$id', + getParentRoute: () => rootRouteImport, +} as any) +const MissingIdRoute = MissingIdRouteImport.update({ + id: '/missing/$id', + path: '/missing/$id', + getParentRoute: () => rootRouteImport, +} as any) +const TargetIdRoute = TargetIdRouteImport.update({ + id: '/target/$id', + path: '/target/$id', getParentRoute: () => rootRouteImport, } as any) @@ -117,25 +117,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/target/$id': { - id: '/target/$id' - path: '/target/$id' - fullPath: '/target/$id' - preLoaderRoute: typeof TargetIdRouteImport - parentRoute: typeof rootRouteImport - } - '/missing/$id': { - id: '/missing/$id' - path: '/missing/$id' - fullPath: '/missing/$id' - preLoaderRoute: typeof MissingIdRouteImport - parentRoute: typeof rootRouteImport - } - '/headers/$id': { - id: '/headers/$id' - path: '/headers/$id' - fullPath: '/headers/$id' - preLoaderRoute: typeof HeadersIdRouteImport + '/boom/$id': { + id: '/boom/$id' + path: '/boom/$id' + fullPath: '/boom/$id' + preLoaderRoute: typeof BoomIdRouteImport parentRoute: typeof rootRouteImport } '/from/$id': { @@ -145,11 +131,25 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof FromIdRouteImport parentRoute: typeof rootRouteImport } - '/boom/$id': { - id: '/boom/$id' - path: '/boom/$id' - fullPath: '/boom/$id' - preLoaderRoute: typeof BoomIdRouteImport + '/headers/$id': { + id: '/headers/$id' + path: '/headers/$id' + fullPath: '/headers/$id' + preLoaderRoute: typeof HeadersIdRouteImport + parentRoute: typeof rootRouteImport + } + '/missing/$id': { + id: '/missing/$id' + path: '/missing/$id' + fullPath: '/missing/$id' + preLoaderRoute: typeof MissingIdRouteImport + parentRoute: typeof rootRouteImport + } + '/target/$id': { + id: '/target/$id' + path: '/target/$id' + fullPath: '/target/$id' + preLoaderRoute: typeof TargetIdRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/ssr/scenarios/control-flow/solid/tsconfig.json b/benchmarks/ssr/scenarios/control-flow/solid/tsconfig.json index b1806caa67..42c3a2160f 100644 --- a/benchmarks/ssr/scenarios/control-flow/solid/tsconfig.json +++ b/benchmarks/ssr/scenarios/control-flow/solid/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/control-flow/solid/vite.config.ts b/benchmarks/ssr/scenarios/control-flow/solid/vite.config.ts index 0bcd175f60..c75c957466 100644 --- a/benchmarks/ssr/scenarios/control-flow/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/control-flow/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr control-flow (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts b/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts index 99bb46dfb3..0b95f426f2 100644 --- a/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts @@ -1,12 +1,8 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, - runErrorLoop, - runNotFoundLoop, runRedirectLoop, - runRouteHeadersLoop, - runUnmatchedLoop, } from '../shared' import type { StartRequestHandler } from '../shared' @@ -20,34 +16,8 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -describe('ssr', () => { - bench( - 'ssr redirect (vue)', - () => runRedirectLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr not-found (vue)', - () => runNotFoundLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr control-flow error 500 (vue)', - () => runErrorLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr control-flow unmatched 404 (vue)', - () => runUnmatchedLoop(handler), - controlFlowBenchOptions, - ) - - bench( - 'ssr control-flow route headers (vue)', - () => runRouteHeadersLoop(handler), +test('ssr', async ({ bench }) => { + await bench('ssr redirect (vue)', async () => runRedirectLoop(handler)).run( controlFlowBenchOptions, ) }) diff --git a/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-error-500.bench.ts b/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-error-500.bench.ts new file mode 100644 index 0000000000..262ca951af --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-error-500.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runErrorLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow error 500 (vue)', async () => + runErrorLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-route-headers.bench.ts b/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-route-headers.bench.ts new file mode 100644 index 0000000000..bf8c90a8a1 --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-route-headers.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runRouteHeadersLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow route headers (vue)', async () => + runRouteHeadersLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-unmatched-404.bench.ts b/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-unmatched-404.bench.ts new file mode 100644 index 0000000000..d7f8ebeb9e --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/speed.control-flow-unmatched-404.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runUnmatchedLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr control-flow unmatched 404 (vue)', async () => + runUnmatchedLoop(handler), + ).run(controlFlowBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/vue/speed.not-found.bench.ts b/benchmarks/ssr/scenarios/control-flow/vue/speed.not-found.bench.ts new file mode 100644 index 0000000000..4b84fb594c --- /dev/null +++ b/benchmarks/ssr/scenarios/control-flow/vue/speed.not-found.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertControlFlowSanity, + controlFlowBenchOptions, + runNotFoundLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertControlFlowSanity(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr not-found (vue)', async () => runNotFoundLoop(handler)).run( + controlFlowBenchOptions, + ) +}) diff --git a/benchmarks/ssr/scenarios/control-flow/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/control-flow/vue/src/routeTree.gen.ts index f5063d1c09..6dcf0d095e 100644 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/routeTree.gen.ts +++ b/benchmarks/ssr/scenarios/control-flow/vue/src/routeTree.gen.ts @@ -10,30 +10,20 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as TargetIdRouteImport } from './routes/target.$id' -import { Route as MissingIdRouteImport } from './routes/missing.$id' -import { Route as HeadersIdRouteImport } from './routes/headers.$id' -import { Route as FromIdRouteImport } from './routes/from.$id' import { Route as BoomIdRouteImport } from './routes/boom.$id' +import { Route as FromIdRouteImport } from './routes/from.$id' +import { Route as HeadersIdRouteImport } from './routes/headers.$id' +import { Route as MissingIdRouteImport } from './routes/missing.$id' +import { Route as TargetIdRouteImport } from './routes/target.$id' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const TargetIdRoute = TargetIdRouteImport.update({ - id: '/target/$id', - path: '/target/$id', - getParentRoute: () => rootRouteImport, -} as any) -const MissingIdRoute = MissingIdRouteImport.update({ - id: '/missing/$id', - path: '/missing/$id', - getParentRoute: () => rootRouteImport, -} as any) -const HeadersIdRoute = HeadersIdRouteImport.update({ - id: '/headers/$id', - path: '/headers/$id', +const BoomIdRoute = BoomIdRouteImport.update({ + id: '/boom/$id', + path: '/boom/$id', getParentRoute: () => rootRouteImport, } as any) const FromIdRoute = FromIdRouteImport.update({ @@ -41,9 +31,19 @@ const FromIdRoute = FromIdRouteImport.update({ path: '/from/$id', getParentRoute: () => rootRouteImport, } as any) -const BoomIdRoute = BoomIdRouteImport.update({ - id: '/boom/$id', - path: '/boom/$id', +const HeadersIdRoute = HeadersIdRouteImport.update({ + id: '/headers/$id', + path: '/headers/$id', + getParentRoute: () => rootRouteImport, +} as any) +const MissingIdRoute = MissingIdRouteImport.update({ + id: '/missing/$id', + path: '/missing/$id', + getParentRoute: () => rootRouteImport, +} as any) +const TargetIdRoute = TargetIdRouteImport.update({ + id: '/target/$id', + path: '/target/$id', getParentRoute: () => rootRouteImport, } as any) @@ -117,25 +117,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/target/$id': { - id: '/target/$id' - path: '/target/$id' - fullPath: '/target/$id' - preLoaderRoute: typeof TargetIdRouteImport - parentRoute: typeof rootRouteImport - } - '/missing/$id': { - id: '/missing/$id' - path: '/missing/$id' - fullPath: '/missing/$id' - preLoaderRoute: typeof MissingIdRouteImport - parentRoute: typeof rootRouteImport - } - '/headers/$id': { - id: '/headers/$id' - path: '/headers/$id' - fullPath: '/headers/$id' - preLoaderRoute: typeof HeadersIdRouteImport + '/boom/$id': { + id: '/boom/$id' + path: '/boom/$id' + fullPath: '/boom/$id' + preLoaderRoute: typeof BoomIdRouteImport parentRoute: typeof rootRouteImport } '/from/$id': { @@ -145,11 +131,25 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof FromIdRouteImport parentRoute: typeof rootRouteImport } - '/boom/$id': { - id: '/boom/$id' - path: '/boom/$id' - fullPath: '/boom/$id' - preLoaderRoute: typeof BoomIdRouteImport + '/headers/$id': { + id: '/headers/$id' + path: '/headers/$id' + fullPath: '/headers/$id' + preLoaderRoute: typeof HeadersIdRouteImport + parentRoute: typeof rootRouteImport + } + '/missing/$id': { + id: '/missing/$id' + path: '/missing/$id' + fullPath: '/missing/$id' + preLoaderRoute: typeof MissingIdRouteImport + parentRoute: typeof rootRouteImport + } + '/target/$id': { + id: '/target/$id' + path: '/target/$id' + fullPath: '/target/$id' + preLoaderRoute: typeof TargetIdRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/headers.$id.tsx b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/headers.$id.tsx index ac2ec01b52..20c1bbe5ac 100644 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/headers.$id.tsx +++ b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/headers.$id.tsx @@ -1,5 +1,14 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' +const HeadersComponent = defineComponent({ + setup() { + const params = Route.useParams() + + return () =>
{`headers-${params.value.id}`}
+ }, +}) + export const Route = createFileRoute('/headers/$id')({ headers: ({ params }) => ({ 'x-bench-route-header': `route-header-${params.id}`, @@ -7,9 +16,3 @@ export const Route = createFileRoute('/headers/$id')({ }), component: HeadersComponent, }) - -function HeadersComponent() { - const params = Route.useParams() - - return
{`headers-${params.value.id}`}
-} diff --git a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/target.$id.tsx b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/target.$id.tsx index 17ade6bf5b..0bbf4a3dc6 100644 --- a/benchmarks/ssr/scenarios/control-flow/vue/src/routes/target.$id.tsx +++ b/benchmarks/ssr/scenarios/control-flow/vue/src/routes/target.$id.tsx @@ -1,11 +1,14 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' +const TargetComponent = defineComponent({ + setup() { + const params = Route.useParams() + + return () =>
{`target-${params.value.id}`}
+ }, +}) + export const Route = createFileRoute('/target/$id')({ component: TargetComponent, }) - -function TargetComponent() { - const params = Route.useParams() - - return
{`target-${params.value.id}`}
-} diff --git a/benchmarks/ssr/scenarios/control-flow/vue/tsconfig.json b/benchmarks/ssr/scenarios/control-flow/vue/tsconfig.json index 4fe3ccecb1..08c94853f4 100644 --- a/benchmarks/ssr/scenarios/control-flow/vue/tsconfig.json +++ b/benchmarks/ssr/scenarios/control-flow/vue/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/control-flow/vue/vite.config.ts b/benchmarks/ssr/scenarios/control-flow/vue/vite.config.ts index 2c978a7a71..1b77968d96 100644 --- a/benchmarks/ssr/scenarios/control-flow/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/control-flow/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr control-flow (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/global-middleware/bench.ts b/benchmarks/ssr/scenarios/global-middleware/bench.ts index cd4dc662e3..d2784aed38 100644 --- a/benchmarks/ssr/scenarios/global-middleware/bench.ts +++ b/benchmarks/ssr/scenarios/global-middleware/bench.ts @@ -7,10 +7,13 @@ import { import { expectedFunctionTotal, expectedRequestTotal, + getExpectedRequestContext, makeDocumentMarker, makeServerFnMarker, makeServerRouteMarker, + setRequestMiddlewareCount, } from './shared' +import type { RequestMiddlewareCount } from './shared' import type { StartRequestHandler } from '../../bench-utils' export type { StartRequestHandler } @@ -54,9 +57,9 @@ const postHeaders = { accept: acceptHeader, 'content-type': 'application/json', } satisfies HeadersInit -const documentLoopIterations = 50 -const serverFnLoopIterations = 125 -const serverRouteLoopIterations = 250 +const documentLoopTotalRequests = 64 +const serverFnLoopTotalRequests = 128 +const serverRouteLoopTotalRequests = 256 export const globalMiddlewareBenchOptions = { warmupIterations: 100, @@ -140,6 +143,7 @@ function buildPostRequest(urls: FnUrls, bodies: Array, index: number) { export async function setupGlobalMiddlewareBench( handler: StartRequestHandler, ): Promise { + setRequestMiddlewareCount(3) const urls = await discoverUrls(handler) const payloads = createPayloads() const bodies = await createBodies(payloads) @@ -154,6 +158,7 @@ export async function setupGlobalMiddlewareBench( } async function assertDocumentResponse(handler: StartRequestHandler) { + setRequestMiddlewareCount(3) const id = 'page-sanity' const response = await handler.fetch( new Request(`${origin}/page/${id}`, documentRequestInit), @@ -175,7 +180,11 @@ async function assertDocumentResponse(handler: StartRequestHandler) { } } -async function assertServerRouteResponse(handler: StartRequestHandler) { +async function assertServerRouteResponseForCount( + handler: StartRequestHandler, + count: RequestMiddlewareCount, +) { + setRequestMiddlewareCount(count) const id = 'route-sanity' const response = await handler.fetch( new Request(`${origin}/api/ping/${id}`, apiRequestInit), @@ -199,10 +208,8 @@ async function assertServerRouteResponse(handler: StartRequestHandler) { marker?: string requestTotal?: number } - const expectedMarker = makeServerRouteMarker(id, { - requestTrace: 'req.r1.r2.r3', - requestTotal: expectedRequestTotal, - }) + const expectedContext = getExpectedRequestContext(count) + const expectedMarker = makeServerRouteMarker(id, expectedContext) if (body.marker !== expectedMarker) { throw new Error( @@ -210,9 +217,9 @@ async function assertServerRouteResponse(handler: StartRequestHandler) { ) } - if (body.requestTotal !== expectedRequestTotal) { + if (body.requestTotal !== expectedContext.requestTotal) { throw new Error( - `Expected server route requestTotal ${expectedRequestTotal}, received ${body.requestTotal}`, + `Expected server route requestTotal ${expectedContext.requestTotal}, received ${body.requestTotal}`, ) } } @@ -221,6 +228,7 @@ async function assertServerFnResponse( handler: StartRequestHandler, context: GlobalMiddlewareBenchContext, ) { + setRequestMiddlewareCount(3) const response = await handler.fetch( buildPostRequest(context.urls, context.bodies, 0), ) @@ -257,13 +265,18 @@ export async function assertGlobalMiddlewareScenario( ) { await assertDocumentResponse(handler) await assertServerFnResponse(handler, context) - await assertServerRouteResponse(handler) + for (const count of [0, 1, 2, 3] as const) { + await assertServerRouteResponseForCount(handler, count) + } + setRequestMiddlewareCount(3) } export function runGlobalMiddlewareDocumentLoop(handler: StartRequestHandler) { + setRequestMiddlewareCount(3) return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: documentLoopIterations, + concurrency: 16, + totalRequests: documentLoopTotalRequests, buildRequest: buildDocumentRequest, }) } @@ -272,9 +285,11 @@ export function runGlobalMiddlewareServerFnLoop( handler: StartRequestHandler, context: GlobalMiddlewareBenchContext, ) { + setRequestMiddlewareCount(3) return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: serverFnLoopIterations, + concurrency: 16, + totalRequests: serverFnLoopTotalRequests, buildRequest: (_random, index) => buildPostRequest(context.urls, context.bodies, index), }) @@ -282,10 +297,13 @@ export function runGlobalMiddlewareServerFnLoop( export function runGlobalMiddlewareServerRouteLoop( handler: StartRequestHandler, + count: RequestMiddlewareCount = 3, ) { + setRequestMiddlewareCount(count) return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: serverRouteLoopIterations, + concurrency: 16, + totalRequests: serverRouteLoopTotalRequests, buildRequest: buildServerRouteRequest, }) } diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.bench.ts index 8288322e70..cb3f9f427c 100644 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/global-middleware/react/speed.bench.ts @@ -1,10 +1,8 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, runGlobalMiddlewareDocumentLoop, - runGlobalMiddlewareServerFnLoop, - runGlobalMiddlewareServerRouteLoop, setupGlobalMiddlewareBench, } from '../bench' import type { StartRequestHandler } from '../bench' @@ -16,27 +14,12 @@ const { default: handler } = (await import( )) as { default: StartRequestHandler } - const context = await setupGlobalMiddlewareBench(handler) await assertGlobalMiddlewareScenario(handler, context) -describe('ssr', () => { - bench( - 'ssr global-mw document (react)', - () => runGlobalMiddlewareDocumentLoop(handler), - globalMiddlewareBenchOptions, - ) - - bench( - 'ssr global-mw server-fn (react)', - () => runGlobalMiddlewareServerFnLoop(handler, context), - globalMiddlewareBenchOptions, - ) - - bench( - 'ssr global-mw server-route (react)', - () => runGlobalMiddlewareServerRouteLoop(handler), - globalMiddlewareBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr global-mw document (react)', async () => + runGlobalMiddlewareDocumentLoop(handler), + ).run(globalMiddlewareBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-fn.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-fn.bench.ts new file mode 100644 index 0000000000..48c444de77 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-fn.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerFnLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-fn (react)', async () => + runGlobalMiddlewareServerFnLoop(handler, context), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-0-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-0-middleware.bench.ts new file mode 100644 index 0000000000..22f53883ee --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-0-middleware.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 0 middleware (react)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 0), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-1-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-1-middleware.bench.ts new file mode 100644 index 0000000000..f01b48d66e --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-1-middleware.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 1 middleware (react)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 1), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-2-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-2-middleware.bench.ts new file mode 100644 index 0000000000..b01957f806 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-2-middleware.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 2 middlewares (react)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 2), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route.bench.ts new file mode 100644 index 0000000000..08d97fcaf6 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 3 middlewares (react)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 3), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/global-middleware/react/src/routeTree.gen.ts index aa916f0800..8dfaa80562 100644 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/routeTree.gen.ts +++ b/benchmarks/ssr/scenarios/global-middleware/react/src/routeTree.gen.ts @@ -10,8 +10,8 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as PageIdRouteImport } from './routes/page.$id' import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' +import { Route as PageIdRouteImport } from './routes/page.$id' import { Route as ApiPingIdRouteImport } from './routes/api.ping.$id' const IndexRoute = IndexRouteImport.update({ @@ -19,16 +19,16 @@ const IndexRoute = IndexRouteImport.update({ path: '/', getParentRoute: () => rootRouteImport, } as any) -const PageIdRoute = PageIdRouteImport.update({ - id: '/page/$id', - path: '/page/$id', - getParentRoute: () => rootRouteImport, -} as any) const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ id: '/api/fn-urls', path: '/api/fn-urls', getParentRoute: () => rootRouteImport, } as any) +const PageIdRoute = PageIdRouteImport.update({ + id: '/page/$id', + path: '/page/$id', + getParentRoute: () => rootRouteImport, +} as any) const ApiPingIdRoute = ApiPingIdRouteImport.update({ id: '/api/ping/$id', path: '/api/ping/$id', @@ -78,13 +78,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/page/$id': { - id: '/page/$id' - path: '/page/$id' - fullPath: '/page/$id' - preLoaderRoute: typeof PageIdRouteImport - parentRoute: typeof rootRouteImport - } '/api/fn-urls': { id: '/api/fn-urls' path: '/api/fn-urls' @@ -92,6 +85,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiFnUrlsRouteImport parentRoute: typeof rootRouteImport } + '/page/$id': { + id: '/page/$id' + path: '/page/$id' + fullPath: '/page/$id' + preLoaderRoute: typeof PageIdRouteImport + parentRoute: typeof rootRouteImport + } '/api/ping/$id': { id: '/api/ping/$id' path: '/api/ping/$id' diff --git a/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts b/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts index 6b59e8035b..8dfb2dd3c4 100644 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts +++ b/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts @@ -1,4 +1,5 @@ import { createMiddleware, createStart } from '@tanstack/react-start' +import { getRequestMiddlewareCount } from '../../shared' import type { GlobalMiddlewareContext } from '../../shared' function appendTrace( @@ -48,6 +49,13 @@ const requestMiddlewareC = createMiddleware({ type: 'request' }).server( }, ) +const requestMiddlewareSets: Array> = [ + [], + [requestMiddlewareA], + [requestMiddlewareA, requestMiddlewareB], + [requestMiddlewareA, requestMiddlewareB, requestMiddlewareC], +] + const functionMiddlewareA = createMiddleware({ type: 'function' }).server( ({ next, context }) => { const ctx = (context ?? {}) as GlobalMiddlewareContext @@ -75,10 +83,6 @@ const functionMiddlewareB = createMiddleware({ type: 'function' }).server( ) export const startInstance = createStart(() => ({ - requestMiddleware: [ - requestMiddlewareA, - requestMiddlewareB, - requestMiddlewareC, - ], + requestMiddleware: requestMiddlewareSets[getRequestMiddlewareCount()], functionMiddleware: [functionMiddlewareA, functionMiddlewareB], })) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/tsconfig.json b/benchmarks/ssr/scenarios/global-middleware/react/tsconfig.json index 0c0192daaa..de4a3204b9 100644 --- a/benchmarks/ssr/scenarios/global-middleware/react/tsconfig.json +++ b/benchmarks/ssr/scenarios/global-middleware/react/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "../shared.ts", diff --git a/benchmarks/ssr/scenarios/global-middleware/react/vite.config.ts b/benchmarks/ssr/scenarios/global-middleware/react/vite.config.ts index 71c8ff3719..968a8a24e9 100644 --- a/benchmarks/ssr/scenarios/global-middleware/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/global-middleware/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr global-middleware (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/global-middleware/shared.ts b/benchmarks/ssr/scenarios/global-middleware/shared.ts index f90fa9b233..8fbe788911 100644 --- a/benchmarks/ssr/scenarios/global-middleware/shared.ts +++ b/benchmarks/ssr/scenarios/global-middleware/shared.ts @@ -10,11 +10,41 @@ export interface GlobalMiddlewareRouteContext extends GlobalMiddlewareContext { globalMiddlewareContext?: GlobalMiddlewareContext } +export type RequestMiddlewareCount = 0 | 1 | 2 | 3 + +const requestMiddlewareCountKey = '__TSR_SSR_BENCH_REQUEST_MIDDLEWARE_COUNT__' + +type BenchmarkGlobal = typeof globalThis & { + [requestMiddlewareCountKey]?: RequestMiddlewareCount +} + +const expectedRequestContexts: ReadonlyArray = [ + {}, + { requestTrace: 'req.r1', requestTotal: 1 }, + { requestTrace: 'req.r1.r2', requestTotal: 3 }, + { requestTrace: 'req.r1.r2.r3', requestTotal: 6 }, +] + export const expectedRequestTrace = 'req.r1.r2.r3' export const expectedRequestTotal = 6 export const expectedFunctionTrace = 'fn.f1.f2' export const expectedFunctionTotal = 30 +export function setRequestMiddlewareCount(count: RequestMiddlewareCount) { + const benchmarkGlobal = globalThis as BenchmarkGlobal + benchmarkGlobal[requestMiddlewareCountKey] = count +} + +export function getRequestMiddlewareCount(): RequestMiddlewareCount { + return (globalThis as BenchmarkGlobal)[requestMiddlewareCountKey] ?? 3 +} + +export function getExpectedRequestContext( + count: RequestMiddlewareCount, +): GlobalMiddlewareContext { + return expectedRequestContexts[count]! +} + export function makeDocumentMarker( id: string, context: GlobalMiddlewareContext, diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.bench.ts index 019735eb40..0e5f504090 100644 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/global-middleware/solid/speed.bench.ts @@ -1,10 +1,8 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, runGlobalMiddlewareDocumentLoop, - runGlobalMiddlewareServerFnLoop, - runGlobalMiddlewareServerRouteLoop, setupGlobalMiddlewareBench, } from '../bench' import type { StartRequestHandler } from '../bench' @@ -16,27 +14,12 @@ const { default: handler } = (await import( )) as { default: StartRequestHandler } - const context = await setupGlobalMiddlewareBench(handler) await assertGlobalMiddlewareScenario(handler, context) -describe('ssr', () => { - bench( - 'ssr global-mw document (solid)', - () => runGlobalMiddlewareDocumentLoop(handler), - globalMiddlewareBenchOptions, - ) - - bench( - 'ssr global-mw server-fn (solid)', - () => runGlobalMiddlewareServerFnLoop(handler, context), - globalMiddlewareBenchOptions, - ) - - bench( - 'ssr global-mw server-route (solid)', - () => runGlobalMiddlewareServerRouteLoop(handler), - globalMiddlewareBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr global-mw document (solid)', async () => + runGlobalMiddlewareDocumentLoop(handler), + ).run(globalMiddlewareBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-fn.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-fn.bench.ts new file mode 100644 index 0000000000..915507ef9f --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-fn.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerFnLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-fn (solid)', async () => + runGlobalMiddlewareServerFnLoop(handler, context), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-0-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-0-middleware.bench.ts new file mode 100644 index 0000000000..a791145935 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-0-middleware.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 0 middleware (solid)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 0), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-1-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-1-middleware.bench.ts new file mode 100644 index 0000000000..1baab0f344 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-1-middleware.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 1 middleware (solid)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 1), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-2-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-2-middleware.bench.ts new file mode 100644 index 0000000000..d6fde20764 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-2-middleware.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 2 middlewares (solid)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 2), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route.bench.ts b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route.bench.ts new file mode 100644 index 0000000000..558ebeb9a4 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 3 middlewares (solid)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 3), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/global-middleware/solid/src/routeTree.gen.ts index 28d816525e..65f7fa5848 100644 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/routeTree.gen.ts +++ b/benchmarks/ssr/scenarios/global-middleware/solid/src/routeTree.gen.ts @@ -10,8 +10,8 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as PageIdRouteImport } from './routes/page.$id' import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' +import { Route as PageIdRouteImport } from './routes/page.$id' import { Route as ApiPingIdRouteImport } from './routes/api.ping.$id' const IndexRoute = IndexRouteImport.update({ @@ -19,16 +19,16 @@ const IndexRoute = IndexRouteImport.update({ path: '/', getParentRoute: () => rootRouteImport, } as any) -const PageIdRoute = PageIdRouteImport.update({ - id: '/page/$id', - path: '/page/$id', - getParentRoute: () => rootRouteImport, -} as any) const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ id: '/api/fn-urls', path: '/api/fn-urls', getParentRoute: () => rootRouteImport, } as any) +const PageIdRoute = PageIdRouteImport.update({ + id: '/page/$id', + path: '/page/$id', + getParentRoute: () => rootRouteImport, +} as any) const ApiPingIdRoute = ApiPingIdRouteImport.update({ id: '/api/ping/$id', path: '/api/ping/$id', @@ -78,13 +78,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/page/$id': { - id: '/page/$id' - path: '/page/$id' - fullPath: '/page/$id' - preLoaderRoute: typeof PageIdRouteImport - parentRoute: typeof rootRouteImport - } '/api/fn-urls': { id: '/api/fn-urls' path: '/api/fn-urls' @@ -92,6 +85,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ApiFnUrlsRouteImport parentRoute: typeof rootRouteImport } + '/page/$id': { + id: '/page/$id' + path: '/page/$id' + fullPath: '/page/$id' + preLoaderRoute: typeof PageIdRouteImport + parentRoute: typeof rootRouteImport + } '/api/ping/$id': { id: '/api/ping/$id' path: '/api/ping/$id' diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/src/start.ts b/benchmarks/ssr/scenarios/global-middleware/solid/src/start.ts index 8c4168d574..a6f6214b82 100644 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/start.ts +++ b/benchmarks/ssr/scenarios/global-middleware/solid/src/start.ts @@ -1,4 +1,5 @@ import { createMiddleware, createStart } from '@tanstack/solid-start' +import { getRequestMiddlewareCount } from '../../shared' import type { GlobalMiddlewareContext } from '../../shared' function appendTrace( @@ -48,6 +49,13 @@ const requestMiddlewareC = createMiddleware({ type: 'request' }).server( }, ) +const requestMiddlewareSets: Array> = [ + [], + [requestMiddlewareA], + [requestMiddlewareA, requestMiddlewareB], + [requestMiddlewareA, requestMiddlewareB, requestMiddlewareC], +] + const functionMiddlewareA = createMiddleware({ type: 'function' }).server( ({ next, context }) => { const ctx = (context ?? {}) as GlobalMiddlewareContext @@ -75,10 +83,6 @@ const functionMiddlewareB = createMiddleware({ type: 'function' }).server( ) export const startInstance = createStart(() => ({ - requestMiddleware: [ - requestMiddlewareA, - requestMiddlewareB, - requestMiddlewareC, - ], + requestMiddleware: requestMiddlewareSets[getRequestMiddlewareCount()], functionMiddleware: [functionMiddlewareA, functionMiddlewareB], })) diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/tsconfig.json b/benchmarks/ssr/scenarios/global-middleware/solid/tsconfig.json index 5ad8f505b6..dce3ceae30 100644 --- a/benchmarks/ssr/scenarios/global-middleware/solid/tsconfig.json +++ b/benchmarks/ssr/scenarios/global-middleware/solid/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "../shared.ts", diff --git a/benchmarks/ssr/scenarios/global-middleware/solid/vite.config.ts b/benchmarks/ssr/scenarios/global-middleware/solid/vite.config.ts index e8af6933ed..f3597b25d5 100644 --- a/benchmarks/ssr/scenarios/global-middleware/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/global-middleware/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr global-middleware (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts index 0b3ed9dd7a..9660f29d07 100644 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts @@ -1,10 +1,8 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, runGlobalMiddlewareDocumentLoop, - runGlobalMiddlewareServerFnLoop, - runGlobalMiddlewareServerRouteLoop, setupGlobalMiddlewareBench, } from '../bench' import type { StartRequestHandler } from '../bench' @@ -16,27 +14,12 @@ const { default: handler } = (await import( )) as { default: StartRequestHandler } - const context = await setupGlobalMiddlewareBench(handler) await assertGlobalMiddlewareScenario(handler, context) -describe('ssr', () => { - bench( - 'ssr global-mw document (vue)', - () => runGlobalMiddlewareDocumentLoop(handler), - globalMiddlewareBenchOptions, - ) - - bench( - 'ssr global-mw server-fn (vue)', - () => runGlobalMiddlewareServerFnLoop(handler, context), - globalMiddlewareBenchOptions, - ) - - bench( - 'ssr global-mw server-route (vue)', - () => runGlobalMiddlewareServerRouteLoop(handler), - globalMiddlewareBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr global-mw document (vue)', async () => + runGlobalMiddlewareDocumentLoop(handler), + ).run(globalMiddlewareBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-fn.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-fn.bench.ts new file mode 100644 index 0000000000..297e8cee7b --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-fn.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerFnLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-fn (vue)', async () => + runGlobalMiddlewareServerFnLoop(handler, context), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-0-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-0-middleware.bench.ts new file mode 100644 index 0000000000..d023dd458a --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-0-middleware.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 0 middleware (vue)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 0), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-1-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-1-middleware.bench.ts new file mode 100644 index 0000000000..5018163631 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-1-middleware.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 1 middleware (vue)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 1), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-2-middleware.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-2-middleware.bench.ts new file mode 100644 index 0000000000..f9abd8eb60 --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-2-middleware.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 2 middlewares (vue)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 2), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route.bench.ts new file mode 100644 index 0000000000..adcec3019f --- /dev/null +++ b/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route.bench.ts @@ -0,0 +1,25 @@ +import { test } from 'vitest' +import { + assertGlobalMiddlewareScenario, + globalMiddlewareBenchOptions, + runGlobalMiddlewareServerRouteLoop, + setupGlobalMiddlewareBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} +const context = await setupGlobalMiddlewareBench(handler) + +await assertGlobalMiddlewareScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr global-mw server-route 3 middlewares (vue)', async () => + runGlobalMiddlewareServerRouteLoop(handler, 3), + ).run(globalMiddlewareBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/global-middleware/vue/src/routeTree.gen.ts index aae3329420..3118848e4d 100644 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/routeTree.gen.ts +++ b/benchmarks/ssr/scenarios/global-middleware/vue/src/routeTree.gen.ts @@ -10,8 +10,8 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as PageIdRouteImport } from './routes/page.$id' import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' +import { Route as PageIdRouteImport } from './routes/page.$id' import { Route as ApiPingIdRouteImport } from './routes/api.ping.$id' const IndexRoute = IndexRouteImport.update({ @@ -19,16 +19,16 @@ const IndexRoute = IndexRouteImport.update({ path: '/', getParentRoute: () => rootRouteImport, } as any) -const PageIdRoute = PageIdRouteImport.update({ - id: '/page/$id', - path: '/page/$id', - getParentRoute: () => rootRouteImport, -} as any) const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ id: '/api/fn-urls', path: '/api/fn-urls', getParentRoute: () => rootRouteImport, } as any) +const PageIdRoute = PageIdRouteImport.update({ + id: '/page/$id', + path: '/page/$id', + getParentRoute: () => rootRouteImport, +} as any) const ApiPingIdRoute = ApiPingIdRouteImport.update({ id: '/api/ping/$id', path: '/api/ping/$id', @@ -78,13 +78,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/page/$id': { - id: '/page/$id' - path: '/page/$id' - fullPath: '/page/$id' - preLoaderRoute: typeof PageIdRouteImport - parentRoute: typeof rootRouteImport - } '/api/fn-urls': { id: '/api/fn-urls' path: '/api/fn-urls' @@ -92,6 +85,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ApiFnUrlsRouteImport parentRoute: typeof rootRouteImport } + '/page/$id': { + id: '/page/$id' + path: '/page/$id' + fullPath: '/page/$id' + preLoaderRoute: typeof PageIdRouteImport + parentRoute: typeof rootRouteImport + } '/api/ping/$id': { id: '/api/ping/$id' path: '/api/ping/$id' diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/page.$id.tsx b/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/page.$id.tsx index 2010d0cd2a..6e837ef0a0 100644 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/page.$id.tsx +++ b/benchmarks/ssr/scenarios/global-middleware/vue/src/routes/page.$id.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { getGlobalMiddlewareContext, @@ -5,6 +6,14 @@ import { type GlobalMiddlewareContext, } from '../../../shared' +const PageComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () =>
{data.value.marker}
+ }, +}) + export const Route = createFileRoute('/page/$id')({ beforeLoad: ({ serverContext }) => ({ globalMiddlewareContext: (serverContext ?? {}) as GlobalMiddlewareContext, @@ -14,9 +23,3 @@ export const Route = createFileRoute('/page/$id')({ }), component: PageComponent, }) - -function PageComponent() { - const data = Route.useLoaderData() - - return
{data.value.marker}
-} diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/start.ts b/benchmarks/ssr/scenarios/global-middleware/vue/src/start.ts index dc3f142e27..6e4eb2c5ef 100644 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/start.ts +++ b/benchmarks/ssr/scenarios/global-middleware/vue/src/start.ts @@ -1,4 +1,5 @@ import { createMiddleware, createStart } from '@tanstack/vue-start' +import { getRequestMiddlewareCount } from '../../shared' import type { GlobalMiddlewareContext } from '../../shared' function appendTrace( @@ -48,6 +49,13 @@ const requestMiddlewareC = createMiddleware({ type: 'request' }).server( }, ) +const requestMiddlewareSets: Array> = [ + [], + [requestMiddlewareA], + [requestMiddlewareA, requestMiddlewareB], + [requestMiddlewareA, requestMiddlewareB, requestMiddlewareC], +] + const functionMiddlewareA = createMiddleware({ type: 'function' }).server( ({ next, context }) => { const ctx = (context ?? {}) as GlobalMiddlewareContext @@ -75,10 +83,6 @@ const functionMiddlewareB = createMiddleware({ type: 'function' }).server( ) export const startInstance = createStart(() => ({ - requestMiddleware: [ - requestMiddlewareA, - requestMiddlewareB, - requestMiddlewareC, - ], + requestMiddleware: requestMiddlewareSets[getRequestMiddlewareCount()], functionMiddleware: [functionMiddlewareA, functionMiddlewareB], })) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/tsconfig.json b/benchmarks/ssr/scenarios/global-middleware/vue/tsconfig.json index 70d62162e6..56800fd29e 100644 --- a/benchmarks/ssr/scenarios/global-middleware/vue/tsconfig.json +++ b/benchmarks/ssr/scenarios/global-middleware/vue/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "../shared.ts", diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/vite.config.ts b/benchmarks/ssr/scenarios/global-middleware/vue/vite.config.ts index 6dd55adab3..8e29c5ee98 100644 --- a/benchmarks/ssr/scenarios/global-middleware/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/global-middleware/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr global-middleware (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/head/react/speed.bench.ts b/benchmarks/ssr/scenarios/head/react/speed.bench.ts index 19158b32a9..f75008506e 100644 --- a/benchmarks/ssr/scenarios/head/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/head/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertHeadSanity, headBenchOptions, runHeadLoop } from '../shared' import type { StartRequestHandler } from '../shared' @@ -12,6 +12,8 @@ const { default: handler } = (await import( await assertHeadSanity(handler) -describe('ssr', () => { - bench('ssr head (react)', () => runHeadLoop(handler), headBenchOptions) +test('ssr', async ({ bench }) => { + await bench('ssr head (react)', async () => runHeadLoop(handler)).run( + headBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/head/react/vite.config.ts b/benchmarks/ssr/scenarios/head/react/vite.config.ts index 56d69443ac..d24fc850a1 100644 --- a/benchmarks/ssr/scenarios/head/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/head/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr head (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/head/shared.ts b/benchmarks/ssr/scenarios/head/shared.ts index 26e084b156..033ca47c22 100644 --- a/benchmarks/ssr/scenarios/head/shared.ts +++ b/benchmarks/ssr/scenarios/head/shared.ts @@ -7,7 +7,7 @@ export type { StartRequestHandler } const benchmarkSeed = 0xdecafbad const origin = 'http://localhost' const dedupedMetaName = 'head-benchmark-shared' -const headLoopIterations = 25 +const headLoopTotalRequests = 32 const requestInit = { method: 'GET', @@ -32,7 +32,8 @@ function buildHeadRequest(random: () => number) { export function runHeadLoop(handler: StartRequestHandler) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: headLoopIterations, + concurrency: 16, + totalRequests: headLoopTotalRequests, buildRequest: buildHeadRequest, }) } diff --git a/benchmarks/ssr/scenarios/head/solid/speed.bench.ts b/benchmarks/ssr/scenarios/head/solid/speed.bench.ts index ad5bf52809..333e2f091b 100644 --- a/benchmarks/ssr/scenarios/head/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/head/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertHeadSanity, headBenchOptions, runHeadLoop } from '../shared' import type { StartRequestHandler } from '../shared' @@ -12,6 +12,8 @@ const { default: handler } = (await import( await assertHeadSanity(handler) -describe('ssr', () => { - bench('ssr head (solid)', () => runHeadLoop(handler), headBenchOptions) +test('ssr', async ({ bench }) => { + await bench('ssr head (solid)', async () => runHeadLoop(handler)).run( + headBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/head/solid/vite.config.ts b/benchmarks/ssr/scenarios/head/solid/vite.config.ts index f7b97a44d1..7a870bbd77 100644 --- a/benchmarks/ssr/scenarios/head/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/head/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr head (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/head/vue/speed.bench.ts b/benchmarks/ssr/scenarios/head/vue/speed.bench.ts index 5d8243b588..936735a909 100644 --- a/benchmarks/ssr/scenarios/head/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/head/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertHeadSanity, headBenchOptions, runHeadLoop } from '../shared' import type { StartRequestHandler } from '../shared' @@ -12,6 +12,8 @@ const { default: handler } = (await import( await assertHeadSanity(handler) -describe('ssr', () => { - bench('ssr head (vue)', () => runHeadLoop(handler), headBenchOptions) +test('ssr', async ({ bench }) => { + await bench('ssr head (vue)', async () => runHeadLoop(handler)).run( + headBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/head/vue/vite.config.ts b/benchmarks/ssr/scenarios/head/vue/vite.config.ts index e020012560..1434d26069 100644 --- a/benchmarks/ssr/scenarios/head/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/head/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr head (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts b/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts index a5eecfc648..7acd43c635 100644 --- a/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertLoadersSanity, benchOptions, @@ -16,6 +16,8 @@ const { default: handler } = (await import( await assertLoadersSanity(handler) -describe('ssr', () => { - bench('ssr loaders (react)', () => runLoadersLoop(handler), benchOptions) +test('ssr', async ({ bench }) => { + await bench('ssr loaders (react)', async () => runLoadersLoop(handler)).run( + benchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/loaders/react/vite.config.ts b/benchmarks/ssr/scenarios/loaders/react/vite.config.ts index 5c4dcaa40d..e761426c84 100644 --- a/benchmarks/ssr/scenarios/loaders/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/loaders/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr loaders (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/loaders/shared-bench.ts b/benchmarks/ssr/scenarios/loaders/shared-bench.ts index 2b1e9b4749..f52c51dccd 100644 --- a/benchmarks/ssr/scenarios/loaders/shared-bench.ts +++ b/benchmarks/ssr/scenarios/loaders/shared-bench.ts @@ -5,7 +5,7 @@ import type { StartRequestHandler } from '../../bench-utils' export type { StartRequestHandler } const benchmarkSeed = 0xdecafbad -const loadersLoopIterations = 15 +const loadersLoopTotalRequests = 16 const requestInit = { method: 'GET', @@ -68,7 +68,8 @@ export const benchOptions = { export function runLoadersLoop(handler: StartRequestHandler) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: loadersLoopIterations, + concurrency: 16, + totalRequests: loadersLoopTotalRequests, buildRequest: buildLoaderRequest, }) } diff --git a/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts b/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts index 7b3f6247ea..7fc8d88389 100644 --- a/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertLoadersSanity, benchOptions, @@ -16,6 +16,8 @@ const { default: handler } = (await import( await assertLoadersSanity(handler) -describe('ssr', () => { - bench('ssr loaders (solid)', () => runLoadersLoop(handler), benchOptions) +test('ssr', async ({ bench }) => { + await bench('ssr loaders (solid)', async () => runLoadersLoop(handler)).run( + benchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/loaders/solid/vite.config.ts b/benchmarks/ssr/scenarios/loaders/solid/vite.config.ts index 527ca977c5..64f52159c3 100644 --- a/benchmarks/ssr/scenarios/loaders/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/loaders/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr loaders (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts b/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts index fb39e0652c..321350d98c 100644 --- a/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertLoadersSanity, benchOptions, @@ -16,6 +16,8 @@ const { default: handler } = (await import( await assertLoadersSanity(handler) -describe('ssr', () => { - bench('ssr loaders (vue)', () => runLoadersLoop(handler), benchOptions) +test('ssr', async ({ bench }) => { + await bench('ssr loaders (vue)', async () => runLoadersLoop(handler)).run( + benchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.$c.tsx b/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.$c.tsx index de927a8092..0a52b9c542 100644 --- a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.$c.tsx +++ b/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.$c.tsx @@ -1,6 +1,24 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { makeLevelData } from '../../../shared-data' +const LevelCComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+

{data.value.meta.label}

+
    + {data.value.items.slice(0, 10).map((item) => ( +
  • {item.name}
  • + ))} +
+
+ ) + }, +}) + export const Route = createFileRoute('/$a/$b/$c')({ beforeLoad: ({ params, context }) => { void context @@ -15,18 +33,3 @@ export const Route = createFileRoute('/$a/$b/$c')({ }, component: LevelCComponent, }) - -function LevelCComponent() { - const data = Route.useLoaderData() - - return ( -
-

{data.value.meta.label}

-
    - {data.value.items.slice(0, 10).map((item) => ( -
  • {item.name}
  • - ))} -
-
- ) -} diff --git a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.tsx b/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.tsx index e1a5f52ae2..f3943d58e7 100644 --- a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.tsx +++ b/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.$b.tsx @@ -1,6 +1,25 @@ +import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { makeLevelData } from '../../../shared-data' +const LevelBComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+

{data.value.meta.label}

+
    + {data.value.items.slice(0, 10).map((item) => ( +
  • {item.name}
  • + ))} +
+ +
+ ) + }, +}) + export const Route = createFileRoute('/$a/$b')({ beforeLoad: ({ params, context }) => { void context @@ -15,19 +34,3 @@ export const Route = createFileRoute('/$a/$b')({ }, component: LevelBComponent, }) - -function LevelBComponent() { - const data = Route.useLoaderData() - - return ( -
-

{data.value.meta.label}

-
    - {data.value.items.slice(0, 10).map((item) => ( -
  • {item.name}
  • - ))} -
- -
- ) -} diff --git a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.tsx b/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.tsx index b197a8edf1..63bb36949f 100644 --- a/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.tsx +++ b/benchmarks/ssr/scenarios/loaders/vue/src/routes/$a.tsx @@ -1,6 +1,25 @@ +import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { makeLevelData } from '../../../shared-data' +const LevelAComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+

{data.value.meta.label}

+
    + {data.value.items.slice(0, 10).map((item) => ( +
  • {item.name}
  • + ))} +
+ +
+ ) + }, +}) + export const Route = createFileRoute('/$a')({ beforeLoad: ({ params, context }) => { void context @@ -15,19 +34,3 @@ export const Route = createFileRoute('/$a')({ }, component: LevelAComponent, }) - -function LevelAComponent() { - const data = Route.useLoaderData() - - return ( -
-

{data.value.meta.label}

-
    - {data.value.items.slice(0, 10).map((item) => ( -
  • {item.name}
  • - ))} -
- -
- ) -} diff --git a/benchmarks/ssr/scenarios/loaders/vue/vite.config.ts b/benchmarks/ssr/scenarios/loaders/vue/vite.config.ts index b7a4d1b48b..92bf3e60f0 100644 --- a/benchmarks/ssr/scenarios/loaders/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/loaders/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr loaders (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts b/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts index d7025ce0f9..920186c5db 100644 --- a/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts @@ -1,11 +1,10 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertRewriteScenario, rewriteBenchOptions, runRewriteLocalizedLoop, - runRewritePassthroughLoop, - type StartRequestHandler, } from '../shared' +import type { StartRequestHandler } from '../shared' const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href @@ -17,15 +16,8 @@ const { default: handler } = (await import( await assertRewriteScenario(handler) -describe('ssr', () => { - bench( - 'ssr rewrite localized (react)', - () => runRewriteLocalizedLoop(handler), - rewriteBenchOptions, - ) - bench( - 'ssr rewrite passthrough (react)', - () => runRewritePassthroughLoop(handler), - rewriteBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr rewrite localized (react)', async () => + runRewriteLocalizedLoop(handler), + ).run(rewriteBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/rewrites/react/speed.rewrite-passthrough.bench.ts b/benchmarks/ssr/scenarios/rewrites/react/speed.rewrite-passthrough.bench.ts new file mode 100644 index 0000000000..f5d09089a6 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/react/speed.rewrite-passthrough.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertRewriteScenario, + rewriteBenchOptions, + runRewritePassthroughLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertRewriteScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr rewrite passthrough (react)', async () => + runRewritePassthroughLoop(handler), + ).run(rewriteBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/rewrites/react/tsconfig.json b/benchmarks/ssr/scenarios/rewrites/react/tsconfig.json index 91027bfc88..cf14e1d440 100644 --- a/benchmarks/ssr/scenarios/rewrites/react/tsconfig.json +++ b/benchmarks/ssr/scenarios/rewrites/react/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/rewrites/react/vite.config.ts b/benchmarks/ssr/scenarios/rewrites/react/vite.config.ts index 5bf098275b..7b20340ec6 100644 --- a/benchmarks/ssr/scenarios/rewrites/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/rewrites/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -25,6 +26,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr rewrites (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/rewrites/shared.ts b/benchmarks/ssr/scenarios/rewrites/shared.ts index a8f2e3279b..9b29bc0249 100644 --- a/benchmarks/ssr/scenarios/rewrites/shared.ts +++ b/benchmarks/ssr/scenarios/rewrites/shared.ts @@ -6,8 +6,8 @@ export type { StartRequestHandler } const benchmarkSeed = 0xdecafbad const origin = 'http://localhost' -const localizedLoopIterations = 25 -const passthroughLoopIterations = 25 +const localizedLoopTotalRequests = 32 +const passthroughLoopTotalRequests = 32 const requestInit = { method: 'GET', @@ -39,7 +39,8 @@ function buildPassthroughRequest(random: () => number) { export function runRewriteLocalizedLoop(handler: StartRequestHandler) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: localizedLoopIterations, + concurrency: 16, + totalRequests: localizedLoopTotalRequests, buildRequest: buildLocalizedRequest, }) } @@ -47,7 +48,8 @@ export function runRewriteLocalizedLoop(handler: StartRequestHandler) { export function runRewritePassthroughLoop(handler: StartRequestHandler) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: passthroughLoopIterations, + concurrency: 16, + totalRequests: passthroughLoopTotalRequests, buildRequest: buildPassthroughRequest, }) } diff --git a/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts b/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts index 7aa4bd0b18..488fb2ca52 100644 --- a/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts @@ -1,11 +1,10 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertRewriteScenario, rewriteBenchOptions, runRewriteLocalizedLoop, - runRewritePassthroughLoop, - type StartRequestHandler, } from '../shared' +import type { StartRequestHandler } from '../shared' const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href @@ -17,15 +16,8 @@ const { default: handler } = (await import( await assertRewriteScenario(handler) -describe('ssr', () => { - bench( - 'ssr rewrite localized (solid)', - () => runRewriteLocalizedLoop(handler), - rewriteBenchOptions, - ) - bench( - 'ssr rewrite passthrough (solid)', - () => runRewritePassthroughLoop(handler), - rewriteBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr rewrite localized (solid)', async () => + runRewriteLocalizedLoop(handler), + ).run(rewriteBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/rewrites/solid/speed.rewrite-passthrough.bench.ts b/benchmarks/ssr/scenarios/rewrites/solid/speed.rewrite-passthrough.bench.ts new file mode 100644 index 0000000000..7b86e2ba11 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/solid/speed.rewrite-passthrough.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertRewriteScenario, + rewriteBenchOptions, + runRewritePassthroughLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertRewriteScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr rewrite passthrough (solid)', async () => + runRewritePassthroughLoop(handler), + ).run(rewriteBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/rewrites/solid/tsconfig.json b/benchmarks/ssr/scenarios/rewrites/solid/tsconfig.json index b1806caa67..42c3a2160f 100644 --- a/benchmarks/ssr/scenarios/rewrites/solid/tsconfig.json +++ b/benchmarks/ssr/scenarios/rewrites/solid/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/rewrites/solid/vite.config.ts b/benchmarks/ssr/scenarios/rewrites/solid/vite.config.ts index ae9f925cb7..963fe7132b 100644 --- a/benchmarks/ssr/scenarios/rewrites/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/rewrites/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -25,6 +26,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr rewrites (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts b/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts index 0bbd896d71..5fd4da9d3e 100644 --- a/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts @@ -1,11 +1,10 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertRewriteScenario, rewriteBenchOptions, runRewriteLocalizedLoop, - runRewritePassthroughLoop, - type StartRequestHandler, } from '../shared' +import type { StartRequestHandler } from '../shared' const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href @@ -17,15 +16,8 @@ const { default: handler } = (await import( await assertRewriteScenario(handler) -describe('ssr', () => { - bench( - 'ssr rewrite localized (vue)', - () => runRewriteLocalizedLoop(handler), - rewriteBenchOptions, - ) - bench( - 'ssr rewrite passthrough (vue)', - () => runRewritePassthroughLoop(handler), - rewriteBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr rewrite localized (vue)', async () => + runRewriteLocalizedLoop(handler), + ).run(rewriteBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/rewrites/vue/speed.rewrite-passthrough.bench.ts b/benchmarks/ssr/scenarios/rewrites/vue/speed.rewrite-passthrough.bench.ts new file mode 100644 index 0000000000..f3664b5f21 --- /dev/null +++ b/benchmarks/ssr/scenarios/rewrites/vue/speed.rewrite-passthrough.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertRewriteScenario, + rewriteBenchOptions, + runRewritePassthroughLoop, +} from '../shared' +import type { StartRequestHandler } from '../shared' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertRewriteScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr rewrite passthrough (vue)', async () => + runRewritePassthroughLoop(handler), + ).run(rewriteBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.$b.tsx b/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.$b.tsx index 3fdb7014f4..3c9de1806e 100644 --- a/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.$b.tsx +++ b/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.$b.tsx @@ -1,5 +1,41 @@ +import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' +const LeafComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+

+ rewrite-leaf {data.value.a} {data.value.b} +

+ + leaf-self-link + + + leaf-next-link + + + leaf-parent-link + +
+ ) + }, +}) + export const Route = createFileRoute('/p/$a/$b')({ loader: ({ params }) => ({ a: params.a, @@ -8,32 +44,3 @@ export const Route = createFileRoute('/p/$a/$b')({ }), component: LeafComponent, }) - -function LeafComponent() { - const data = Route.useLoaderData() - - return ( -
-

- rewrite-leaf {data.value.a} {data.value.b} -

- - leaf-self-link - - - leaf-next-link - - - leaf-parent-link - -
- ) -} diff --git a/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.tsx b/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.tsx index acb74aabbd..9702ebedd7 100644 --- a/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.tsx +++ b/benchmarks/ssr/scenarios/rewrites/vue/src/routes/p.$a.tsx @@ -1,5 +1,26 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' +const ParentComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+

rewrite-parent {data.value.a}

+ + parent-branch-link + + +
+ ) + }, +}) + export const Route = createFileRoute('/p/$a')({ loader: ({ params }) => ({ a: params.a, @@ -7,21 +28,3 @@ export const Route = createFileRoute('/p/$a')({ }), component: ParentComponent, }) - -function ParentComponent() { - const data = Route.useLoaderData() - - return ( -
-

rewrite-parent {data.value.a}

- - parent-branch-link - - -
- ) -} diff --git a/benchmarks/ssr/scenarios/rewrites/vue/tsconfig.json b/benchmarks/ssr/scenarios/rewrites/vue/tsconfig.json index 4fe3ccecb1..08c94853f4 100644 --- a/benchmarks/ssr/scenarios/rewrites/vue/tsconfig.json +++ b/benchmarks/ssr/scenarios/rewrites/vue/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/rewrites/vue/vite.config.ts b/benchmarks/ssr/scenarios/rewrites/vue/vite.config.ts index f3b69dfe20..22399ec6b2 100644 --- a/benchmarks/ssr/scenarios/rewrites/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/rewrites/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -25,6 +26,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr rewrites (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/speed.bench.ts b/benchmarks/ssr/scenarios/selective-ssr/react/speed.bench.ts index e0e8a0e3c4..ba6bd4a61d 100644 --- a/benchmarks/ssr/scenarios/selective-ssr/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/selective-ssr/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertSelectiveSanity, benchOptions, @@ -16,6 +16,8 @@ const { default: handler } = (await import( await assertSelectiveSanity(handler) -describe('ssr', () => { - bench('ssr selective (react)', () => runSelectiveLoop(handler), benchOptions) +test('ssr', async ({ bench }) => { + await bench('ssr selective (react)', async () => + runSelectiveLoop(handler), + ).run(benchOptions) }) diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/vite.config.ts b/benchmarks/ssr/scenarios/selective-ssr/react/vite.config.ts index 03ff77aa7b..70c67cff81 100644 --- a/benchmarks/ssr/scenarios/selective-ssr/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/selective-ssr/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr selective-ssr (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/selective-ssr/shared-bench.ts b/benchmarks/ssr/scenarios/selective-ssr/shared-bench.ts index bf97d5d63e..5b2530ccab 100644 --- a/benchmarks/ssr/scenarios/selective-ssr/shared-bench.ts +++ b/benchmarks/ssr/scenarios/selective-ssr/shared-bench.ts @@ -5,7 +5,7 @@ import type { StartRequestHandler } from '../../bench-utils' export type { StartRequestHandler } const benchmarkSeed = 0xdecafbad -const selectiveLoopIterations = 20 +const selectiveLoopTotalRequests = 32 const requestInit = { method: 'GET', @@ -88,7 +88,8 @@ export const benchOptions = { export function runSelectiveLoop(handler: StartRequestHandler) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: selectiveLoopIterations, + concurrency: 16, + totalRequests: selectiveLoopTotalRequests, buildRequest: buildSelectiveRequest, }) } diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/speed.bench.ts b/benchmarks/ssr/scenarios/selective-ssr/solid/speed.bench.ts index 6a2803d45f..76265397ab 100644 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/selective-ssr/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertSelectiveSanity, benchOptions, @@ -16,6 +16,8 @@ const { default: handler } = (await import( await assertSelectiveSanity(handler) -describe('ssr', () => { - bench('ssr selective (solid)', () => runSelectiveLoop(handler), benchOptions) +test('ssr', async ({ bench }) => { + await bench('ssr selective (solid)', async () => + runSelectiveLoop(handler), + ).run(benchOptions) }) diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/vite.config.ts b/benchmarks/ssr/scenarios/selective-ssr/solid/vite.config.ts index 09b42f00e6..2c0042c1ed 100644 --- a/benchmarks/ssr/scenarios/selective-ssr/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/selective-ssr/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr selective-ssr (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/speed.bench.ts b/benchmarks/ssr/scenarios/selective-ssr/vue/speed.bench.ts index f3082a102d..ff60341b27 100644 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/selective-ssr/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertSelectiveSanity, benchOptions, @@ -16,6 +16,8 @@ const { default: handler } = (await import( await assertSelectiveSanity(handler) -describe('ssr', () => { - bench('ssr selective (vue)', () => runSelectiveLoop(handler), benchOptions) +test('ssr', async ({ bench }) => { + await bench('ssr selective (vue)', async () => runSelectiveLoop(handler)).run( + benchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.$c.tsx b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.$c.tsx index 46d7541c2b..8ae7d468f1 100644 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.$c.tsx +++ b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.$c.tsx @@ -1,6 +1,21 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { makeLevelData } from '../../../../loaders/shared-data' +const LevelCComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + const params = Route.useParams() + + return () => ( +
+

{`csr-rendered-${params.value.c}`}

+

{data.value.marker}

+
+ ) + }, +}) + export const Route = createFileRoute('/mix/$a/$b/$c')({ ssr: false, loader: async ({ params }) => { @@ -11,15 +26,3 @@ export const Route = createFileRoute('/mix/$a/$b/$c')({ }, component: LevelCComponent, }) - -function LevelCComponent() { - const data = Route.useLoaderData() - const params = Route.useParams() - - return ( -
-

{`csr-rendered-${params.value.c}`}

-

{data.value.marker}

-
- ) -} diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.tsx b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.tsx index bc685478cc..c10751489e 100644 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.tsx +++ b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.$b.tsx @@ -1,6 +1,22 @@ +import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { makeLevelData } from '../../../../loaders/shared-data' +const LevelBComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + const params = Route.useParams() + + return () => ( +
+

{`data-only-rendered-${params.value.b}`}

+

{data.value.marker}

+ +
+ ) + }, +}) + export const Route = createFileRoute('/mix/$a/$b')({ ssr: 'data-only', loader: async ({ params }) => { @@ -11,16 +27,3 @@ export const Route = createFileRoute('/mix/$a/$b')({ }, component: LevelBComponent, }) - -function LevelBComponent() { - const data = Route.useLoaderData() - const params = Route.useParams() - - return ( -
-

{`data-only-rendered-${params.value.b}`}

-

{data.value.marker}

- -
- ) -} diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.tsx b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.tsx index 8ab4c7d54d..c96165c6d6 100644 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.tsx +++ b/benchmarks/ssr/scenarios/selective-ssr/vue/src/routes/mix.$a.tsx @@ -1,6 +1,22 @@ +import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { makeLevelData } from '../../../../loaders/shared-data' +const LevelAComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + const params = Route.useParams() + + return () => ( +
+

{`level-a-rendered-${params.value.a}`}

+

{data.value.items[0]?.name}

+ +
+ ) + }, +}) + export const Route = createFileRoute('/mix/$a')({ ssr: true, loader: async ({ params }) => { @@ -8,16 +24,3 @@ export const Route = createFileRoute('/mix/$a')({ }, component: LevelAComponent, }) - -function LevelAComponent() { - const data = Route.useLoaderData() - const params = Route.useParams() - - return ( -
-

{`level-a-rendered-${params.value.a}`}

-

{data.value.items[0]?.name}

- -
- ) -} diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/vite.config.ts b/benchmarks/ssr/scenarios/selective-ssr/vue/vite.config.ts index 76299a67fd..09bb36cb0b 100644 --- a/benchmarks/ssr/scenarios/selective-ssr/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/selective-ssr/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr selective-ssr (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts b/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts index 95c91f4529..8be07d2643 100644 --- a/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts @@ -1,11 +1,10 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertSerializationScenario, - runPlainSerializationLoop, runRichSerializationLoop, serializationBenchOptions, - type StartRequestHandler, } from '../shared-bench' +import type { StartRequestHandler } from '../shared-bench' const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href @@ -17,16 +16,8 @@ const { default: handler } = (await import( await assertSerializationScenario(handler) -describe('ssr', () => { - bench( - 'ssr dehydrate rich types (react)', - () => runRichSerializationLoop(handler), - serializationBenchOptions, - ) - - bench( - 'ssr dehydrate plain control (react)', - () => runPlainSerializationLoop(handler), - serializationBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr dehydrate rich types (react)', async () => + runRichSerializationLoop(handler), + ).run(serializationBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/serialization/react/speed.dehydrate-plain-control.bench.ts b/benchmarks/ssr/scenarios/serialization/react/speed.dehydrate-plain-control.bench.ts new file mode 100644 index 0000000000..c70fddc6c4 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/react/speed.dehydrate-plain-control.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertSerializationScenario, + runPlainSerializationLoop, + serializationBenchOptions, +} from '../shared-bench' +import type { StartRequestHandler } from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertSerializationScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr dehydrate plain control (react)', async () => + runPlainSerializationLoop(handler), + ).run(serializationBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/serialization/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/serialization/react/src/routeTree.gen.ts index 92bf0bb732..49bdbd036b 100644 --- a/benchmarks/ssr/scenarios/serialization/react/src/routeTree.gen.ts +++ b/benchmarks/ssr/scenarios/serialization/react/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 RichIdRouteImport } from './routes/rich.$id' import { Route as PlainIdRouteImport } from './routes/plain.$id' +import { Route as RichIdRouteImport } from './routes/rich.$id' -const RichIdRoute = RichIdRouteImport.update({ - id: '/rich/$id', - path: '/rich/$id', - getParentRoute: () => rootRouteImport, -} as any) const PlainIdRoute = PlainIdRouteImport.update({ id: '/plain/$id', path: '/plain/$id', getParentRoute: () => rootRouteImport, } as any) +const RichIdRoute = RichIdRouteImport.update({ + id: '/rich/$id', + path: '/rich/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/plain/$id': typeof PlainIdRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/rich/$id': { - id: '/rich/$id' - path: '/rich/$id' - fullPath: '/rich/$id' - preLoaderRoute: typeof RichIdRouteImport - parentRoute: typeof rootRouteImport - } '/plain/$id': { id: '/plain/$id' path: '/plain/$id' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PlainIdRouteImport parentRoute: typeof rootRouteImport } + '/rich/$id': { + id: '/rich/$id' + path: '/rich/$id' + fullPath: '/rich/$id' + preLoaderRoute: typeof RichIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/ssr/scenarios/serialization/react/tsconfig.json b/benchmarks/ssr/scenarios/serialization/react/tsconfig.json index 9bfd9bcf62..59499356d6 100644 --- a/benchmarks/ssr/scenarios/serialization/react/tsconfig.json +++ b/benchmarks/ssr/scenarios/serialization/react/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "../shared-bench.ts", diff --git a/benchmarks/ssr/scenarios/serialization/react/vite.config.ts b/benchmarks/ssr/scenarios/serialization/react/vite.config.ts index 6280d87579..64568ccb7e 100644 --- a/benchmarks/ssr/scenarios/serialization/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/serialization/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr serialization (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/serialization/shared-bench.ts b/benchmarks/ssr/scenarios/serialization/shared-bench.ts index a39f35dc75..25ed478f03 100644 --- a/benchmarks/ssr/scenarios/serialization/shared-bench.ts +++ b/benchmarks/ssr/scenarios/serialization/shared-bench.ts @@ -5,8 +5,8 @@ import type { StartRequestHandler } from '../../bench-utils' export type { StartRequestHandler } const benchmarkSeed = 0xdecafbad -const richSerializationLoopIterations = 30 -const plainSerializationLoopIterations = 30 +const richSerializationLoopTotalRequests = 32 +const plainSerializationLoopTotalRequests = 32 const requestInit = { method: 'GET', @@ -89,7 +89,8 @@ export const serializationBenchOptions = { export function runRichSerializationLoop(handler: StartRequestHandler) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: richSerializationLoopIterations, + concurrency: 16, + totalRequests: richSerializationLoopTotalRequests, buildRequest: (random, index) => buildSerializationRequest('rich', random, index), }) @@ -98,7 +99,8 @@ export function runRichSerializationLoop(handler: StartRequestHandler) { export function runPlainSerializationLoop(handler: StartRequestHandler) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: plainSerializationLoopIterations, + concurrency: 16, + totalRequests: plainSerializationLoopTotalRequests, buildRequest: (random, index) => buildSerializationRequest('plain', random, index), }) diff --git a/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts b/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts index a939cae51f..70bda8c7af 100644 --- a/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts @@ -1,11 +1,10 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertSerializationScenario, - runPlainSerializationLoop, runRichSerializationLoop, serializationBenchOptions, - type StartRequestHandler, } from '../shared-bench' +import type { StartRequestHandler } from '../shared-bench' const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href @@ -17,16 +16,8 @@ const { default: handler } = (await import( await assertSerializationScenario(handler) -describe('ssr', () => { - bench( - 'ssr dehydrate rich types (solid)', - () => runRichSerializationLoop(handler), - serializationBenchOptions, - ) - - bench( - 'ssr dehydrate plain control (solid)', - () => runPlainSerializationLoop(handler), - serializationBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr dehydrate rich types (solid)', async () => + runRichSerializationLoop(handler), + ).run(serializationBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/serialization/solid/speed.dehydrate-plain-control.bench.ts b/benchmarks/ssr/scenarios/serialization/solid/speed.dehydrate-plain-control.bench.ts new file mode 100644 index 0000000000..d7ccb16f6f --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/solid/speed.dehydrate-plain-control.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertSerializationScenario, + runPlainSerializationLoop, + serializationBenchOptions, +} from '../shared-bench' +import type { StartRequestHandler } from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertSerializationScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr dehydrate plain control (solid)', async () => + runPlainSerializationLoop(handler), + ).run(serializationBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/serialization/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/serialization/solid/src/routeTree.gen.ts index 69b63cffe9..b9e25f918e 100644 --- a/benchmarks/ssr/scenarios/serialization/solid/src/routeTree.gen.ts +++ b/benchmarks/ssr/scenarios/serialization/solid/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 RichIdRouteImport } from './routes/rich.$id' import { Route as PlainIdRouteImport } from './routes/plain.$id' +import { Route as RichIdRouteImport } from './routes/rich.$id' -const RichIdRoute = RichIdRouteImport.update({ - id: '/rich/$id', - path: '/rich/$id', - getParentRoute: () => rootRouteImport, -} as any) const PlainIdRoute = PlainIdRouteImport.update({ id: '/plain/$id', path: '/plain/$id', getParentRoute: () => rootRouteImport, } as any) +const RichIdRoute = RichIdRouteImport.update({ + id: '/rich/$id', + path: '/rich/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/plain/$id': typeof PlainIdRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/rich/$id': { - id: '/rich/$id' - path: '/rich/$id' - fullPath: '/rich/$id' - preLoaderRoute: typeof RichIdRouteImport - parentRoute: typeof rootRouteImport - } '/plain/$id': { id: '/plain/$id' path: '/plain/$id' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PlainIdRouteImport parentRoute: typeof rootRouteImport } + '/rich/$id': { + id: '/rich/$id' + path: '/rich/$id' + fullPath: '/rich/$id' + preLoaderRoute: typeof RichIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/ssr/scenarios/serialization/solid/tsconfig.json b/benchmarks/ssr/scenarios/serialization/solid/tsconfig.json index d7feff5f61..3ea91b977f 100644 --- a/benchmarks/ssr/scenarios/serialization/solid/tsconfig.json +++ b/benchmarks/ssr/scenarios/serialization/solid/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "../shared-bench.ts", diff --git a/benchmarks/ssr/scenarios/serialization/solid/vite.config.ts b/benchmarks/ssr/scenarios/serialization/solid/vite.config.ts index 67df3299e1..db81e2ab74 100644 --- a/benchmarks/ssr/scenarios/serialization/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/serialization/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr serialization (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts b/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts index ee1e072286..7f733dd601 100644 --- a/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts @@ -1,11 +1,10 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertSerializationScenario, - runPlainSerializationLoop, runRichSerializationLoop, serializationBenchOptions, - type StartRequestHandler, } from '../shared-bench' +import type { StartRequestHandler } from '../shared-bench' const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href @@ -17,16 +16,8 @@ const { default: handler } = (await import( await assertSerializationScenario(handler) -describe('ssr', () => { - bench( - 'ssr dehydrate rich types (vue)', - () => runRichSerializationLoop(handler), - serializationBenchOptions, - ) - - bench( - 'ssr dehydrate plain control (vue)', - () => runPlainSerializationLoop(handler), - serializationBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr dehydrate rich types (vue)', async () => + runRichSerializationLoop(handler), + ).run(serializationBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/serialization/vue/speed.dehydrate-plain-control.bench.ts b/benchmarks/ssr/scenarios/serialization/vue/speed.dehydrate-plain-control.bench.ts new file mode 100644 index 0000000000..8efdeb6c79 --- /dev/null +++ b/benchmarks/ssr/scenarios/serialization/vue/speed.dehydrate-plain-control.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertSerializationScenario, + runPlainSerializationLoop, + serializationBenchOptions, +} from '../shared-bench' +import type { StartRequestHandler } from '../shared-bench' + +const appModuleUrl = new URL('./dist/server/server.js', import.meta.url).href + +const { default: handler } = (await import( + /* @vite-ignore */ appModuleUrl +)) as { + default: StartRequestHandler +} + +await assertSerializationScenario(handler) + +test('ssr', async ({ bench }) => { + await bench('ssr dehydrate plain control (vue)', async () => + runPlainSerializationLoop(handler), + ).run(serializationBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/serialization/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/serialization/vue/src/routeTree.gen.ts index 02268c2c3c..cd7b0b449b 100644 --- a/benchmarks/ssr/scenarios/serialization/vue/src/routeTree.gen.ts +++ b/benchmarks/ssr/scenarios/serialization/vue/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 RichIdRouteImport } from './routes/rich.$id' import { Route as PlainIdRouteImport } from './routes/plain.$id' +import { Route as RichIdRouteImport } from './routes/rich.$id' -const RichIdRoute = RichIdRouteImport.update({ - id: '/rich/$id', - path: '/rich/$id', - getParentRoute: () => rootRouteImport, -} as any) const PlainIdRoute = PlainIdRouteImport.update({ id: '/plain/$id', path: '/plain/$id', getParentRoute: () => rootRouteImport, } as any) +const RichIdRoute = RichIdRouteImport.update({ + id: '/rich/$id', + path: '/rich/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/plain/$id': typeof PlainIdRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/rich/$id': { - id: '/rich/$id' - path: '/rich/$id' - fullPath: '/rich/$id' - preLoaderRoute: typeof RichIdRouteImport - parentRoute: typeof rootRouteImport - } '/plain/$id': { id: '/plain/$id' path: '/plain/$id' @@ -65,6 +58,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PlainIdRouteImport parentRoute: typeof rootRouteImport } + '/rich/$id': { + id: '/rich/$id' + path: '/rich/$id' + fullPath: '/rich/$id' + preLoaderRoute: typeof RichIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/ssr/scenarios/serialization/vue/src/routes/plain.$id.tsx b/benchmarks/ssr/scenarios/serialization/vue/src/routes/plain.$id.tsx index d41d123f1f..47fdeb971f 100644 --- a/benchmarks/ssr/scenarios/serialization/vue/src/routes/plain.$id.tsx +++ b/benchmarks/ssr/scenarios/serialization/vue/src/routes/plain.$id.tsx @@ -1,24 +1,27 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { makePlainSerializationData } from '../../../shared-data' +const PlainComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+

{data.value.label}

+

{data.value.createdAt}

+

{data.value.lookup[0]?.[1].label}

+

{data.value.tags[0]}

+

{data.value.count}

+

{data.value.nested[0]?.id}

+

{data.value.points[0]?.label}

+

{data.value.problem.message}

+
+ ) + }, +}) + export const Route = createFileRoute('/plain/$id')({ loader: ({ params }) => makePlainSerializationData(params.id), component: PlainComponent, }) - -function PlainComponent() { - const data = Route.useLoaderData() - - return ( -
-

{data.value.label}

-

{data.value.createdAt}

-

{data.value.lookup[0]?.[1].label}

-

{data.value.tags[0]}

-

{data.value.count}

-

{data.value.nested[0]?.id}

-

{data.value.points[0]?.label}

-

{data.value.problem.message}

-
- ) -} diff --git a/benchmarks/ssr/scenarios/serialization/vue/src/routes/rich.$id.tsx b/benchmarks/ssr/scenarios/serialization/vue/src/routes/rich.$id.tsx index d50a3f292d..1ee86cefd3 100644 --- a/benchmarks/ssr/scenarios/serialization/vue/src/routes/rich.$id.tsx +++ b/benchmarks/ssr/scenarios/serialization/vue/src/routes/rich.$id.tsx @@ -1,24 +1,27 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { makeRichSerializationData } from '../../../shared-data' +const RichComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+

{data.value.label}

+

{data.value.createdAt.toISOString()}

+

{data.value.lookup.get('k0')?.label}

+

{Array.from(data.value.tags)[0]}

+

{data.value.count.toString()}

+

{data.value.nested[0]?.id}

+

{data.value.points[0]?.label}

+

{data.value.problem.message}

+
+ ) + }, +}) + export const Route = createFileRoute('/rich/$id')({ loader: ({ params }) => makeRichSerializationData(params.id), component: RichComponent, }) - -function RichComponent() { - const data = Route.useLoaderData() - - return ( -
-

{data.value.label}

-

{data.value.createdAt.toISOString()}

-

{data.value.lookup.get('k0')?.label}

-

{Array.from(data.value.tags)[0]}

-

{data.value.count.toString()}

-

{data.value.nested[0]?.id}

-

{data.value.points[0]?.label}

-

{data.value.problem.message}

-
- ) -} diff --git a/benchmarks/ssr/scenarios/serialization/vue/tsconfig.json b/benchmarks/ssr/scenarios/serialization/vue/tsconfig.json index 4a7f0ef092..5d8c7b5b62 100644 --- a/benchmarks/ssr/scenarios/serialization/vue/tsconfig.json +++ b/benchmarks/ssr/scenarios/serialization/vue/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "../shared-bench.ts", diff --git a/benchmarks/ssr/scenarios/serialization/vue/vite.config.ts b/benchmarks/ssr/scenarios/serialization/vue/vite.config.ts index 76f99750c3..b89537fa18 100644 --- a/benchmarks/ssr/scenarios/serialization/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/serialization/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr serialization (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/server-fn-transport/bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/bench.ts index 73a79aa79a..4274c724ca 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/bench.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/bench.ts @@ -67,9 +67,9 @@ const commonHeaders = { 'sec-fetch-site': 'same-origin', accept: acceptHeader, } satisfies HeadersInit -const serverFnMultipartLoopIterations = 125 -const serverFnRawResponseLoopIterations = 175 -const serverFnRawStreamLoopIterations = 100 +const serverFnMultipartLoopTotalRequests = 128 +const serverFnRawResponseLoopTotalRequests = 176 +const serverFnRawStreamLoopTotalRequests = 112 export const serverFnTransportBenchOptions = { warmupIterations: 100, @@ -519,7 +519,8 @@ export function runServerFnMultipartRequestLoop( ) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: serverFnMultipartLoopIterations, + concurrency: 16, + totalRequests: serverFnMultipartLoopTotalRequests, buildRequest: (_random, index) => buildMultipartRequest(context.urls, context.multipartPayloads, index), validateResponse: validateSerializedResponse, @@ -532,7 +533,8 @@ export function runServerFnRawResponseRequestLoop( ) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: serverFnRawResponseLoopIterations, + concurrency: 16, + totalRequests: serverFnRawResponseLoopTotalRequests, buildRequest: (_random, index) => buildRawResponseRequest(context.urls, context.rawPayloads, index), validateResponse: validateRawResponse, @@ -545,7 +547,8 @@ export function runServerFnRawStreamRequestLoop( ) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: serverFnRawStreamLoopIterations, + concurrency: 16, + totalRequests: serverFnRawStreamLoopTotalRequests, buildRequest: (_random, index) => buildRawStreamRequest(context.urls, context.streamPayloads, index), validateResponse: validateRawStreamResponse, diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/speed.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.bench.ts index c168f6e61c..fa80cdb690 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.bench.ts @@ -1,9 +1,7 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerFnTransportScenario, runServerFnMultipartRequestLoop, - runServerFnRawResponseRequestLoop, - runServerFnRawStreamRequestLoop, serverFnTransportBenchOptions, setupServerFnTransportBench, } from '../bench' @@ -14,27 +12,12 @@ const { default: handler } = (await import( )) as { default: StartRequestHandler } - const context = await setupServerFnTransportBench(handler) await assertServerFnTransportScenario(handler, context) -describe('ssr', () => { - bench( - 'ssr server-fn multipart (react)', - () => runServerFnMultipartRequestLoop(handler, context), - serverFnTransportBenchOptions, - ) - - bench( - 'ssr server-fn raw-response (react)', - () => runServerFnRawResponseRequestLoop(handler, context), - serverFnTransportBenchOptions, - ) - - bench( - 'ssr server-fn raw-stream (react)', - () => runServerFnRawStreamRequestLoop(handler, context), - serverFnTransportBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-fn multipart (react)', async () => + runServerFnMultipartRequestLoop(handler, context), + ).run(serverFnTransportBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-response.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-response.bench.ts new file mode 100644 index 0000000000..fd535ee313 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-response.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnTransportScenario, + runServerFnRawResponseRequestLoop, + serverFnTransportBenchOptions, + setupServerFnTransportBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnTransportBench(handler) + +await assertServerFnTransportScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn raw-response (react)', async () => + runServerFnRawResponseRequestLoop(handler, context), + ).run(serverFnTransportBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-stream.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-stream.bench.ts new file mode 100644 index 0000000000..8fbce405dd --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.server-fn-raw-stream.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnTransportScenario, + runServerFnRawStreamRequestLoop, + serverFnTransportBenchOptions, + setupServerFnTransportBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnTransportBench(handler) + +await assertServerFnTransportScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn raw-stream (react)', async () => + runServerFnRawStreamRequestLoop(handler, context), + ).run(serverFnTransportBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/tsconfig.json b/benchmarks/ssr/scenarios/server-fn-transport/react/tsconfig.json index 08c349fd49..4f3cc314af 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/tsconfig.json +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "../bench.ts", diff --git a/benchmarks/ssr/scenarios/server-fn-transport/react/vite.config.ts b/benchmarks/ssr/scenarios/server-fn-transport/react/vite.config.ts index 4c6293d5d7..c37fde0c4b 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-fn-transport (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.bench.ts index b93d7d79a9..adac07cb22 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.bench.ts @@ -1,9 +1,7 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerFnTransportScenario, runServerFnMultipartRequestLoop, - runServerFnRawResponseRequestLoop, - runServerFnRawStreamRequestLoop, serverFnTransportBenchOptions, setupServerFnTransportBench, } from '../bench' @@ -14,27 +12,12 @@ const { default: handler } = (await import( )) as { default: StartRequestHandler } - const context = await setupServerFnTransportBench(handler) await assertServerFnTransportScenario(handler, context) -describe('ssr', () => { - bench( - 'ssr server-fn multipart (solid)', - () => runServerFnMultipartRequestLoop(handler, context), - serverFnTransportBenchOptions, - ) - - bench( - 'ssr server-fn raw-response (solid)', - () => runServerFnRawResponseRequestLoop(handler, context), - serverFnTransportBenchOptions, - ) - - bench( - 'ssr server-fn raw-stream (solid)', - () => runServerFnRawStreamRequestLoop(handler, context), - serverFnTransportBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-fn multipart (solid)', async () => + runServerFnMultipartRequestLoop(handler, context), + ).run(serverFnTransportBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-response.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-response.bench.ts new file mode 100644 index 0000000000..843a4c97ce --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-response.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnTransportScenario, + runServerFnRawResponseRequestLoop, + serverFnTransportBenchOptions, + setupServerFnTransportBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnTransportBench(handler) + +await assertServerFnTransportScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn raw-response (solid)', async () => + runServerFnRawResponseRequestLoop(handler, context), + ).run(serverFnTransportBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-stream.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-stream.bench.ts new file mode 100644 index 0000000000..aa24d55e79 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.server-fn-raw-stream.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnTransportScenario, + runServerFnRawStreamRequestLoop, + serverFnTransportBenchOptions, + setupServerFnTransportBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnTransportBench(handler) + +await assertServerFnTransportScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn raw-stream (solid)', async () => + runServerFnRawStreamRequestLoop(handler, context), + ).run(serverFnTransportBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/tsconfig.json b/benchmarks/ssr/scenarios/server-fn-transport/solid/tsconfig.json index 54a0e49d93..0af78df33d 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/tsconfig.json +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "../bench.ts", diff --git a/benchmarks/ssr/scenarios/server-fn-transport/solid/vite.config.ts b/benchmarks/ssr/scenarios/server-fn-transport/solid/vite.config.ts index b71d03009b..a8af4a6b50 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-fn-transport (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.bench.ts index 6f803d1665..24305cf1bc 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.bench.ts @@ -1,9 +1,7 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerFnTransportScenario, runServerFnMultipartRequestLoop, - runServerFnRawResponseRequestLoop, - runServerFnRawStreamRequestLoop, serverFnTransportBenchOptions, setupServerFnTransportBench, } from '../bench' @@ -14,27 +12,12 @@ const { default: handler } = (await import( )) as { default: StartRequestHandler } - const context = await setupServerFnTransportBench(handler) await assertServerFnTransportScenario(handler, context) -describe('ssr', () => { - bench( - 'ssr server-fn multipart (vue)', - () => runServerFnMultipartRequestLoop(handler, context), - serverFnTransportBenchOptions, - ) - - bench( - 'ssr server-fn raw-response (vue)', - () => runServerFnRawResponseRequestLoop(handler, context), - serverFnTransportBenchOptions, - ) - - bench( - 'ssr server-fn raw-stream (vue)', - () => runServerFnRawStreamRequestLoop(handler, context), - serverFnTransportBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-fn multipart (vue)', async () => + runServerFnMultipartRequestLoop(handler, context), + ).run(serverFnTransportBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-response.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-response.bench.ts new file mode 100644 index 0000000000..2eeb9a4f6b --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-response.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnTransportScenario, + runServerFnRawResponseRequestLoop, + serverFnTransportBenchOptions, + setupServerFnTransportBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnTransportBench(handler) + +await assertServerFnTransportScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn raw-response (vue)', async () => + runServerFnRawResponseRequestLoop(handler, context), + ).run(serverFnTransportBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-stream.bench.ts b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-stream.bench.ts new file mode 100644 index 0000000000..a73905004d --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.server-fn-raw-stream.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnTransportScenario, + runServerFnRawStreamRequestLoop, + serverFnTransportBenchOptions, + setupServerFnTransportBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnTransportBench(handler) + +await assertServerFnTransportScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn raw-stream (vue)', async () => + runServerFnRawStreamRequestLoop(handler, context), + ).run(serverFnTransportBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/tsconfig.json b/benchmarks/ssr/scenarios/server-fn-transport/vue/tsconfig.json index 29efa76d67..5b7742b414 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/tsconfig.json +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "../bench.ts", diff --git a/benchmarks/ssr/scenarios/server-fn-transport/vue/vite.config.ts b/benchmarks/ssr/scenarios/server-fn-transport/vue/vite.config.ts index 5d74904e14..0f3e2ce84d 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-fn-transport (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/server-fns/bench.ts b/benchmarks/ssr/scenarios/server-fns/bench.ts index 65a8749cef..1461ce2bfd 100644 --- a/benchmarks/ssr/scenarios/server-fns/bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/bench.ts @@ -53,12 +53,12 @@ const documentRequestInit = { accept: 'text/html', }, } satisfies RequestInit -const serverFnGetLoopIterations = 100 -const serverFnPostLoopIterations = 150 -const serverFnRedirectLoopIterations = 125 -const serverFnNotFoundLoopIterations = 200 -const serverFnSendContextLoopIterations = 175 -const serverFnDocumentSsrLoopIterations = 45 +const serverFnGetLoopTotalRequests = 112 +const serverFnPostLoopTotalRequests = 160 +const serverFnRedirectLoopTotalRequests = 128 +const serverFnNotFoundLoopTotalRequests = 208 +const serverFnSendContextLoopTotalRequests = 176 +const serverFnDocumentSsrLoopTotalRequests = 48 export const serverFnBenchOptions = { warmupIterations: 100, @@ -456,7 +456,8 @@ export function runServerFnGetRequestLoop( ) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: serverFnGetLoopIterations, + concurrency: 16, + totalRequests: serverFnGetLoopTotalRequests, buildRequest: (_random, index) => buildGetRequest(context.urls, context.getQueries, index), }) @@ -468,7 +469,8 @@ export function runServerFnPostRequestLoop( ) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: serverFnPostLoopIterations, + concurrency: 16, + totalRequests: serverFnPostLoopTotalRequests, buildRequest: (_random, index) => buildPostRequest(context.urls, context.bodies, index), }) @@ -480,7 +482,8 @@ export function runServerFnRedirectRequestLoop( ) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: serverFnRedirectLoopIterations, + concurrency: 16, + totalRequests: serverFnRedirectLoopTotalRequests, buildRequest: (_random, index) => buildRedirectRequest(context.urls, context.bodies, index), validateResponse: validateRedirectResponse, @@ -493,7 +496,8 @@ export function runServerFnNotFoundRequestLoop( ) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: serverFnNotFoundLoopIterations, + concurrency: 16, + totalRequests: serverFnNotFoundLoopTotalRequests, buildRequest: (_random, index) => buildNotFoundRequest(context.urls, context.bodies, index), validateResponse: (response) => @@ -507,7 +511,8 @@ export function runServerFnSendContextRequestLoop( ) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: serverFnSendContextLoopIterations, + concurrency: 16, + totalRequests: serverFnSendContextLoopTotalRequests, buildRequest: (_random, index) => buildContextRequest(context.urls, context.contextBodies, index), validateResponse: (response) => @@ -520,7 +525,8 @@ export function runServerFnDocumentSsrRequestLoop( ) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: serverFnDocumentSsrLoopIterations, + concurrency: 16, + totalRequests: serverFnDocumentSsrLoopTotalRequests, buildRequest: buildSsrCallRequest, validateResponse: validateDocumentResponse, }) diff --git a/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts b/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts index 46dca5adc7..c876772ad1 100644 --- a/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts @@ -1,12 +1,7 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerFnScenario, - runServerFnDocumentSsrRequestLoop, runServerFnGetRequestLoop, - runServerFnNotFoundRequestLoop, - runServerFnPostRequestLoop, - runServerFnRedirectRequestLoop, - runServerFnSendContextRequestLoop, serverFnBenchOptions, setupServerFnBench, } from '../bench' @@ -17,45 +12,12 @@ const { default: handler } = (await import( )) as { default: StartRequestHandler } - const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -describe('ssr', () => { - bench( - 'ssr server-fn GET (react)', - () => runServerFnGetRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn POST (react)', - () => runServerFnPostRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn redirect (react)', - () => runServerFnRedirectRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn not-found (react)', - () => runServerFnNotFoundRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn send-context (react)', - () => runServerFnSendContextRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn during document ssr (react)', - () => runServerFnDocumentSsrRequestLoop(handler), - serverFnBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-fn GET (react)', async () => + runServerFnGetRequestLoop(handler, context), + ).run(serverFnBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-during-document-ssr.bench.ts b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-during-document-ssr.bench.ts new file mode 100644 index 0000000000..6a0cb55f78 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-during-document-ssr.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnDocumentSsrRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn during document ssr (react)', async () => + runServerFnDocumentSsrRequestLoop(handler), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-not-found.bench.ts b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-not-found.bench.ts new file mode 100644 index 0000000000..96f1160078 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-not-found.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnNotFoundRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn not-found (react)', async () => + runServerFnNotFoundRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-post.bench.ts b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-post.bench.ts new file mode 100644 index 0000000000..e85d5debd3 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-post.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnPostRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn POST (react)', async () => + runServerFnPostRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-redirect.bench.ts b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-redirect.bench.ts new file mode 100644 index 0000000000..5dae598549 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-redirect.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnRedirectRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn redirect (react)', async () => + runServerFnRedirectRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-send-context.bench.ts b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-send-context.bench.ts new file mode 100644 index 0000000000..40d6961206 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.server-fn-send-context.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnSendContextRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn send-context (react)', async () => + runServerFnSendContextRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/react/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-fns/react/src/routeTree.gen.ts index 1abf49d56b..4daa5f03b0 100644 --- a/benchmarks/ssr/scenarios/server-fns/react/src/routeTree.gen.ts +++ b/benchmarks/ssr/scenarios/server-fns/react/src/routeTree.gen.ts @@ -10,24 +10,24 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as SsrCallIdRouteImport } from './routes/ssr-call.$id' import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' +import { Route as SsrCallIdRouteImport } from './routes/ssr-call.$id' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const SsrCallIdRoute = SsrCallIdRouteImport.update({ - id: '/ssr-call/$id', - path: '/ssr-call/$id', - getParentRoute: () => rootRouteImport, -} as any) const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ id: '/api/fn-urls', path: '/api/fn-urls', getParentRoute: () => rootRouteImport, } as any) +const SsrCallIdRoute = SsrCallIdRouteImport.update({ + id: '/ssr-call/$id', + path: '/ssr-call/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -68,13 +68,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/ssr-call/$id': { - id: '/ssr-call/$id' - path: '/ssr-call/$id' - fullPath: '/ssr-call/$id' - preLoaderRoute: typeof SsrCallIdRouteImport - parentRoute: typeof rootRouteImport - } '/api/fn-urls': { id: '/api/fn-urls' path: '/api/fn-urls' @@ -82,6 +75,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiFnUrlsRouteImport parentRoute: typeof rootRouteImport } + '/ssr-call/$id': { + id: '/ssr-call/$id' + path: '/ssr-call/$id' + fullPath: '/ssr-call/$id' + preLoaderRoute: typeof SsrCallIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/ssr/scenarios/server-fns/react/tsconfig.json b/benchmarks/ssr/scenarios/server-fns/react/tsconfig.json index 91027bfc88..cf14e1d440 100644 --- a/benchmarks/ssr/scenarios/server-fns/react/tsconfig.json +++ b/benchmarks/ssr/scenarios/server-fns/react/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/server-fns/react/vite.config.ts b/benchmarks/ssr/scenarios/server-fns/react/vite.config.ts index 4f608f0444..cd56edda95 100644 --- a/benchmarks/ssr/scenarios/server-fns/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-fns/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-fns (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts b/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts index a116ea9102..f6bbdc9e73 100644 --- a/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts @@ -1,12 +1,7 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerFnScenario, - runServerFnDocumentSsrRequestLoop, runServerFnGetRequestLoop, - runServerFnNotFoundRequestLoop, - runServerFnPostRequestLoop, - runServerFnRedirectRequestLoop, - runServerFnSendContextRequestLoop, serverFnBenchOptions, setupServerFnBench, } from '../bench' @@ -17,45 +12,12 @@ const { default: handler } = (await import( )) as { default: StartRequestHandler } - const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -describe('ssr', () => { - bench( - 'ssr server-fn GET (solid)', - () => runServerFnGetRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn POST (solid)', - () => runServerFnPostRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn redirect (solid)', - () => runServerFnRedirectRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn not-found (solid)', - () => runServerFnNotFoundRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn send-context (solid)', - () => runServerFnSendContextRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn during document ssr (solid)', - () => runServerFnDocumentSsrRequestLoop(handler), - serverFnBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-fn GET (solid)', async () => + runServerFnGetRequestLoop(handler, context), + ).run(serverFnBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-during-document-ssr.bench.ts b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-during-document-ssr.bench.ts new file mode 100644 index 0000000000..933f61b59c --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-during-document-ssr.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnDocumentSsrRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn during document ssr (solid)', async () => + runServerFnDocumentSsrRequestLoop(handler), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-not-found.bench.ts b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-not-found.bench.ts new file mode 100644 index 0000000000..513b69f4ba --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-not-found.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnNotFoundRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn not-found (solid)', async () => + runServerFnNotFoundRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-post.bench.ts b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-post.bench.ts new file mode 100644 index 0000000000..e2ce8ad9ee --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-post.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnPostRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn POST (solid)', async () => + runServerFnPostRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-redirect.bench.ts b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-redirect.bench.ts new file mode 100644 index 0000000000..14353f1290 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-redirect.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnRedirectRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn redirect (solid)', async () => + runServerFnRedirectRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-send-context.bench.ts b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-send-context.bench.ts new file mode 100644 index 0000000000..76d3a554bd --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.server-fn-send-context.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnSendContextRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn send-context (solid)', async () => + runServerFnSendContextRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-fns/solid/src/routeTree.gen.ts index 3db5e487b3..3d0bd34eaa 100644 --- a/benchmarks/ssr/scenarios/server-fns/solid/src/routeTree.gen.ts +++ b/benchmarks/ssr/scenarios/server-fns/solid/src/routeTree.gen.ts @@ -10,24 +10,24 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as SsrCallIdRouteImport } from './routes/ssr-call.$id' import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' +import { Route as SsrCallIdRouteImport } from './routes/ssr-call.$id' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const SsrCallIdRoute = SsrCallIdRouteImport.update({ - id: '/ssr-call/$id', - path: '/ssr-call/$id', - getParentRoute: () => rootRouteImport, -} as any) const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ id: '/api/fn-urls', path: '/api/fn-urls', getParentRoute: () => rootRouteImport, } as any) +const SsrCallIdRoute = SsrCallIdRouteImport.update({ + id: '/ssr-call/$id', + path: '/ssr-call/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -68,13 +68,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/ssr-call/$id': { - id: '/ssr-call/$id' - path: '/ssr-call/$id' - fullPath: '/ssr-call/$id' - preLoaderRoute: typeof SsrCallIdRouteImport - parentRoute: typeof rootRouteImport - } '/api/fn-urls': { id: '/api/fn-urls' path: '/api/fn-urls' @@ -82,6 +75,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ApiFnUrlsRouteImport parentRoute: typeof rootRouteImport } + '/ssr-call/$id': { + id: '/ssr-call/$id' + path: '/ssr-call/$id' + fullPath: '/ssr-call/$id' + preLoaderRoute: typeof SsrCallIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/ssr/scenarios/server-fns/solid/tsconfig.json b/benchmarks/ssr/scenarios/server-fns/solid/tsconfig.json index b1806caa67..42c3a2160f 100644 --- a/benchmarks/ssr/scenarios/server-fns/solid/tsconfig.json +++ b/benchmarks/ssr/scenarios/server-fns/solid/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/server-fns/solid/vite.config.ts b/benchmarks/ssr/scenarios/server-fns/solid/vite.config.ts index ef8292a042..2f2f78b75c 100644 --- a/benchmarks/ssr/scenarios/server-fns/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-fns/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-fns (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts b/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts index 02cb03efd1..3f67c1a500 100644 --- a/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts @@ -1,12 +1,7 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerFnScenario, - runServerFnDocumentSsrRequestLoop, runServerFnGetRequestLoop, - runServerFnNotFoundRequestLoop, - runServerFnPostRequestLoop, - runServerFnRedirectRequestLoop, - runServerFnSendContextRequestLoop, serverFnBenchOptions, setupServerFnBench, } from '../bench' @@ -17,45 +12,12 @@ const { default: handler } = (await import( )) as { default: StartRequestHandler } - const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -describe('ssr', () => { - bench( - 'ssr server-fn GET (vue)', - () => runServerFnGetRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn POST (vue)', - () => runServerFnPostRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn redirect (vue)', - () => runServerFnRedirectRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn not-found (vue)', - () => runServerFnNotFoundRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn send-context (vue)', - () => runServerFnSendContextRequestLoop(handler, context), - serverFnBenchOptions, - ) - - bench( - 'ssr server-fn during document ssr (vue)', - () => runServerFnDocumentSsrRequestLoop(handler), - serverFnBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-fn GET (vue)', async () => + runServerFnGetRequestLoop(handler, context), + ).run(serverFnBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-during-document-ssr.bench.ts b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-during-document-ssr.bench.ts new file mode 100644 index 0000000000..56c9addca5 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-during-document-ssr.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnDocumentSsrRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn during document ssr (vue)', async () => + runServerFnDocumentSsrRequestLoop(handler), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-not-found.bench.ts b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-not-found.bench.ts new file mode 100644 index 0000000000..e9a6e31617 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-not-found.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnNotFoundRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn not-found (vue)', async () => + runServerFnNotFoundRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-post.bench.ts b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-post.bench.ts new file mode 100644 index 0000000000..df9312ccd1 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-post.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnPostRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn POST (vue)', async () => + runServerFnPostRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-redirect.bench.ts b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-redirect.bench.ts new file mode 100644 index 0000000000..67c4611644 --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-redirect.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnRedirectRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn redirect (vue)', async () => + runServerFnRedirectRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-send-context.bench.ts b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-send-context.bench.ts new file mode 100644 index 0000000000..6f51ef4bab --- /dev/null +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.server-fn-send-context.bench.ts @@ -0,0 +1,23 @@ +import { test } from 'vitest' +import { + assertServerFnScenario, + runServerFnSendContextRequestLoop, + serverFnBenchOptions, + setupServerFnBench, +} from '../bench' +import type { StartRequestHandler } from '../bench' + +const { default: handler } = (await import( + /* @vite-ignore */ new URL('./dist/server/server.js', import.meta.url).href +)) as { + default: StartRequestHandler +} +const context = await setupServerFnBench(handler) + +await assertServerFnScenario(handler, context) + +test('ssr', async ({ bench }) => { + await bench('ssr server-fn send-context (vue)', async () => + runServerFnSendContextRequestLoop(handler, context), + ).run(serverFnBenchOptions) +}) diff --git a/benchmarks/ssr/scenarios/server-fns/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/server-fns/vue/src/routeTree.gen.ts index fa27fb1a5d..0e24cd9c15 100644 --- a/benchmarks/ssr/scenarios/server-fns/vue/src/routeTree.gen.ts +++ b/benchmarks/ssr/scenarios/server-fns/vue/src/routeTree.gen.ts @@ -10,24 +10,24 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as SsrCallIdRouteImport } from './routes/ssr-call.$id' import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' +import { Route as SsrCallIdRouteImport } from './routes/ssr-call.$id' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const SsrCallIdRoute = SsrCallIdRouteImport.update({ - id: '/ssr-call/$id', - path: '/ssr-call/$id', - getParentRoute: () => rootRouteImport, -} as any) const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ id: '/api/fn-urls', path: '/api/fn-urls', getParentRoute: () => rootRouteImport, } as any) +const SsrCallIdRoute = SsrCallIdRouteImport.update({ + id: '/ssr-call/$id', + path: '/ssr-call/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -68,13 +68,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/ssr-call/$id': { - id: '/ssr-call/$id' - path: '/ssr-call/$id' - fullPath: '/ssr-call/$id' - preLoaderRoute: typeof SsrCallIdRouteImport - parentRoute: typeof rootRouteImport - } '/api/fn-urls': { id: '/api/fn-urls' path: '/api/fn-urls' @@ -82,6 +75,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ApiFnUrlsRouteImport parentRoute: typeof rootRouteImport } + '/ssr-call/$id': { + id: '/ssr-call/$id' + path: '/ssr-call/$id' + fullPath: '/ssr-call/$id' + preLoaderRoute: typeof SsrCallIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/ssr/scenarios/server-fns/vue/src/routes/ssr-call.$id.tsx b/benchmarks/ssr/scenarios/server-fns/vue/src/routes/ssr-call.$id.tsx index 8abe77c2af..45fad23dc0 100644 --- a/benchmarks/ssr/scenarios/server-fns/vue/src/routes/ssr-call.$id.tsx +++ b/benchmarks/ssr/scenarios/server-fns/vue/src/routes/ssr-call.$id.tsx @@ -1,6 +1,17 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { echoGet } from '../fns' +const SsrCallComponent = defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
{data.value.marker}
+ ) + }, +}) + export const Route = createFileRoute('/ssr-call/$id')({ loader: async ({ params }) => { const result = await echoGet({ @@ -15,9 +26,3 @@ export const Route = createFileRoute('/ssr-call/$id')({ }, component: SsrCallComponent, }) - -function SsrCallComponent() { - const data = Route.useLoaderData() - - return
{data.value.marker}
-} diff --git a/benchmarks/ssr/scenarios/server-fns/vue/tsconfig.json b/benchmarks/ssr/scenarios/server-fns/vue/tsconfig.json index 4fe3ccecb1..08c94853f4 100644 --- a/benchmarks/ssr/scenarios/server-fns/vue/tsconfig.json +++ b/benchmarks/ssr/scenarios/server-fns/vue/tsconfig.json @@ -6,7 +6,7 @@ "types": ["node", "vite/client", "vitest/globals"] }, "include": [ - "speed.bench.ts", + "speed*.bench.ts", "vite.config.ts", "../../../bench-utils.ts", "./src/**/*" diff --git a/benchmarks/ssr/scenarios/server-fns/vue/vite.config.ts b/benchmarks/ssr/scenarios/server-fns/vue/vite.config.ts index 2a7783ed7a..5f3e3ca4b5 100644 --- a/benchmarks/ssr/scenarios/server-fns/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-fns/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-fns (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/react/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes-middleware/react/speed.bench.ts index 8e96bc8e04..6331216522 100644 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-routes-middleware/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerRouteMiddlewareResponse, runServerRouteMiddlewareLoop, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertServerRouteMiddlewareResponse(handler) -describe('ssr', () => { - bench( - 'ssr server-route middleware (react)', - () => runServerRouteMiddlewareLoop(handler), - serverRouteMiddlewareBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-route middleware (react)', async () => + runServerRouteMiddlewareLoop(handler), + ).run(serverRouteMiddlewareBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/react/vite.config.ts b/benchmarks/ssr/scenarios/server-routes-middleware/react/vite.config.ts index 9c41f6d542..f6998c2ac8 100644 --- a/benchmarks/ssr/scenarios/server-routes-middleware/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-routes-middleware/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-routes-middleware (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/shared.ts b/benchmarks/ssr/scenarios/server-routes-middleware/shared.ts index 3177e0f763..663ca09294 100644 --- a/benchmarks/ssr/scenarios/server-routes-middleware/shared.ts +++ b/benchmarks/ssr/scenarios/server-routes-middleware/shared.ts @@ -4,7 +4,7 @@ import type { StartRequestHandler } from '../../bench-utils' export type { StartRequestHandler } const benchmarkSeed = 0xdecafbad -const loopIterations = 150 +const loopTotalRequests = 160 const apiRequestInit = { method: 'GET', @@ -22,7 +22,8 @@ export const serverRouteMiddlewareBenchOptions = { export function runServerRouteMiddlewareLoop(handler: StartRequestHandler) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: loopIterations, + concurrency: 16, + totalRequests: loopTotalRequests, buildRequest: (random) => new Request( `http://localhost/api/chain/${randomSegment(random)}`, diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/solid/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes-middleware/solid/speed.bench.ts index 7e6fac4bbe..77d58e7b19 100644 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-routes-middleware/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerRouteMiddlewareResponse, runServerRouteMiddlewareLoop, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertServerRouteMiddlewareResponse(handler) -describe('ssr', () => { - bench( - 'ssr server-route middleware (solid)', - () => runServerRouteMiddlewareLoop(handler), - serverRouteMiddlewareBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-route middleware (solid)', async () => + runServerRouteMiddlewareLoop(handler), + ).run(serverRouteMiddlewareBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/solid/vite.config.ts b/benchmarks/ssr/scenarios/server-routes-middleware/solid/vite.config.ts index 89116c111e..800cf9db9f 100644 --- a/benchmarks/ssr/scenarios/server-routes-middleware/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-routes-middleware/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-routes-middleware (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/vue/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes-middleware/vue/speed.bench.ts index e67ca0a420..3d03b9c1fa 100644 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-routes-middleware/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerRouteMiddlewareResponse, runServerRouteMiddlewareLoop, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertServerRouteMiddlewareResponse(handler) -describe('ssr', () => { - bench( - 'ssr server-route middleware (vue)', - () => runServerRouteMiddlewareLoop(handler), - serverRouteMiddlewareBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-route middleware (vue)', async () => + runServerRouteMiddlewareLoop(handler), + ).run(serverRouteMiddlewareBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/server-routes-middleware/vue/vite.config.ts b/benchmarks/ssr/scenarios/server-routes-middleware/vue/vite.config.ts index a1b26182f7..909b7cca50 100644 --- a/benchmarks/ssr/scenarios/server-routes-middleware/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-routes-middleware/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-routes-middleware (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/server-routes/react/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes/react/speed.bench.ts index 1bdb7946b2..631314148a 100644 --- a/benchmarks/ssr/scenarios/server-routes/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-routes/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerRouteResponse, runServerRouteLoop, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertServerRouteResponse(handler) -describe('ssr', () => { - bench( - 'ssr server-route (react)', - () => runServerRouteLoop(handler), - serverRouteBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-route (react)', async () => + runServerRouteLoop(handler), + ).run(serverRouteBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/server-routes/react/vite.config.ts b/benchmarks/ssr/scenarios/server-routes/react/vite.config.ts index fdc16bf50c..2c723c749c 100644 --- a/benchmarks/ssr/scenarios/server-routes/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-routes/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-routes (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/server-routes/shared.ts b/benchmarks/ssr/scenarios/server-routes/shared.ts index 20f67ea296..ce33faaefe 100644 --- a/benchmarks/ssr/scenarios/server-routes/shared.ts +++ b/benchmarks/ssr/scenarios/server-routes/shared.ts @@ -4,7 +4,7 @@ import type { StartRequestHandler } from '../../bench-utils' export type { StartRequestHandler } const benchmarkSeed = 0xdecafbad -const loopIterations = 200 +const loopTotalRequests = 208 const apiRequestInit = { method: 'GET', @@ -22,7 +22,8 @@ export const serverRouteBenchOptions = { export function runServerRouteLoop(handler: StartRequestHandler) { return runRequestLoop(handler, { seed: benchmarkSeed, - iterations: loopIterations, + concurrency: 16, + totalRequests: loopTotalRequests, buildRequest: (random) => new Request( `http://localhost/api/users/${randomSegment(random)}`, diff --git a/benchmarks/ssr/scenarios/server-routes/solid/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes/solid/speed.bench.ts index ce3e1f8a21..4788d31854 100644 --- a/benchmarks/ssr/scenarios/server-routes/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-routes/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerRouteResponse, runServerRouteLoop, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertServerRouteResponse(handler) -describe('ssr', () => { - bench( - 'ssr server-route (solid)', - () => runServerRouteLoop(handler), - serverRouteBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-route (solid)', async () => + runServerRouteLoop(handler), + ).run(serverRouteBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/server-routes/solid/vite.config.ts b/benchmarks/ssr/scenarios/server-routes/solid/vite.config.ts index 24e502a63a..994e04f1d6 100644 --- a/benchmarks/ssr/scenarios/server-routes/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-routes/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-routes (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/server-routes/vue/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes/vue/speed.bench.ts index f2b9e27acb..09c0bbe90b 100644 --- a/benchmarks/ssr/scenarios/server-routes/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-routes/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertServerRouteResponse, runServerRouteLoop, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertServerRouteResponse(handler) -describe('ssr', () => { - bench( - 'ssr server-route (vue)', - () => runServerRouteLoop(handler), - serverRouteBenchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr server-route (vue)', async () => + runServerRouteLoop(handler), + ).run(serverRouteBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/server-routes/vue/vite.config.ts b/benchmarks/ssr/scenarios/server-routes/vue/vite.config.ts index c56f3c872a..0457453532 100644 --- a/benchmarks/ssr/scenarios/server-routes/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/server-routes/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr server-routes (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts b/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts index c1dbf38ae5..eb4c9dc1d6 100644 --- a/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertStreamingSanity, benchOptions, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertStreamingSanity(handler) -describe('ssr', () => { - bench( - 'ssr streaming deferred (react)', - () => runStreamingLoop(handler), - benchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr streaming deferred (react)', async () => + runStreamingLoop(handler), + ).run(benchOptions) }) diff --git a/benchmarks/ssr/scenarios/streaming/react/vite.config.ts b/benchmarks/ssr/scenarios/streaming/react/vite.config.ts index bdbfebdfce..e1cc5f534b 100644 --- a/benchmarks/ssr/scenarios/streaming/react/vite.config.ts +++ b/benchmarks/ssr/scenarios/streaming/react/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/react-start/plugin/vite' import react from '@vitejs/plugin-react' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr streaming (react)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/streaming/shared-bench.ts b/benchmarks/ssr/scenarios/streaming/shared-bench.ts index 25685b3c78..cc45062e1b 100644 --- a/benchmarks/ssr/scenarios/streaming/shared-bench.ts +++ b/benchmarks/ssr/scenarios/streaming/shared-bench.ts @@ -71,6 +71,8 @@ export const benchOptions = { export function runStreamingLoop(handler: StartRequestHandler) { return runRequestLoop(handler, { seed: benchmarkSeed, + concurrency: 16, + totalRequests: 16, buildRequest: buildStreamingRequest, }) } diff --git a/benchmarks/ssr/scenarios/streaming/shared-data.ts b/benchmarks/ssr/scenarios/streaming/shared-data.ts index 550a351794..695ed107c6 100644 --- a/benchmarks/ssr/scenarios/streaming/shared-data.ts +++ b/benchmarks/ssr/scenarios/streaming/shared-data.ts @@ -15,7 +15,11 @@ export const streamChunkCount = 96 export const streamChunkLength = 192 export function sleep0() { - return new Promise((resolve) => setTimeout(resolve, 1)) + // Give SSR a render turn before resolving deferred values. Counted turns + // avoid grouping concurrent requests by wall-clock timer expiration. + return new Promise((resolve) => { + setImmediate(() => setImmediate(resolve)) + }) } function hashId(id: string) { diff --git a/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts b/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts index 0828715220..19d5817d32 100644 --- a/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertStreamingSanity, benchOptions, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertStreamingSanity(handler) -describe('ssr', () => { - bench( - 'ssr streaming deferred (solid)', - () => runStreamingLoop(handler), - benchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr streaming deferred (solid)', async () => + runStreamingLoop(handler), + ).run(benchOptions) }) diff --git a/benchmarks/ssr/scenarios/streaming/solid/vite.config.ts b/benchmarks/ssr/scenarios/streaming/solid/vite.config.ts index 5b736899c0..353c21f552 100644 --- a/benchmarks/ssr/scenarios/streaming/solid/vite.config.ts +++ b/benchmarks/ssr/scenarios/streaming/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr streaming (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts b/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts index a484f95d6a..42473fc694 100644 --- a/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { assertStreamingSanity, benchOptions, @@ -16,10 +16,8 @@ const { default: handler } = (await import( await assertStreamingSanity(handler) -describe('ssr', () => { - bench( - 'ssr streaming deferred (vue)', - () => runStreamingLoop(handler), - benchOptions, - ) +test('ssr', async ({ bench }) => { + await bench('ssr streaming deferred (vue)', async () => + runStreamingLoop(handler), + ).run(benchOptions) }) diff --git a/benchmarks/ssr/scenarios/streaming/vue/vite.config.ts b/benchmarks/ssr/scenarios/streaming/vue/vite.config.ts index 8c65f71268..a09a30076f 100644 --- a/benchmarks/ssr/scenarios/streaming/vue/vite.config.ts +++ b/benchmarks/ssr/scenarios/streaming/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr streaming (vue)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/solid/speed.bench.ts b/benchmarks/ssr/solid/speed.bench.ts index 0c4317415d..2f72977612 100644 --- a/benchmarks/ssr/solid/speed.bench.ts +++ b/benchmarks/ssr/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { runSsrRequestLoop } from '../bench-utils' import type { StartRequestHandler } from '../bench-utils' @@ -11,14 +11,12 @@ const { default: handler } = (await import( default: StartRequestHandler } -describe('ssr', () => { - bench( - 'ssr request loop (solid)', - () => runSsrRequestLoop(handler, { seed: benchmarkSeed }), - { - warmupIterations: 100, - time: 10_000, - throws: true, - }, - ) +test('ssr', async ({ bench }) => { + await bench('ssr request loop (solid)', async () => + runSsrRequestLoop(handler, { seed: benchmarkSeed }), + ).run({ + warmupIterations: 100, + time: 10_000, + throws: true, + }) }) diff --git a/benchmarks/ssr/solid/vite.config.ts b/benchmarks/ssr/solid/vite.config.ts index dc9cbf90e3..dfd82d9192 100644 --- a/benchmarks/ssr/solid/vite.config.ts +++ b/benchmarks/ssr/solid/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/solid-start/plugin/vite' import solid from 'vite-plugin-solid' +import { cpuSimulationExecArgv } from '../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr (solid)', watch: false, environment: 'node', diff --git a/benchmarks/ssr/tsconfig.json b/benchmarks/ssr/tsconfig.json index e3ed3ad08a..7279177023 100644 --- a/benchmarks/ssr/tsconfig.json +++ b/benchmarks/ssr/tsconfig.json @@ -3,5 +3,10 @@ "compilerOptions": { "types": ["node", "vite/client", "vitest/globals"] }, - "include": ["bench-utils.ts"] + "include": [ + "bench-utils.ts", + "bench-utils.test.ts", + "scenarios/streaming/shared-data.ts", + "vitest.unit.config.ts" + ] } diff --git a/benchmarks/ssr/vitest.unit.config.ts b/benchmarks/ssr/vitest.unit.config.ts new file mode 100644 index 0000000000..cbba6db9ef --- /dev/null +++ b/benchmarks/ssr/vitest.unit.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + name: '@benchmarks/ssr unit', + environment: 'node', + include: ['bench-utils.test.ts'], + }, +}) diff --git a/benchmarks/ssr/vue/speed.bench.ts b/benchmarks/ssr/vue/speed.bench.ts index 849f042e3c..57b59e0504 100644 --- a/benchmarks/ssr/vue/speed.bench.ts +++ b/benchmarks/ssr/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { bench, describe } from 'vitest' +import { test } from 'vitest' import { runSsrRequestLoop } from '../bench-utils' import type { StartRequestHandler } from '../bench-utils' @@ -11,14 +11,12 @@ const { default: handler } = (await import( default: StartRequestHandler } -describe('ssr', () => { - bench( - 'ssr request loop (vue)', - () => runSsrRequestLoop(handler, { seed: benchmarkSeed }), - { - warmupIterations: 100, - time: 10_000, - throws: true, - }, - ) +test('ssr', async ({ bench }) => { + await bench('ssr request loop (vue)', async () => + runSsrRequestLoop(handler, { seed: benchmarkSeed }), + ).run({ + warmupIterations: 100, + time: 10_000, + throws: true, + }) }) diff --git a/benchmarks/ssr/vue/vite.config.ts b/benchmarks/ssr/vue/vite.config.ts index 312f43a7ae..b2b9fc8a09 100644 --- a/benchmarks/ssr/vue/vite.config.ts +++ b/benchmarks/ssr/vue/vite.config.ts @@ -3,6 +3,7 @@ import { defineConfig } from 'vitest/config' import codspeedPlugin from '@codspeed/vitest-plugin' import { tanstackStart } from '@tanstack/vue-start/plugin/vite' import vueJsx from '@vitejs/plugin-vue-jsx' +import { cpuSimulationExecArgv } from '../../cpu-simulation' const rootDir = fileURLToPath(new URL('.', import.meta.url)) @@ -22,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + execArgv: cpuSimulationExecArgv(), + isolate: true, name: '@benchmarks/ssr (vue)', watch: false, environment: 'node', diff --git a/benchmarks/tsconfig.json b/benchmarks/tsconfig.json new file mode 100644 index 0000000000..5e9ff9a8e1 --- /dev/null +++ b/benchmarks/tsconfig.json @@ -0,0 +1,7 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "types": ["node"] + }, + "include": ["cpu-simulation.ts"] +} diff --git a/docs/AGENTS.md b/docs/AGENTS.md new file mode 100644 index 0000000000..ab2d4117e2 --- /dev/null +++ b/docs/AGENTS.md @@ -0,0 +1,4 @@ +# Documentation + +- Register new published pages in `router/config.json` or `start/config.json`; drafts need not be registered. +- Run `pnpm test:docs` from the repository root for Markdown link validation. It checks `docs/**/*.md`, not Markdown elsewhere. Relative links resolve from the containing file. diff --git a/docs/router/api/file-based-routing.md b/docs/router/api/file-based-routing.md index ad3e07fad7..7c94d484d1 100644 --- a/docs/router/api/file-based-routing.md +++ b/docs/router/api/file-based-routing.md @@ -188,7 +188,7 @@ By default, this value is set to `false`. ### `autoCodeSplitting` -This feature is only available if you are using the TanStack Router Bundler Plugin. +This feature is only available if you are using the TanStack Router Bundler Plugin with Vite, Rspack/Rsbuild or Webpack. With Esbuild, setting it to `true` is an error. This option is used to enable automatic code-splitting for non-critical route configuration items. See the "Automatic Code-Splitting" guide for more information. diff --git a/docs/router/api/router/LinkOptionsType.md b/docs/router/api/router/LinkOptionsType.md index 481a5b4a3d..9d3d3fe8d8 100644 --- a/docs/router/api/router/LinkOptionsType.md +++ b/docs/router/api/router/LinkOptionsType.md @@ -9,7 +9,7 @@ The `LinkOptions` type extends the [`NavigateOptions`](./NavigateOptionsType.md) type LinkOptions = NavigateOptions & { target?: HTMLAnchorElement['target'] activeOptions?: ActiveOptions - preload?: false | 'intent' + preload?: false | 'intent' | 'viewport' | 'render' preloadDelay?: number disabled?: boolean } @@ -42,7 +42,7 @@ The `LinkOptions` object accepts/contains the following properties: - Type: `number` - Optional -- Delay intent preloading by this many milliseconds. If the intent exits before this delay, the preload will be cancelled. +- Delay focus, hover, and viewport preloading by this many milliseconds. Touch intent preloads immediately. If focus or hover ends, or the link leaves the viewport before the delay, the preload will be cancelled. ### `disabled` diff --git a/docs/router/api/router/RouteMatchType.md b/docs/router/api/router/RouteMatchType.md index 251c2c031e..b5009ebe68 100644 --- a/docs/router/api/router/RouteMatchType.md +++ b/docs/router/api/router/RouteMatchType.md @@ -11,9 +11,8 @@ interface RouteMatch { routeId: string pathname: string params: Route['allParams'] - status: 'pending' | 'success' | 'error' | 'redirected' | 'notFound' + status: 'pending' | 'success' | 'error' | 'notFound' isFetching: false | 'beforeLoad' | 'loader' - showPending: boolean error: unknown paramsError: unknown searchError: unknown @@ -21,9 +20,17 @@ interface RouteMatch { loaderData?: Route['loaderData'] context: Route['allContext'] search: Route['fullSearchSchema'] - fetchedAt: number abortController: AbortController - cause: 'enter' | 'stay' + cause: 'preload' | 'enter' | 'stay' ssr?: boolean | 'data-only' } ``` + +`status` describes the match's render state. `isFetching` independently exposes +active `beforeLoad` or loader work. In particular, a successful match can report +`isFetching: 'loader'` while stale data remains visible during a background +reload. + +The router state can contain matches below the pending, error, or not-found +boundary. Those matches remain observable as part of the structurally matched +lane even though the route renderer stops at the boundary. diff --git a/docs/router/api/router/RouteOptionsType.md b/docs/router/api/router/RouteOptionsType.md index 1fb4c4eb30..2adfc6e5c6 100644 --- a/docs/router/api/router/RouteOptionsType.md +++ b/docs/router/api/router/RouteOptionsType.md @@ -56,6 +56,7 @@ The `RouteOptions` type accepts an object with the following properties: - Type: `(rawSearchParams: unknown) => TSearchSchema` - Optional - A function that will be called when this route is matched and passed the raw search params from the current location and return valid parsed search params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's search params and the return type will be inferred into the rest of the router. +- This is a planning callback. It must be deterministic and side-effect-free for the same input; do not navigate or mutate application/router state from it. - Optionally, the parameter type can be tagged with the `SearchSchemaInput` type like this: `(searchParams: TSearchSchemaInput & SearchSchemaInput) => TSearchSchema`. If this tag is present, `TSearchSchemaInput` will be used to type the `search` property of `` and `navigate()` **instead of** `TSearchSchema`. The difference between `TSearchSchemaInput` and `TSearchSchema` can be useful, for example, to express optional search parameters. ### `search.middlewares` property @@ -70,6 +71,7 @@ The `RouteOptions` type accepts an object with the following properties: - Type: `(rawParams: Record) => TParams` - Optional - A function that will be called when this route is matched and passed the raw params from the current location and return valid parsed params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's params and the return type will be inferred into the rest of the router. +- This is a planning callback. It must be deterministic and side-effect-free for the same input. ### `stringifyParams` method (⚠️ deprecated, use `params.stringify` instead) @@ -82,6 +84,7 @@ The `RouteOptions` type accepts an object with the following properties: - Type: `(rawParams: Record) => TParams | false` - Optional - A function that will be called when this route is matched and passed the raw params from the current location and return valid parsed params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function returns parsed params, its return value will be used as the route's params and the return type will be inferred into the rest of the router. +- This is a planning callback. It must be deterministic and side-effect-free for the same input. - Experimental: returning `false` during incoming route matching skips this route and allows matching to continue to another candidate route. ### `params.priority` property @@ -112,14 +115,14 @@ type beforeLoad = ( location: ParsedLocation navigate: NavigateFn // @deprecated buildLocation: BuildLocationFn - cause: 'enter' | 'stay' + cause: 'preload' | 'enter' | 'stay' }, ) => Promise | TRouteContext | void ``` - Optional - [`ParsedLocation`](./ParsedLocationType.md) -- This async function is called before a route is loaded. If an error is thrown here, the route's loader will not be called and the route will not render. If thrown during a navigation, the navigation will be canceled and the error will be passed to the `onError` function. If thrown during a preload event, the error will be logged to the console and the preload will fail. +- This async function is called before a route is loaded. If it fails, the route's loader and its descendants will not run. During navigation, ordinary errors become the match's error state and are passed to the `onError` function. During a preload, ordinary errors and not-found results are represented in the returned speculative match lane instead of rejecting the `preloadRoute` promise. - If this function returns a promise, the route will be put into a pending state and cause rendering to suspend until the promise resolves. If this route's pendingMs threshold is reached, the `pendingComponent` will be shown until it resolves. If the promise rejects, the route will be put into an error state and the error will be thrown during render. - If this function returns a `TRouteContext` object, that object will be merged into the route's context and be made available in the `loader` and other related route components/methods. - It's common to use this function to check if a user is authenticated and redirect them to a login page if they are not. To do this, you can either return or throw a `redirect` object from this function. @@ -156,9 +159,9 @@ type loader = - Optional - [`ParsedLocation`](./ParsedLocationType.md) -- This async function is called when a route is matched and passed the route's match object. If an error is thrown here, the route will be put into an error state and the error will be thrown during render. If thrown during a navigation, the navigation will be canceled and the error will be passed to the `onError` function. If thrown during a preload event, the error will be logged to the console and the preload will fail. +- This async function is called when a route is matched and passed the route's match object. During navigation, ordinary errors become the match's error state and are passed to the `onError` function. During a preload, ordinary errors and not-found results are represented in the returned speculative match lane instead of rejecting the `preloadRoute` promise. - If this function returns a promise, the route will be put into a pending state and cause rendering to suspend until the promise resolves. If this route's pendingMs threshold is reached, the `pendingComponent` will be shown until it resolves. If the promise rejects, the route will be put into an error state and the error will be thrown during render. -- If this function returns a `TLoaderData` object, that object will be stored on the route match until the route match is no longer active. It can be accessed using the `useLoaderData` hook in any component that is a child of the route match before another `` is rendered. +- If this function returns a `TLoaderData` object, that object will be stored on the route match and can remain available in the in-memory cache after the match becomes inactive. Navigation-owned data uses `gcTime` for retention, while preload-owned data uses `preloadGcTime`. It can be accessed using the `useLoaderData` hook in any component that is a child of the route match before another `` is rendered. - Deps must be returned by your `loaderDeps` function in order to appear. - Use the object form to configure loader-specific behavior like `staleReloadMode`. - `staleReloadMode: 'background'` preserves stale-while-revalidate behavior for stale successful matches. @@ -176,6 +179,7 @@ type loaderDeps = (opts: { search: TFullSearchSchema }) => Record - Optional - A function that will be called before this route is matched to provide additional unique identification to the route match and serve as a dependency tracker for when the match should be reloaded. It should return any serializable value that can uniquely identify the route match from navigation to navigation. +- This is a planning callback and cache-key function. It must be deterministic and side-effect-free for the same validated search input. The returned value and any serialization methods on it, such as `toJSON`, must also be side-effect-free. - By default, path params are already used to uniquely identify a route match, so it's unnecessary to return these here. - If your route match relies on search params for unique identification, it's required that you return them here so they can be made available in the `loader`'s `deps` argument. @@ -186,19 +190,26 @@ type loaderDeps = (opts: { search: TFullSearchSchema }) => Record - Defaults to `routerOptions.defaultStaleTime`, which defaults to `0` - The amount of time in milliseconds that a route match's loader data will be considered fresh. If a route match is matched again within this time frame, its loader data will not be reloaded. +### `preload` property + +- Type: `boolean` +- Optional +- Defaults to `true` +- If `false`, speculative preloads still run this route's `beforeLoad` function but skip its `loader`. A navigation runs both `beforeLoad` and the skipped `loader` normally. + ### `preloadStaleTime` property - Type: `number` - Optional - Defaults to `routerOptions.defaultPreloadStaleTime`, which defaults to `30_000` ms (30 seconds) -- The amount of time in milliseconds that a route match's loader data will be considered fresh when preloading. If a route match is preloaded again within this time frame, its loader data will not be reloaded. If a route match is loaded (for navigation) within this time frame, the normal `staleTime` is used instead. +- The amount of time in milliseconds that loader data produced by a preload is considered fresh. Another preload or the first navigation can reuse it within this interval. After navigation accepts the generation, subsequent freshness uses `staleTime`. ### `gcTime` property - Type: `number` - Optional -- Defaults to `routerOptions.defaultGcTime`, which defaults to 30 minutes. -- The amount of time in milliseconds that a route match's loader data will be kept in memory after a preload or it is no longer in use. +- Defaults to `routerOptions.defaultGcTime`, which defaults to 5 minutes. +- The retention window in milliseconds for unused loader data from an ordinary load. Once the data is older than this value, it is eligible for pruning during a later cache reconciliation. ### `shouldReload` property @@ -234,12 +245,12 @@ type loaderDeps = (opts: { search: TFullSearchSchema }) => Record - Defaults to `routerOptions.defaultPendingMinMs` which defaults to `500` - The minimum amount of time in milliseconds that the pending component will be shown for if it is shown. This is useful to prevent the pending component from flashing on the screen for a split second. -### `preloadMaxAge` property +### `preloadGcTime` property - Type: `number` - Optional -- Defaults to `30_000` ms (30 seconds) -- The maximum amount of time in milliseconds that a route's preloaded route data will be cached for. If a route is not matched within this time frame, its loader data will be discarded. +- Defaults to `routerOptions.defaultPreloadGcTime`, which defaults to 5 minutes. +- The retention window in milliseconds for unused loader data produced by a preload. Once the data is older than this value, it is eligible for pruning during a later cache reconciliation. Use `preloadStaleTime` to control whether retained data is fresh enough to reuse without reloading. ### `preSearchFilters` property (⚠️ deprecated, use `search.middlewares` instead) @@ -262,29 +273,33 @@ type loaderDeps = (opts: { search: TFullSearchSchema }) => Record - Type: `(error: any) => void` - Optional - A function that will be called when an error is thrown during a navigation or preload event. -- If this function throws a [`redirect`](./redirectFunction.md), then the router will process and apply the redirect immediately. +- If this function throws a [`redirect`](./redirectFunction.md), the redirect replaces the original error and becomes control flow for the current navigation or preload operation. If it throws a not-found result, that result replaces the original error in the current match lane. ### `onEnter` property - Type: `(match: RouteMatch) => void` - Optional - A function that will be called when a route is matched and loaded after not being matched in the previous location. +- Routes below an error or not-found boundary do not enter the active route lifecycle. The boundary itself remains active. A previously hidden route receives `onEnter` when a navigation makes it active again. ### `onStay` property - Type: `(match: RouteMatch) => void` - Optional - A function that will be called when a route is matched and loaded after being matched in the previous location. +- Both navigations must include the route in the active branch, through the first error or not-found boundary. ### `onLeave` property - Type: `(match: RouteMatch) => void` - Optional - A function that will be called when a route is no longer matched after being matched in the previous location. +- This also runs when a navigation hides a previously active route below an error or not-found boundary, even if the route remains structurally matched. +- Background reloads update route data without dispatching these lifecycle callbacks. ### `onCatch` property -- Type: `(error: Error, errorInfo: ErrorInfo) => void` +- Type: `(error: unknown) => void` in React and Vue; `(error: Error) => void` in Solid - Optional - Defaults to `routerOptions.defaultOnCatch` - A function that will be called when errors are caught when the route encounters an error. diff --git a/docs/router/api/router/RouterEventsType.md b/docs/router/api/router/RouterEventsType.md index c79bb47f81..c27887fba1 100644 --- a/docs/router/api/router/RouterEventsType.md +++ b/docs/router/api/router/RouterEventsType.md @@ -47,9 +47,6 @@ type RouterEvents = { hrefChanged: boolean hashChanged: boolean } - onInjectedHtml: { - type: 'onInjectedHtml' - } onRendered: { type: 'onRendered' fromLocation?: ParsedLocation @@ -67,7 +64,7 @@ Once an event is emitted, the following properties will be present on the event ### `type` property -- Type: `onBeforeNavigate | onBeforeLoad | onLoad | onBeforeRouteMount | onResolved | onRendered | onInjectedHtml` +- Type: `onBeforeNavigate | onBeforeLoad | onLoad | onBeforeRouteMount | onResolved | onRendered` - The type of the event - This is useful for discriminating between events in a listener function. diff --git a/docs/router/api/router/RouterOptionsType.md b/docs/router/api/router/RouterOptionsType.md index 7127e1191e..31f410b208 100644 --- a/docs/router/api/router/RouterOptionsType.md +++ b/docs/router/api/router/RouterOptionsType.md @@ -59,7 +59,7 @@ The `RouterOptions` type accepts an object with the following properties and met - Type: `number` - Optional - Defaults to `50` -- The delay in milliseconds that a route must be hovered over or touched before it is preloaded. +- The delay in milliseconds before intent focus/hover and viewport preloading. Touch intent preloads immediately. ### `defaultComponent` property @@ -129,19 +129,19 @@ The `RouterOptions` type accepts an object with the following properties and met - Type: `number` - Optional -- Defaults to `routerOptions.defaultGcTime`, which defaults to 30 minutes. +- Defaults to 5 minutes. - The default `preloadGcTime` a route should use if no preloadGcTime is provided. ### `defaultGcTime` property - Type: `number` - Optional -- Defaults to 30 minutes. +- Defaults to 5 minutes. - The default `gcTime` a route should use if no gcTime is provided. ### `defaultOnCatch` property -- Type: `(error: Error, errorInfo: ErrorInfo) => void` +- Type: `(error: unknown, errorInfo: ErrorInfo) => void` - Optional - The default `onCatch` handler for errors caught by the Router ErrorBoundary @@ -223,6 +223,13 @@ const router = createRouter({ - Defaults to `/` - The basepath for the entire router. This is useful for mounting a router instance at a subpath. +### `origin` property + +- Type: `string` +- Optional +- The origin used to resolve URLs. Defaults to the browser origin, or `http://localhost` on the server and in browsers with an opaque origin. +- Pass a normalized origin, such as `https://example.com` or `http://localhost:3000`, without a path or trailing slash. The router uses this value as provided; if you have a full URL, normalize it with `new URL(url).origin` before passing it to the router. + ### `rewrite` property - Type: `LocationRewrite` @@ -368,9 +375,10 @@ const router = createRouter({ ### `pathParamsAllowedCharacters` property -- Type: `Array<';' | ':' | '@' | '&' | '=' | '+' | '$' | ','>` +- Type: `ReadonlyArray<';' | ':' | '@' | '&' | '=' | '+' | '$' | ','>` - Optional - Configures which URI characters are allowed in path params that would ordinarily be escaped by encodeURIComponent. +- Read only when the router is created. To change these characters, create a new router instance. Router option updates and provider props do not change this setting. ### `defaultStructuralSharing` property diff --git a/docs/router/api/router/RouterStateType.md b/docs/router/api/router/RouterStateType.md index a77f4e775f..4da9cd9bb6 100644 --- a/docs/router/api/router/RouterStateType.md +++ b/docs/router/api/router/RouterStateType.md @@ -3,16 +3,17 @@ id: RouterStateType title: RouterState type --- -The `RouterState` type represents shape of the internal state of the router. The Router's internal state is useful, if you need to access certain internals of the router, such as any pending matches, is the router in its loading state, etc. +The `RouterState` type represents the observable state of the router, including +the requested and resolved locations, match presentation, and foreground loading +status. ```tsx type RouterState = { status: 'pending' | 'idle' isLoading: boolean - isTransitioning: boolean matches: Array location: ParsedLocation - resolvedLocation: ParsedLocation + resolvedLocation?: ParsedLocation } ``` @@ -23,22 +24,24 @@ The `RouterState` type contains all of the properties that are available on the ### `status` property - Type: `'pending' | 'idle'` -- The current status of the router. If the router is pending, it means that it is currently loading a route or the router is still transitioning to the new route. +- The current foreground status of the router. `pending` means the requested route is still loading or waiting for its framework transition to settle. ### `isLoading` property - Type: `boolean` -- `true` if the router is currently loading a route or waiting for a route to finish loading. - -### `isTransitioning` property - -- Type: `boolean` -- `true` if the router is currently transitioning to a new route. +- `true` when `status` is `pending`. +- Background loader refreshes do not change this value. Inspect each match's `isFetching` field to observe foreground `beforeLoad`/loader work and background loader work. ### `matches` property - Type: [`Array`](./RouteMatchType.md) -- An array of all of the route matches that have been resolved and are currently active. +- The match presentation currently exposed to the application. +- A navigation can keep the previous presentation visible until pending UI is + published. Once the destination is presented, this contains its complete + structurally matched lane, including descendants that are still loading. +- Error and not-found results also preserve the complete structurally matched + lane. Rendering stops at the selected pending or terminal boundary; it does + not truncate this array. ### `location` property @@ -47,5 +50,5 @@ The `RouterState` type contains all of the properties that are available on the ### `resolvedLocation` property -- Type: [`ParsedLocation`](./ParsedLocationType.md) -- The location that the router has resolved and loaded. +- Type: [`ParsedLocation`](./ParsedLocationType.md) | `undefined` +- The location whose load and framework transition have settled. It is `undefined` before the initial location resolves. diff --git a/docs/router/api/router/RouterType.md b/docs/router/api/router/RouterType.md index 757a6098ca..3fde90e32e 100644 --- a/docs/router/api/router/RouterType.md +++ b/docs/router/api/router/RouterType.md @@ -11,8 +11,9 @@ An instance of the `Router` has the following properties and methods: ### `.update` method -- Type: `(newOptions: RouterOptions) => void` +- Type: `(newOptions: Omit) => void` - Updates the router instance with new options. +- Initialization-only options such as `pathParamsAllowedCharacters` cannot be updated. Create a new router instance to change them. ### `state` property @@ -35,16 +36,6 @@ An instance of the `Router` has the following properties and methods: - Matches a pathname and search params against the router's route tree and returns an array of route matches. - If `opts.throwOnError` is `true`, any errors that occur during the matching process will be thrown (in addition to being returned in the route match's `error` property). -### `.cancelMatch` method - -- Type: `(matchId: string) => void` -- Cancels a route match that is currently pending by calling `match.abortController.abort()`. - -### `.cancelMatches` method - -- Type: `() => void` -- Cancels all route matches that are currently pending by calling `match.abortController.abort()` on each one. - ### `.buildLocation` method Builds a new parsed location object that can be used later to navigate to a new location. @@ -138,23 +129,27 @@ Navigates to a new location. ### `.invalidate` method -Invalidates route matches by forcing their `beforeLoad` and `load` functions to be called again. +Invalidates selected route-match generations, reruns their loading lifecycle, +reruns `beforeLoad`, and reloads their loaders through the normal loading +protocol. - Type: `(opts?: {filter?: (d: MakeRouteMatchUnion) => boolean, sync?: boolean, forcePending?: boolean }) => Promise` - This is useful any time your loader data might be out of date or stale. For example, if you have a route that displays a list of posts, and you have a loader function that fetches the list of posts from an API, you might want to invalidate the route matches for that route any time a new post is created so that the list of posts is always up-to-date. -- if `filter` is not supplied, all matches will be invalidated -- if `filter` is supplied, only matches for which `filter` returns `true` will be invalidated. -- if `sync` is true, the promise returned by this function will only resolve once all loaders have finished. -- if `forcePending` is true, the invalidated matches will be put into `'pending'` state regardless whether they are in `'error'` state or not. +- If `filter` is not supplied, all committed, cached, and in-flight match generations are invalidated. +- If `filter` is supplied, it is evaluated against committed, cached, and in-flight matches. Selecting one generation invalidates every committed, cached, or in-flight generation with the same match ID. +- Invalidation reruns `beforeLoad`; reusable loader data is marked stale and reloads through the normal loading protocol. Route-level `context` remains reusable while the match ID is unchanged. +- If `sync` is `true`, stale loader work is blocking and the returned promise resolves after it finishes instead of leaving a background refresh detached. +- If `forcePending` is `true`, selected routes that need loading enter the normal pending protocol even when successful data was already available. - You might also want to invalidate the Router if you imperatively `reset` the router's `CatchBoundary` to trigger loaders again. ### `.clearCache` method -Remove cached route matches. +Remove cached route matches and matching active preloads. - Type: `(opts?: {filter?: (d: MakeRouteMatchUnion) => boolean}) => void` -- if `filter` is not supplied, all cached matches will be removed -- if `filter` is supplied, only matches for which `filter` returns `true` will be removed. +- If `filter` is not supplied, all cached matches and active preload lanes are removed. +- If `filter` is supplied, matching cached matches are removed. An active preload lane is canceled when any match in that lane passes the filter. +- Current committed and presented matches are not removed. ### `.load` method @@ -170,16 +165,28 @@ Loads all of the currently matched route matches and resolves when they are all Preloads all of the matches that match the provided `NavigateOptions`. -> ⚠️⚠️⚠️ **Preloaded route matches are not stored long-term in the router state. They are only stored until the next attempted navigation action.** +An active preload is speculative and is not published as the current match +presentation. Successful loader data can enter the normal in-memory route +cache. Its freshness follows `preloadStaleTime`; once unused and older than +`preloadGcTime`, it is eligible for pruning during a later cache +reconciliation. -- Type: `(opts?: NavigateOptions) => Promise` +Every preload and navigation runs its own `beforeLoad` chain. A later lane can +reuse successful settled loader data or join loader work that is still in +flight, but it never reuses `beforeLoad` context or an already-settled +redirect, error, or not-found result. If joined loader work later produces a +terminal outcome, all current consumers of that flight observe it. + +- Type: `(opts: NavigateOptions) => Promise` - Properties - `opts` - Type: `NavigateOptions` - - Optional, defaults to the current location. + - Required. - The options that will be used to determine which route matches to preload. - Returns - - A promise that resolves with an array of all of the route matches that were preloaded. + - A promise that resolves with the speculative route-match lane. An ordinary error or not-found is represented by a terminal match array rather than a rejected promise. + - It resolves with `undefined` when cancellation or control flow does not produce a reusable lane. + - The method is also available on server router instances. It remains speculative and does not change the request's current location or presented matches. ### `.loadRouteChunk` method diff --git a/docs/router/api/router/catchBoundaryComponent.md b/docs/router/api/router/catchBoundaryComponent.md index deef0ffa22..aa2f6eb7ce 100644 --- a/docs/router/api/router/catchBoundaryComponent.md +++ b/docs/router/api/router/catchBoundaryComponent.md @@ -29,7 +29,7 @@ The `CatchBoundary` component accepts the following props: ### `props.onCatch` prop -- Type: `(error: any) => void` +- Type: `(error: unknown, errorInfo: ErrorInfo) => void` in React; `(error: unknown) => void` in Vue; `(error: Error) => void` in Solid - Optional - A callback that will be called with the error that was thrown by the component's children. diff --git a/docs/router/api/router/errorComponentComponent.md b/docs/router/api/router/errorComponentComponent.md index 04399f124d..07d7187580 100644 --- a/docs/router/api/router/errorComponentComponent.md +++ b/docs/router/api/router/errorComponentComponent.md @@ -3,7 +3,7 @@ id: errorComponentComponent title: ErrorComponent component --- -The `ErrorComponent` component is a component that renders an error message and optionally the error's message. +The `ErrorComponent` component renders an error notice and optional details about the thrown value. ## ErrorComponent props @@ -11,8 +11,8 @@ The `ErrorComponent` component accepts the following props: ### `props.error` prop -- Type: `TError` (defaults to `Error`) -- The error that was thrown by the component's children +- Type: `unknown` in React and Vue; `Error` in Solid +- The caught error. Solid normalizes non-`Error` values, including SSR loader errors, into an `Error` with the original value in `cause`. ### `props.info` prop @@ -27,6 +27,6 @@ The `ErrorComponent` component accepts the following props: ## ErrorComponent returns -- Returns a formatted error message with the error's message if it exists. +- Displays an error notice, with details when the thrown value has a nonempty `message`. Values without a message still display the error notice. - The error message can be toggled by clicking the "Show Error" button. - By default, the error message will be shown in development. diff --git a/docs/router/api/router/linkComponent.md b/docs/router/api/router/linkComponent.md index a8227913b5..478271a208 100644 --- a/docs/router/api/router/linkComponent.md +++ b/docs/router/api/router/linkComponent.md @@ -43,7 +43,7 @@ By default, param values with characters such as `@` will be encoded in the URL: ``` -To opt-out, update the [pathParamsAllowedCharacters](../router/RouterOptionsType#pathparamsallowedcharacters-property) config on the router +To opt out, set [pathParamsAllowedCharacters](../router/RouterOptionsType#pathparamsallowedcharacters-property) when creating the router. This setting cannot be changed on an existing router instance. ```tsx import { createRouter } from '@tanstack/react-router' diff --git a/docs/router/api/router/useChildMatchesHook.md b/docs/router/api/router/useChildMatchesHook.md index d6de892192..13212e61e0 100644 --- a/docs/router/api/router/useChildMatchesHook.md +++ b/docs/router/api/router/useChildMatchesHook.md @@ -5,8 +5,9 @@ title: useChildMatches hook The `useChildMatches` hook returns all of the child [`RouteMatch`](./RouteMatchType.md) objects from the closest match down to the leaf-most match. **It does not include the current match, which can be obtained using the `useMatch` hook.** -> [!IMPORTANT] -> If the router has pending matches and they are showing their pending component fallbacks, pending matches are used instead of active matches. +The result is derived from the router's current match presentation. It can +include still-loading descendants and descendants below the current render +boundary. ## useChildMatches options diff --git a/docs/router/api/router/useMatchRouteHook.md b/docs/router/api/router/useMatchRouteHook.md index 01c26d07c6..e67ccb6cbd 100644 --- a/docs/router/api/router/useMatchRouteHook.md +++ b/docs/router/api/router/useMatchRouteHook.md @@ -3,7 +3,9 @@ id: useMatchRouteHook title: useMatchRoute hook --- -The `useMatchRoute` hook is a hook that returns a `matchRoute` function that can be used to match a route against either the current or pending location. +The `useMatchRoute` hook returns a `matchRoute` function that can be used to match a route against either the current or pending location. The hook subscribes the component to changes in the router state used for matching, making it useful when the match result affects what the component renders. + +The `matchRoute` function's identity changes when that router state changes. For an imperative check, such as one performed in an event handler, use [`useRouter`](./useRouterHook.md) and call `router.matchRoute` instead. The router instance is stable, and this avoids subscribing the component to router state that it does not use while rendering. ## useMatchRoute returns @@ -25,6 +27,8 @@ The `matchRoute` function accepts a single argument, an `options` object. ## Examples +Use `useMatchRoute` when the result determines the rendered output: + ```tsx import { useMatchRoute } from '@tanstack/react-router' @@ -33,7 +37,36 @@ function Component() { const matchRoute = useMatchRoute() const params = matchRoute({ to: '/posts/$postId' }) // ^ { postId: '123' } + + return params ? : } +``` + +For a check made at the time of an event, call `router.matchRoute` directly: + +```tsx +import { useRouter } from '@tanstack/react-router' + +function Component() { + const router = useRouter() + + return ( + + ) +} +``` + +Additional matching examples: + +```tsx +import { useMatchRoute } from '@tanstack/react-router' // Current location: /posts/123 function Component() { diff --git a/docs/router/api/router/useMatchesHook.md b/docs/router/api/router/useMatchesHook.md index d7a1be8dc3..e57c6c2c7e 100644 --- a/docs/router/api/router/useMatchesHook.md +++ b/docs/router/api/router/useMatchesHook.md @@ -3,7 +3,7 @@ id: useMatchesHook title: useMatches hook --- -The `useMatches` hook returns all of the [`RouteMatch`](./RouteMatchType.md) objects from the router **regardless of its callers position in the React component tree**. +The `useMatches` hook returns the router's complete presented array of [`RouteMatch`](./RouteMatchType.md) objects **regardless of its caller's position in the component tree**. The array can include still-loading descendants or matches below a pending/error/not-found render boundary. > [!TIP] > If you only want the parent or child matches, then you can use the [`useParentMatches`](./useParentMatchesHook.md) or the [`useChildMatches`](./useChildMatchesHook.md) based on the selection you need. diff --git a/docs/router/api/router/useParentMatchesHook.md b/docs/router/api/router/useParentMatchesHook.md index 7afc5585a6..a0ce985411 100644 --- a/docs/router/api/router/useParentMatchesHook.md +++ b/docs/router/api/router/useParentMatchesHook.md @@ -5,8 +5,9 @@ title: useParentMatches hook The `useParentMatches` hook returns all of the parent [`RouteMatch`](./RouteMatchType.md) objects from the root down to the immediate parent of the current match in context. **It does not include the current match, which can be obtained using the `useMatch` hook.** -> [!IMPORTANT] -> If the router has pending matches and they are showing their pending component fallbacks, pending matches are used instead of active matches. +The result is derived from the router's current match presentation. During a +navigation that may still be the previous presentation; after pending UI is +published it is the destination's complete structurally matched lane. ## useParentMatches options diff --git a/docs/router/config.json b/docs/router/config.json index bb30fabc4a..1258ddd817 100644 --- a/docs/router/config.json +++ b/docs/router/config.json @@ -94,7 +94,7 @@ ] }, { - "label": "Routing", + "label": "Core Routing", "children": [ { "label": "Routing Concepts", @@ -123,6 +123,10 @@ { "label": "File Naming Conventions", "to": "routing/file-naming-conventions" + }, + { + "label": "URL Rewrites", + "to": "guide/url-rewrites" } ], "frameworks": [ @@ -137,31 +141,20 @@ ] }, { - "label": "Guides", + "label": "Navigation & URL State", + "collapsible": true, "children": [ - { - "label": "Code Splitting", - "to": "guide/code-splitting" - }, - { - "label": "Automatic Code Splitting", - "to": "guide/automatic-code-splitting" - }, - { - "label": "Creating a Router", - "to": "guide/creating-a-router" - }, - { - "label": "Outlets", - "to": "guide/outlets" - }, { "label": "Navigation", "to": "guide/navigation" }, { - "label": "Router Events", - "to": "guide/router-events" + "label": "Link Options", + "to": "guide/link-options" + }, + { + "label": "Custom Links", + "to": "guide/custom-link" }, { "label": "Path Params", @@ -172,12 +165,52 @@ "to": "guide/search-params" }, { - "label": "Link Options", - "to": "guide/link-options" + "label": "Custom Search Param Serialization", + "to": "guide/custom-search-param-serialization" }, { - "label": "Custom Links", - "to": "guide/custom-link" + "label": "Route Masking", + "to": "guide/route-masking" + }, + { + "label": "Navigation Blocking", + "to": "guide/navigation-blocking" + }, + { + "label": "History Types", + "to": "guide/history-types" + }, + { + "label": "Scroll Restoration", + "to": "guide/scroll-restoration" + }, + { + "label": "Internationalization", + "to": "guide/internationalization-i18n" + } + ], + "frameworks": [ + { + "label": "react", + "children": [] + }, + { + "label": "solid", + "children": [] + } + ] + }, + { + "label": "Data & Rendering", + "collapsible": true, + "children": [ + { + "label": "Code Splitting", + "to": "guide/code-splitting" + }, + { + "label": "Automatic Code Splitting", + "to": "guide/automatic-code-splitting" }, { "label": "Data Loading", @@ -195,14 +228,6 @@ "label": "Data Mutations", "to": "guide/data-mutations" }, - { - "label": "Type Safety", - "to": "guide/type-safety" - }, - { - "label": "Type Utilities", - "to": "guide/type-utilities" - }, { "label": "Preloading", "to": "guide/preloading" @@ -212,20 +237,48 @@ "to": "guide/document-head-management" }, { - "label": "Route Masking", - "to": "guide/route-masking" + "label": "SSR", + "to": "guide/ssr" }, { - "label": "Navigation Blocking", - "to": "guide/navigation-blocking" + "label": "Render Optimizations", + "to": "guide/render-optimizations" + } + ], + "frameworks": [ + { + "label": "react", + "children": [] }, { - "label": "Custom Search Param Serialization", - "to": "guide/custom-search-param-serialization" + "label": "solid", + "children": [] + } + ] + }, + { + "label": "Router Configuration", + "collapsible": true, + "children": [ + { + "label": "Creating a Router", + "to": "guide/creating-a-router" }, { - "label": "History Types", - "to": "guide/history-types" + "label": "Outlets", + "to": "guide/outlets" + }, + { + "label": "Router Events", + "to": "guide/router-events" + }, + { + "label": "Type Safety", + "to": "guide/type-safety" + }, + { + "label": "Type Utilities", + "to": "guide/type-utilities" }, { "label": "Router Context", @@ -239,21 +292,9 @@ "label": "Authenticated Routes", "to": "guide/authenticated-routes" }, - { - "label": "Scroll Restoration", - "to": "guide/scroll-restoration" - }, { "label": "Static Route Data", "to": "guide/static-route-data" - }, - { - "label": "SSR", - "to": "guide/ssr" - }, - { - "label": "Render Optimizations", - "to": "guide/render-optimizations" } ], "frameworks": [ diff --git a/docs/router/decisions-on-dx.md b/docs/router/decisions-on-dx.md index 26c366a9da..a06ec4b331 100644 --- a/docs/router/decisions-on-dx.md +++ b/docs/router/decisions-on-dx.md @@ -39,7 +39,7 @@ But to achieve this, we had to make some decisions that deviate from the norms i ## Why is the Router's configuration done this way? -When you want to leverage the TypeScript's inference features to its fullest, you'll quickly realize that _Generics_ are your best friend. And so, TanStack Router uses Generics everywhere to ensure that the types of your routes are inferred as much as possible. +When you want to leverage TypeScript's inference features to its fullest, you'll quickly realize that _Generics_ are your best friend. And so, TanStack Router uses Generics everywhere to ensure that the types of your routes are inferred as much as possible. This means that you have to define your routes in a way that allows TypeScript to infer the types of your routes as much as possible. @@ -219,7 +219,7 @@ TanStack Router's file-based routing is designed to solve all of these issues. I The file-based routing approach is powered by the TanStack Router Bundler Plugin. It performs 3 essential tasks that solve the pain points in route configuration when using code-based routing: 1. **Route configuration boilerplate**: It generates the boilerplate for your route configurations. -2. **Route tree stitching**: It stitches together your route configurations into a single cohesive route-tree. Also in the background, it correctly updates the route configurations to define the `getParentRoute` function match the routes with their parent routes. +2. **Route tree stitching**: It stitches together your route configurations into a single cohesive route-tree. Also in the background, it correctly updates the route configurations to define the `getParentRoute` function and so matches the routes with their parent routes. 3. **Code-splitting**: It automatically code-splits your route content components and updates the route configurations with the correct component. Additionally, at runtime, it ensures that the correct component is loaded when the route is visited. Let's take a look at how the route configuration for the previous example would look like with file-based routing. diff --git a/docs/router/eslint/create-route-property-order.md b/docs/router/eslint/create-route-property-order.md index c22aa7c52d..453fd64acc 100644 --- a/docs/router/eslint/create-route-property-order.md +++ b/docs/router/eslint/create-route-property-order.md @@ -37,7 +37,10 @@ import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/path')({ loader: async ({ context }) => { - await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) + await context.queryClient.query({ + ...getQueryOptions(context.hello), + staleTime: 'static', + }) }, beforeLoad: () => ({ hello: 'world' }), }) @@ -55,7 +58,10 @@ import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/path')({ loader: async ({ context }) => { - await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) + await context.queryClient.query({ + ...getQueryOptions(context.hello), + staleTime: 'static', + }) }, beforeLoad: () => ({ hello: 'world' }), }) @@ -80,7 +86,10 @@ import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/path')({ beforeLoad: () => ({ hello: 'world' }), loader: async ({ context }) => { - await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) + await context.queryClient.query({ + ...getQueryOptions(context.hello), + staleTime: 'static', + }) }, }) ``` @@ -98,7 +107,10 @@ import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/path')({ beforeLoad: () => ({ hello: 'world' }), loader: async ({ context }) => { - await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) + await context.queryClient.query({ + ...getQueryOptions(context.hello), + staleTime: 'static', + }) }, }) ``` diff --git a/docs/router/guide/automatic-code-splitting.md b/docs/router/guide/automatic-code-splitting.md index 4612c298c6..859a19ff09 100644 --- a/docs/router/guide/automatic-code-splitting.md +++ b/docs/router/guide/automatic-code-splitting.md @@ -4,7 +4,7 @@ title: Automatic Code Splitting The automatic code splitting feature in TanStack Router allows you to optimize your application's bundle size by lazily loading route components and their associated data. This is particularly useful for large applications where you want to minimize the initial load time by only loading the necessary code for the current route. -To turn this feature on, simply set the `autoCodeSplitting` option to `true` in your bundler plugin configuration. This enables the router to automatically handle code splitting for your routes without requiring any additional setup. +To turn this feature on, simply set the `autoCodeSplitting` option to `true` in your bundler plugin configuration. This enables the router to automatically handle code splitting for your routes without requiring any additional setup. It is available with Vite, Rspack/Rsbuild and Webpack, not with Esbuild. ```ts // vite.config.ts @@ -35,7 +35,7 @@ This happens seamlessly, without requiring you to manually split your code or ma ### The transformation process -When you enable automatic code splitting, the bundler plugin does this by using static code analysis look at your the code in your route files to transform them into optimized outputs. +When you enable automatic code splitting, the bundler plugin does this by using static code analysis to look at the code in your route files and to transform them into optimized outputs. This transformation process produces two key outputs when each of your route files are processed: @@ -48,7 +48,7 @@ This process ensures that your original code remains clean and readable, while t The decision of what to split into separate chunks is crucial for optimizing your application's performance. TanStack Router uses a concept called "**Split Groupings**" to determine how different parts of your route should be bundled together. -Split groupings are arrays of properties that tell TanStack Router how to bundle different parts of your route together. Each grouping is an list of property names that you want to bundle together into a single lazy-loaded chunk. +Split groupings are arrays of properties that tell TanStack Router how to bundle different parts of your route together. Each grouping is a list of property names that you want to bundle together into a single lazy-loaded chunk. The available properties to split are: @@ -76,7 +76,7 @@ This means that it creates three separate lazy-loaded chunks for each route. Res ### Rules of Splitting -For automatic code splitting to work, there are some rules in-place to make sure that this process can reliably and predictably happen. +For automatic code splitting to work, there are some rules in place to make sure that this process can happen reliably and predictably. #### Do not export route properties diff --git a/docs/router/guide/code-splitting.md b/docs/router/guide/code-splitting.md index 698bf262b5..b1423253be 100644 --- a/docs/router/guide/code-splitting.md +++ b/docs/router/guide/code-splitting.md @@ -115,7 +115,7 @@ These are the only options that `createLazyFileRoute` supports: ### Example code splitting with `.lazy.tsx` -When you are using `.lazy.tsx` you can split your route into two files to enable code splitting: +When you are using `.lazy.tsx`, you can split your route into two files to enable code splitting: **Before (Single File)** diff --git a/docs/router/guide/data-loading.md b/docs/router/guide/data-loading.md index 2ecdf443ad..6b9fd42777 100644 --- a/docs/router/guide/data-loading.md +++ b/docs/router/guide/data-loading.md @@ -81,7 +81,7 @@ Use the object form when you want to configure loader-specific behavior such as The `loader` function receives a single object with the following properties: -- `abortController` - The route's abortController. Its signal is cancelled when the route is unloaded or when the Route is no longer relevant and the current invocation of the `loader` function becomes outdated. +- `abortController` - The controller for this shareable loader invocation. A preload and navigation can share the same in-flight loader work. Its signal is cancelled after the invocation becomes outdated and no consumer still needs it. - `cause` - The cause of the current route match. Can be either one of the following: - `enter` - When the route is matched and loaded after not being matched in the previous location. - `preload` - When the route is being preloaded. @@ -150,7 +150,7 @@ Using these dependencies as keys, TanStack Router will cache the data returned f To control router dependencies and "freshness", TanStack Router provides a plethora of options to control the keying and caching behavior of your route loaders. Let's take a look at them in the order that you are most likely to use them: - `routeOptions.loaderDeps` - - A function that supplies you the search params for a router and returns an object of dependencies for use in your `loader` function. When these deps changed from navigation to navigation, it will cause the route to reload regardless of `staleTime`s. The deps are compared using a deep equality check. + - A deterministic, side-effect-free function that supplies you the validated search params for a router and returns a serializable object of dependencies for use in your `loader` function. When these deps change from navigation to navigation, it will cause the route to reload regardless of `staleTime`s. The deps are compared using a deep equality check. - `routeOptions.staleTime` - `routerOptions.defaultStaleTime` - The number of milliseconds that a route's data should be considered fresh when attempting to load. @@ -168,11 +168,11 @@ To control router dependencies and "freshness", TanStack Router provides a pleth ### ⚠️ Some Important Defaults -- By default, the `staleTime` is set to `0`, meaning that the route's data is immediately considered stale. Stale matches are reloaded in the background when the route is entered again, when its loader key changes (path params used by the route or `loaderDeps`), or when `router.load()` is called explicitly. -- By default, a previously preloaded route is considered fresh for **30 seconds**. This means if a route is preloaded, then preloaded again within 30 seconds, the second preload will be ignored. This prevents unnecessary preloads from happening too frequently. **When a route is loaded normally, the standard `staleTime` is used.** -- By default, the `gcTime` is set to **30 minutes**, meaning that any route data that has not been accessed in 30 minutes will be garbage collected and removed from the cache. +- By default, `staleTime` is set to `0`, so reusable successful data is immediately considered stale. When the same loader key is entered again or `router.load()` is called explicitly, stale data revalidates in the background by default. A different loader key identifies a separate cache entry and must load if it has no reusable data. +- By default, loader data produced by a preload is considered fresh for **30 seconds**. Every preload and navigation still runs its own `beforeLoad` chain, but a later preload and the first navigation can reuse the preload's loader data or in-flight loader work during that interval. After navigation accepts that loader generation, subsequent freshness checks use the standard `staleTime`. +- By default, `gcTime` and `preloadGcTime` define **5-minute** retention windows. Once unused data is older than its applicable window, it is eligible for pruning during a later cache reconciliation. The two windows can be configured independently. - By default, `staleReloadMode` is `'background'`, so stale successful matches keep rendering with their existing `loaderData` while the loader revalidates in the background. -- `router.invalidate()` will force all active routes to reload their loaders immediately and mark every cached route's data as stale. +- `router.invalidate()` selects matching committed, cached, and in-flight loader generations for invalidation and retires matching active preload lanes. Current active routes reload through the normal loading protocol; cached inactive data remains marked stale and reloads when it is reused. By default, stale successful loader data revalidates in the background unless `sync: true` is requested. ### Using `loaderDeps` to access search params @@ -180,6 +180,11 @@ Imagine a `/posts` route supports some pagination via search params `offset` and Once we have these deps in place, the route will always reload when the deps change. +`loaderDeps` defines a cache key during route planning. For the same validated +search input it must return the same value without navigating or mutating state. +The returned value and custom serialization methods such as `toJSON` must also +be side-effect-free. + ```tsx // /routes/posts.tsx export const Route = createFileRoute('/posts')({ @@ -216,7 +221,13 @@ export const Route = createFileRoute('/posts')({ ### Using `staleTime` to control how long data is considered fresh -By default, `staleTime` for navigations is set to `0`ms (and 30 seconds for preloads) which means that the route's data will always be considered stale. When a stale route is entered again, its loader key changes, or `router.load()` is called explicitly, the route will reload in the background. +By default, `staleTime` for accepted navigation data is `0`ms, while +`preloadStaleTime` is 30 seconds. A successful preload can therefore provide +loader data to the first navigation during that interval. Once navigation +accepts that loader generation, normal navigation freshness applies. With the +default `staleTime`, the data is immediately stale for a later use of the same +loader key and revalidates in the background while cached data remains visible. +A different loader key identifies a separate cache entry. **This is a good default for most use cases, but you may find that some route data is more static or potentially expensive to load.** In these cases, you can use the `staleTime` option to control how long the route's data is considered fresh for navigations. Let's take a look at an example: @@ -302,9 +313,16 @@ export const Route = createFileRoute('/posts')({ ### Opting out of caching while still preloading -Even though you may opt-out of short-term caching for your route data, you can still get the benefits of preloading! With the above configuration, preloading will still "just work" with the default `preloadGcTime`. This means that if a route is preloaded, then navigated to, the route's data will be considered fresh and will not be reloaded. +Even though you may opt out of retaining ordinary route data, you can still get +the benefits of preloading. Preloaded results use `preloadGcTime` for retention +and `preloadStaleTime` for freshness, so the default settings keep a recent +preload in memory and let the first navigation reuse it without another loader +call. -To opt out of preloading, don't turn it on via the `routerOptions.defaultPreload` or `routeOptions.preload` options. +Use `routerOptions.defaultPreload` to control automatic link preloading. Setting +`routeOptions.preload` to `false` has a narrower effect: a speculative lane +still runs that route's `beforeLoad`, but skips its `loader`. Navigation runs +both normally. ## Passing all loader events to an external cache @@ -317,7 +335,11 @@ const router = createRouter({ }) ``` -This will ensure that every preload, load, and reload event will trigger your `loader` functions, which can then be handled and deduped by your external cache. +This makes settled preload data immediately stale in the Router, allowing your +external cache to decide whether to fetch. Retention still follows +`preloadGcTime`, and overlapping preload or navigation consumers can still +share in-flight loader work. A route's `shouldReload` option can also suppress +a loader call. ## Using Router Context @@ -472,7 +494,7 @@ export const Route = createFileRoute('/posts')({ ## Using the Abort Signal -The `abortController` property of the `loader` function is an [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController). Its signal is cancelled when the route is unloaded or when the `loader` call becomes outdated. This is useful for cancelling network requests when the route is unloaded or when the route's params change. Here is an example using it with a fetch call: +The `abortController` property of the `loader` function is an [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) for that loader invocation. A preload and navigation can share an in-flight invocation, so its signal remains active while any consumer still needs the work. The signal is cancelled after the invocation becomes outdated and has no remaining consumers. Here is an example using it with a fetch call: ```tsx // src/routes/posts.tsx @@ -548,7 +570,7 @@ The `routeOptions.onCatch` option is a function that is called whenever an error ```tsx // src/routes/posts.tsx export const Route = createFileRoute('/posts')({ - onCatch: ({ error, errorInfo }) => { + onCatch: (error) => { // Log the error console.error(error) }, @@ -559,16 +581,20 @@ export const Route = createFileRoute('/posts')({ The `routeOptions.errorComponent` option is a component that is rendered when an error occurs during the route loading or rendering lifecycle. It is rendered with the following props: -- `error` - The error that occurred +- `error` - The caught value (`unknown` in React and Vue; `Error` in Solid) - `reset` - A function to reset the internal `CatchBoundary` +`ErrorComponentProps` defaults its `error` property to `unknown` in React and Vue, where you must narrow the value before accessing properties such as `message`. In Solid, it defaults to `Error`. `ErrorComponentProps` can describe an error after you have narrowed it; it does not restrict what a route can throw. This applies to boundary components and `onCatch` callbacks, including `defaultOnCatch`; it does not change the `onError` callback. + +React and Vue boundaries pass through the caught value, including falsy values. Solid wraps non-`Error` throws in an `Error` whose `cause` contains the original value. This also applies to Solid error components rendered during SSR: existing `Error` instances are preserved, strings become the error message, and other values use the message `Unknown error`. Router state and loader `onError` callbacks retain the original value. + ```tsx // src/routes/posts.tsx export const Route = createFileRoute('/posts')({ loader: () => fetchPosts(), errorComponent: ({ error }) => { // Render an error message - return
{error.message}
+ return
{error instanceof Error ? error.message : String(error)}
}, }) ``` @@ -582,7 +608,7 @@ export const Route = createFileRoute('/posts')({ errorComponent: ({ error, reset }) => { return (
- {error.message} + {error instanceof Error ? error.message : String(error)} + ) +} +``` + --- Phew! That's a lot of navigating! That said, hopefully you're feeling pretty good about getting around your application now. Let's move on! diff --git a/docs/router/guide/path-params.md b/docs/router/guide/path-params.md index b1ae4f5d2f..d326eabb4b 100644 --- a/docs/router/guide/path-params.md +++ b/docs/router/guide/path-params.md @@ -137,6 +137,9 @@ When multiple dynamic, optional, or wildcard routes can match the same URL, rout Higher `params.priority` values are tried first. The default priority is `0`, and if a higher-priority route's `params.parse` returns `false`, matching continues to the next candidate route. +`params.parse` runs during route planning and may be evaluated more than once. +It must be deterministic and side-effect-free for the same raw params. + ```tsx title="src/routes/posts.$postId.tsx" export const Route = createFileRoute('/posts/$postId')({ params: { @@ -226,7 +229,7 @@ function PostComponent() { -You can even combines prefixes with wildcard routes to create more complex patterns: +You can even combine prefixes with wildcard routes to create more complex patterns: @@ -582,10 +585,10 @@ Optional parameters can be combined with wildcards for complex routing patterns: # React -```tsx title="src/routes/docs/{-$version}/$.tsx" -// Route: /docs/{-$version}/$ +```tsx title="src/routes/docs/v{-$version}/$.tsx" +// Route: /docs/v{-$version}/$ // Matches: /docs/extra/path, /docs/v2/extra/path -export const Route = createFileRoute('/docs/{-$version}/$')({ +export const Route = createFileRoute('/docs/v{-$version}/$')({ component: DocsComponent, }) @@ -595,7 +598,7 @@ function DocsComponent() { return (
- Version: {version || 'latest'} + Version: {version ? `v${version}` : 'latest'} Path: {_splat}
) @@ -604,10 +607,10 @@ function DocsComponent() { # Solid -```tsx title="src/routes/docs/{-$version}/$.tsx" -// Route: /docs/{-$version}/$ +```tsx title="src/routes/docs/v{-$version}/$.tsx" +// Route: /docs/v{-$version}/$ // Matches: /docs/extra/path, /docs/v2/extra/path -export const Route = createFileRoute('/docs/{-$version}/$')({ +export const Route = createFileRoute('/docs/v{-$version}/$')({ component: DocsComponent, }) @@ -616,7 +619,7 @@ function DocsComponent() { return (
- Version: {params().version || 'latest'} + Version: {params().version ? `v${params().version}` : 'latest'} Path: {params()._splat}
) @@ -1392,6 +1395,8 @@ const router = createRouter({ }) ``` +This setting is fixed when the router is created. To use different allowed characters, create a new router instance. + The following is the list of accepted allowed characters: - `;` diff --git a/docs/router/guide/preloading.md b/docs/router/guide/preloading.md index 092a869685..7f48412ce6 100644 --- a/docs/router/guide/preloading.md +++ b/docs/router/guide/preloading.md @@ -18,10 +18,17 @@ Preloading in TanStack Router is a way to load a route before the user actually ## How long does preloaded data stay in memory? -Preloaded route matches are temporarily cached in memory with a few important caveats: +Successful preloaded loader results can enter the router's in-memory cache with +two independent policies: -- **Unused preloaded data is removed after 30 seconds by default.** This can be configured by setting the `defaultPreloadMaxAge` option on your router. -- **Obviously, when a route is loaded, its preloaded version is promoted to the router's normal pending matches state.** +- **Freshness defaults to 30 seconds.** Configure it with + `defaultPreloadStaleTime` or a route's `preloadStaleTime`. +- **The unused retention window defaults to 5 minutes.** Configure it with + `defaultPreloadGcTime` or a route's `preloadGcTime`. Older unused entries + are eligible for pruning during a later cache reconciliation. +- **The speculative lane is never promoted into router state.** Navigation + creates its own presentation and runs its own `beforeLoad` chain. It can reuse + cached loader data or join a loader that is still in flight. If you need more control over preloading, caching and/or garbage collection of preloaded data, you should use an external caching library like [TanStack Query](https://tanstack.com/query). @@ -57,7 +64,7 @@ This will turn on `intent` preloading by default for all `` components in ## Preload Delay -By default, preloading will start after **50ms** of the user hovering or touching a `` component. You can change this delay by setting the `defaultPreloadDelay` option on your router: +By default, intent focus/hover and viewport preloading start after **50ms**. Pending preloads are cancelled if focus or hover ends, or the link leaves the viewport. Touch intent preloads immediately. You can change this delay by setting the `defaultPreloadDelay` option on your router: @@ -87,9 +94,16 @@ const router = createRouter({ You can also set the `preloadDelay` prop on individual `` components to override the default behavior on a per-link basis. -## Built-in Preloading & `preloadStaleTime` +## Built-in Preloading, Freshness, and Retention -If you're using the built-in loaders, you can control how long preloaded data is considered fresh until another preload is triggered by setting either `routerOptions.defaultPreloadStaleTime` or `routeOptions.preloadStaleTime` to a number of milliseconds. **By default, preloaded data is considered fresh for 30 seconds.**. +If you're using the built-in loaders, you can control how long preloaded data is considered fresh by setting either `routerOptions.defaultPreloadStaleTime` or `routeOptions.preloadStaleTime` to a number of milliseconds. **By default, preloaded data is considered fresh for 30 seconds.** + +Freshness and retention are separate. `preloadStaleTime` controls whether the +retained loader result can be reused without another loader call. +`preloadGcTime` (or `defaultPreloadGcTime`) controls when an unused preload +result becomes eligible for pruning during a later cache reconciliation; it +does not schedule a timer to evict the result at that exact moment. Both preload +GC options default to 5 minutes. To change this, you can set the `defaultPreloadStaleTime` option on your router: @@ -125,18 +139,34 @@ Or, you can use the `routeOptions.preloadStaleTime` option on individual routes: // src/routes/posts.$postId.tsx export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params }) => fetchPost(params.postId), - // Preload the route again if the preload cache is older than 10 seconds + // Reload preloaded data when it is more than 10 seconds old preloadStaleTime: 10_000, }) ``` -Client-side preloading also runs each new route's `beforeLoad` with `preload: true`. When a completed successful preload is still fresh under the built-in freshness and invalidation policy used for preloaded loader data, the client router can reuse the context returned by that invocation instead of calling `beforeLoad` again with `preload: false`. Reuse follows route match identity, including `loaderDeps`, and requires a reusable parent context. The `shouldReload` option remains loader-only. Pending, failed, invalidated, or stale preloads do not donate their `beforeLoad` context to a client navigation. +Client-side preloading runs each route's `beforeLoad` with `preload: true`. +Every later preload or navigation runs its own `beforeLoad` chain, so a +navigation observes `preload: false` even when an identical preload is still +active. A later lane can reuse successful settled loader data or join loader +work that is still in flight, but it never reuses `beforeLoad` context or an +already-settled redirect, error, or not-found result. If joined loader work +later produces a terminal outcome, all current consumers of that flight observe +it. The `shouldReload` option remains loader-only. + +If a route has `preload: false`, its speculative lane still runs `beforeLoad`, +but skips that route's loader. Navigation runs `beforeLoad` again and performs +the skipped loader work. ## Preloading with External Libraries When integrating external caching libraries like React Query, which have their own mechanisms for determining stale data, you may want to override the default preloading and stale-while-revalidate logic of TanStack Router. These libraries often use options like staleTime to control the freshness of data. -To customize the preloading behavior in TanStack Router and fully leverage your external library's caching strategy, you can bypass the built-in caching by setting routerOptions.defaultPreloadStaleTime or routeOptions.preloadStaleTime to 0. This ensures that all preloads are marked as stale internally, and loaders are always invoked, allowing your external library, such as React Query, to manage data loading and caching. +To let an external cache make the freshness decision, set +`routerOptions.defaultPreloadStaleTime` or `routeOptions.preloadStaleTime` to +`0`. Settled preload data then becomes immediately stale in the Router, while +retention still follows `preloadGcTime`. Overlapping preload or navigation +consumers can still share in-flight loader work, and `shouldReload` can still +suppress a loader call. For example: @@ -170,25 +200,38 @@ This would then allow you, for instance, to use an option like React Query's `st ## Preloading Manually -If you need to manually preload a route, you can use the router's `preloadRoute` method. It accepts a standard TanStack `NavigateOptions` object and returns a promise that resolves when the route is preloaded. +If you need to manually preload a route, use the router's `preloadRoute` method. +It accepts a standard TanStack `NavigateOptions` object and returns the +speculative match lane. An ordinary error or not-found thrown while loading is +represented in that returned lane; cancellation or control flow that produces +no reusable lane can return `undefined`. # React ```tsx +import { isNotFound } from '@tanstack/react-router' + function Component() { const router = useRouter() useEffect(() => { async function preload() { - try { - const matches = await router.preloadRoute({ - to: postRoute, - params: { id: 1 }, - }) - } catch (err) { - // Failed to preload route + const matches = await router.preloadRoute({ + to: postRoute, + params: { id: 1 }, + }) + + const routeFailure = matches?.find( + (match) => + match.status === 'error' || + match.status === 'notFound' || + isNotFound(match.error), + ) + + if (routeFailure) { + // Inspect routeFailure.error } } @@ -202,18 +245,27 @@ function Component() { # Solid ```tsx +import { isNotFound } from '@tanstack/solid-router' + function Component() { const router = useRouter() createEffect(() => { async function preload() { - try { - const matches = await router.preloadRoute({ - to: postRoute, - params: { id: 1 }, - }) - } catch (err) { - // Failed to preload route + const matches = await router.preloadRoute({ + to: postRoute, + params: { id: 1 }, + }) + + const routeFailure = matches?.find( + (match) => + match.status === 'error' || + match.status === 'notFound' || + isNotFound(match.error), + ) + + if (routeFailure) { + // Inspect routeFailure.error } } diff --git a/docs/router/guide/router-context.md b/docs/router/guide/router-context.md index 5fc4001010..347082106f 100644 --- a/docs/router/guide/router-context.md +++ b/docs/router/guide/router-context.md @@ -278,9 +278,10 @@ Then, in your route: export const Route = createFileRoute('/todos')({ component: Todos, loader: async ({ context }) => { - await context.queryClient.ensureQueryData({ + await context.queryClient.query({ queryKey: ['todos', { userId: user.id }], queryFn: fetchTodos, + staleTime: 'static', }) }, }) diff --git a/docs/router/guide/ssr.md b/docs/router/guide/ssr.md index f87849f8a1..46a0941e7c 100644 --- a/docs/router/guide/ssr.md +++ b/docs/router/guide/ssr.md @@ -60,7 +60,9 @@ To implement non-streaming SSR with TanStack Router, you will need the following ### Automatic Server History -On the client, Router defaults to using an instance of `createBrowserHistory`, which is the preferred type of history to use on the client. On the server, however, you will want to use an instance of `createMemoryHistory` instead. This is because `createBrowserHistory` uses the `window` object, which does not exist on the server. This is handled automatically for you in the RouterServer component. +On the client, Router defaults to using an instance of `createBrowserHistory`. On the server, the Router SSR request handler and TanStack Start automatically create a lightweight history containing only the request URL. This history does not keep a navigation stack or respond to `push`, `replace`, `go`, `back`, or `forward` calls. + +Server-side calls to `router.navigate()` and `router.commitLocation()` are also no-ops: their promises resolve without changing the request location or running another load. To redirect a request, use the dedicated [redirect API](../api/router/redirectFunction.md), such as `throw redirect({ to: '/login' })` in `beforeLoad` or a loader. ### Automatic Loader Dehydration/Hydration @@ -156,6 +158,8 @@ export async function render({ request }: { request: Request }) { using `renderRouterToString` +React and Solid use their native synchronous string renderers. Suspended components render their Suspense fallback without waiting for the component to resolve. The router still finishes serializing hydration data before returning the response. Use `renderRouterToStream` when you need the server to render suspended content after it resolves. + # React @@ -258,6 +262,9 @@ This pattern can be useful for pages that have slow or high-latency data fetchin > [!NOTE] > This streaming pattern is all automatic as long as you are using either `defaultStreamHandler` or `renderRouterToStream`. +> [!IMPORTANT] +> Render [``](./document-head-management.md#scripts) inside `` of your root route. It emits the route scripts and marks where the router inserts streamed hydration data. Without it the response still completes, but the page cannot hydrate. + using `defaultStreamHandler` diff --git a/docs/router/guide/type-safety.md b/docs/router/guide/type-safety.md index 2adffc58c5..3faaed79e7 100644 --- a/docs/router/guide/type-safety.md +++ b/docs/router/guide/type-safety.md @@ -137,12 +137,13 @@ As your application scales, TypeScript check times will naturally increase. Ther ### Only infer types you need -A great pattern with client side data caches (TanStack Query, etc.) is to prefetch data. For example with TanStack Query you might have a route which calls `queryClient.ensureQueryData` in a `loader`. +A great pattern with client side data caches (TanStack Query, etc.) is to prefetch data. For example with TanStack Query you might have a route which calls `queryClient.query` in a `loader`. ```tsx export const Route = createFileRoute('/posts/$postId/deep')({ + // (ctx: LoaderFnContext) => Promise loader: ({ context: { queryClient }, params: { postId } }) => - queryClient.ensureQueryData(postQueryOptions(postId)), + queryClient.query({ ...postQueryOptions(postId), staleTime: 'static' }), component: PostDeepComponent, }) @@ -154,12 +155,16 @@ function PostDeepComponent() { } ``` -This may look fine and for small route trees and you may not notice any TS performance issues. However in this case TS has to infer the loader's return type, despite it never being used in your route. If the loader data is a complex type with many routes that prefetch in this manner, it can slow down editor performance. In this case, the change is quite simple and let typescript infer Promise. +This may look fine and for small route trees and you may not notice any TS performance issues. However in this case TS has to infer the loader's return type, despite it never being used in your route. If the loader data is a complex type with many routes that prefetch in this manner, it can slow down editor performance. In this case, the change is quite simple and let typescript infer `Promise`. ```tsx export const Route = createFileRoute('/posts/$postId/deep')({ + // (ctx: LoaderFnContext) => Promise loader: async ({ context: { queryClient }, params: { postId } }) => { - await queryClient.ensureQueryData(postQueryOptions(postId)) + await queryClient.query({ + ...postQueryOptions(postId), + staleTime: 'static', + }) }, component: PostDeepComponent, }) diff --git a/docs/router/guide/url-rewrites.md b/docs/router/guide/url-rewrites.md index 7bc3df8545..e780e01781 100644 --- a/docs/router/guide/url-rewrites.md +++ b/docs/router/guide/url-rewrites.md @@ -343,6 +343,8 @@ const navigate = useNavigate() navigate({ to: '/about' }) ``` +When the final output URL has a different origin, programmatic navigation performs a full page load automatically. You do not need to set `reloadDocument: true` for cross-origin rewrites. If a route mask is applied, its output URL determines whether navigation stays on the current origin. + ### Hard Links for Cross-Origin Rewrites When an output rewrite changes the origin (hostname), the `` component automatically renders a standard anchor tag instead of using client-side navigation: diff --git a/docs/router/how-to/debug-router-issues.md b/docs/router/how-to/debug-router-issues.md index b4d20ec72f..27dadd361f 100644 --- a/docs/router/how-to/debug-router-issues.md +++ b/docs/router/how-to/debug-router-issues.md @@ -322,11 +322,16 @@ const route = createRoute({ ```tsx function DataLoadingDebug() { - const location = useLocation() + const state = useRouterState() console.log('Route status:', { - isLoading: location.isLoading, - isTransitioning: location.isTransitioning, + status: state.status, + isLoading: state.isLoading, + matches: state.matches.map((match) => ({ + routeId: match.routeId, + status: match.status, + isFetching: match.isFetching, + })), }) return null diff --git a/docs/router/how-to/setup-testing.md b/docs/router/how-to/setup-testing.md index 72f40032cf..104cbedc0d 100644 --- a/docs/router/how-to/setup-testing.md +++ b/docs/router/how-to/setup-testing.md @@ -224,8 +224,12 @@ export function LoadingComponent() { return
Loading...
} -export function ErrorComponent({ error }: { error: Error }) { - return
Error: {error.message}
+export function ErrorComponent({ error }: { error: unknown }) { + return ( +
+ Error: {error instanceof Error ? error.message : String(error)} +
+ ) } ``` @@ -586,8 +590,12 @@ describe('Code-Based Route Data Loading', () => { return
{user.name}
} - function ErrorComponent({ error }: { error: Error }) { - return
Error: {error.message}
+ function ErrorComponent({ error }: { error: unknown }) { + return ( +
+ Error: {error instanceof Error ? error.message : String(error)} +
+ ) } const userRoute = createRoute({ @@ -651,9 +659,10 @@ describe('React Query Integration', () => { path: '/posts', component: PostsList, loader: ({ context: { queryClient } }) => - queryClient.ensureQueryData({ + queryClient.query({ queryKey: ['posts'], queryFn: mockFetchPosts, + staleTime: 'static', }), }) diff --git a/docs/router/how-to/share-search-params-across-routes.md b/docs/router/how-to/share-search-params-across-routes.md index e1e24c1e0d..23a202b176 100644 --- a/docs/router/how-to/share-search-params-across-routes.md +++ b/docs/router/how-to/share-search-params-across-routes.md @@ -2,8 +2,6 @@ title: Share Search Parameters Across Routes --- -# How to Share Search Parameters Across Routes - Search parameters automatically inherit from parent routes in TanStack Router. When a parent route validates search parameters, child routes can access them via `Route.useSearch()` alongside their own parameters. ## How Parameter Inheritance Works diff --git a/docs/router/how-to/use-environment-variables.md b/docs/router/how-to/use-environment-variables.md index 2d35308158..4f6a764f28 100644 --- a/docs/router/how-to/use-environment-variables.md +++ b/docs/router/how-to/use-environment-variables.md @@ -164,7 +164,7 @@ const fetchPosts = async () => { export const Route = createFileRoute('/posts/')({ loader: fetchPosts, errorComponent: ({ error }) => ( -
Error loading posts: {error.message}
+
Error loading posts: {error instanceof Error ? error.message : String(error)}
), }) ``` diff --git a/docs/router/how-to/validate-search-params.md b/docs/router/how-to/validate-search-params.md index 5abd435cef..15d3f9d6c8 100644 --- a/docs/router/how-to/validate-search-params.md +++ b/docs/router/how-to/validate-search-params.md @@ -36,7 +36,7 @@ export const Route = createFileRoute('/products')({ return (

Invalid Search Parameters

-

{error.message}

+

{error instanceof Error ? error.message : String(error)}

diff --git a/docs/router/installation/manual.md b/docs/router/installation/manual.md index 76d1f1fe6a..ab89060ef1 100644 --- a/docs/router/installation/manual.md +++ b/docs/router/installation/manual.md @@ -232,7 +232,7 @@ render(() => , rootElement) Regardless of whether you are using the `@tanstack/router-plugin` package and running the `npm run dev`/`npm run build` scripts, or manually running the `tsr watch`/`tsr generate` commands from your package scripts, the route tree file will be generated at `src/routeTree.gen.ts`. -If you are working with this pattern you should change the `id` of the root `
` on your `index.html` file to `
` +If you are working with this pattern, you should change the `id` of the root `
` on your `index.html` file to `
` ## Using Code-Based Route Configuration diff --git a/docs/router/installation/with-esbuild.md b/docs/router/installation/with-esbuild.md index b5cad0622c..8ecd9b8d0a 100644 --- a/docs/router/installation/with-esbuild.md +++ b/docs/router/installation/with-esbuild.md @@ -25,7 +25,6 @@ export default { plugins: [ tanstackRouter({ target: 'react', - autoCodeSplitting: true, }), ], } @@ -50,10 +49,7 @@ const ctx = await esbuild.context({ format: 'esm', target: ['esnext'], sourcemap: true, - plugins: [ - solidPlugin(), - tanstackRouter({ target: 'solid', autoCodeSplitting: true }), - ], + plugins: [solidPlugin(), tanstackRouter({ target: 'solid' })], }) if (isDev) { @@ -72,6 +68,9 @@ Or, you can clone our [Quickstart Esbuild example](https://github.com/TanStack/r Now that you've added the plugin to your Esbuild configuration, you're all set to start using file-based routing with TanStack Router. +> [!NOTE] +> Automatic code splitting is not available with Esbuild: the plugin throws an error when `autoCodeSplitting` is `true`. Route generation works as usual. To split routes, use [manual code splitting](../guide/code-splitting.md) or another bundler. + ## Ignoring the generated route tree file If your project is configured to use a linter and/or formatter, you may want to ignore the generated route tree file. This file is managed by TanStack Router and therefore shouldn't be changed by your linter or formatter. diff --git a/docs/router/integrations/query.md b/docs/router/integrations/query.md index 243fcefdf4..707f90900c 100644 --- a/docs/router/integrations/query.md +++ b/docs/router/integrations/query.md @@ -17,7 +17,7 @@ title: TanStack Query Integration The TanStack query integration is a separate package that you need to install: - + react: @tanstack/react-router-ssr-query solid: @tanstack/solid-router-ssr-query @@ -152,7 +152,7 @@ Preload critical data in the route `loader` to avoid waterfalls and loading flas -# React +# Blocking `query` in loader ```tsx title="src/routes/posts.tsx" import { queryOptions, useSuspenseQuery, useQuery } from '@tanstack/react-query' @@ -165,7 +165,12 @@ const postsQuery = queryOptions({ export const Route = createFileRoute('/posts')({ // Ensure the data is in the cache before render - loader: ({ context }) => context.queryClient.ensureQueryData(postsQuery), + loader: ({ context }) => + context.queryClient.query({ + ...postsQuery, + // returns data from cache immediately, otherwise executes a fetch + staleTime: 'static', + }), component: PostsPage, }) @@ -180,15 +185,15 @@ function PostsPage() { ### Prefetching and streaming -You can also prefetch with `fetchQuery` or `ensureQueryData` in a loader without consuming the data in a component. If you return the promise directly from the loader, it will be awaited and thus block the SSR request until the query finishes. If you don't await the promise nor return it, the query will be started on the server and will be streamed to the client without blocking the SSR request. +You can also prefetch with `query` in a loader without consuming the data in a component. If you return the promise directly from the loader, it will be awaited and thus block the SSR request until the query finishes. If you don't await the promise nor return it, the query will be started on the server and will be streamed to the client without blocking the SSR request. -# React +# Non-blocking `query` in loader ```tsx title="src/routes/users.$id.tsx" import { createFileRoute } from '@tanstack/react-router' -import { queryOptions, useQuery } from '@tanstack/react-query' +import { noop, queryOptions, useQuery } from '@tanstack/react-query' const userQuery = (id: string) => queryOptions({ @@ -197,15 +202,18 @@ const userQuery = (id: string) => }) export const Route = createFileRoute('/user/$id')({ - loader: ({ params }) => { - // do not await this nor return the promise, just kick off the query to stream it to the client - context.queryClient.fetchQuery(userQuery(params.id)) + loader: ({ context, params }) => { + // Do not await this nor return the promise, just kick off the query to stream it to the client + void context.queryClient.query(userQuery(params.id)).catch(noop) }, }) ``` +> [!NOTE] +> Previous versions of this guide used `queryClient.ensureQueryData` and `queryClient.prefetchQuery`. These methods are now deprecated in TanStack Query in favor of `queryClient.query`. See the TanStack Query [v5 migration guide](https://tanstack.com/query/latest/docs/framework/react/guides/migrating-to-v5#imperative-queryclient-methods) for more details. + ## Redirect handling If a query or mutation throws a `redirect(...)`, the integration intercepts it on the client and performs a router navigation. diff --git a/docs/router/routing/code-based-routing.md b/docs/router/routing/code-based-routing.md index d3102cafd6..b1457c6fbe 100644 --- a/docs/router/routing/code-based-routing.md +++ b/docs/router/routing/code-based-routing.md @@ -14,7 +14,7 @@ title: Code-Based Routing Code-based routing is no different from file-based routing in that it uses the same route tree concept to organize, match and compose matching routes into a component tree. The only difference is that instead of using the filesystem to organize your routes, you use code. -Let's consider the same route tree from the [Route Trees & Nesting](./route-trees.md#route-trees) guide, and convert it to code-based routing: +Let's consider the same route tree from the [Route Trees](./route-trees.md#route-trees) guide, and convert it to code-based routing: Here is the file-based version: diff --git a/docs/router/routing/file-based-routing.md b/docs/router/routing/file-based-routing.md index 6be11e55d6..2eea38bba2 100644 --- a/docs/router/routing/file-based-routing.md +++ b/docs/router/routing/file-based-routing.md @@ -12,7 +12,7 @@ File-based routing is a way to configure your routes using the filesystem. Inste - **Organization**: Routes are organized in a way that mirrors the URL structure of your application. - **Scalability**: As your application grows, file-based routing makes it easy to add new routes and maintain existing ones. - **Code-Splitting**: File-based routing allows TanStack Router to automatically code-split your routes for better performance. -- **Type-Safety**: File-based routing raises the ceiling on type-safety by generating managing type linkages for your routes, which can otherwise be a tedious process via code-based routing. +- **Type-Safety**: File-based routing raises the ceiling on type-safety by generating and managing type linkages for your routes, which can otherwise be a tedious process via code-based routing. - **Consistency**: File-based routing enforces a consistent structure for your routes, making it easier to maintain and update your application and move from one project to another. ## `/`s or `.`s? @@ -80,7 +80,7 @@ See the example below: ## Mixed Flat and Directory Routes -It's extremely likely that a 100% directory or flat route structure won't be the best fit for your project, which is why TanStack Router allows you to mix both flat and directory routes together to create a route tree that uses the best of both worlds where it makes sense: +It's extremely likely that a 100% directory or flat route structure won't be the best fit for your project, which is why TanStack Router allows you to mix both flat and directory routes together to create a route tree that uses the best of both worlds where it makes sense. See the example below: diff --git a/docs/router/routing/file-naming-conventions.md b/docs/router/routing/file-naming-conventions.md index 115310f5b3..896e7d3d9b 100644 --- a/docs/router/routing/file-naming-conventions.md +++ b/docs/router/routing/file-naming-conventions.md @@ -2,7 +2,7 @@ title: File Naming Conventions --- -File-based routing requires that you follow a few simple file naming conventions to ensure that your routes are generated correctly. The concepts these conventions enable are covered in detail in the [Route Trees & Nesting](./route-trees.md) guide. +File-based routing requires that you follow a few simple file naming conventions to ensure that your routes are generated correctly. The concepts these conventions enable are covered in detail in the [Route Trees](./route-trees.md) guide. | Feature | Description | | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -40,4 +40,4 @@ Pathless routes wrap child routes with either logic or a component without requi | ʦ `_app.a.tsx` | /a | `
` | | ʦ `_app.b.tsx` | /b | `` | -To learn more about pathless routes, see the [Routing Concepts - Pathless Routes](./routing-concepts.md#pathless-layout-routes) guide. +To learn more about pathless routes, see the [Routing Concepts - Pathless Layout Routes](./routing-concepts.md#pathless-layout-routes) guide. diff --git a/docs/router/routing/routing-concepts.md b/docs/router/routing/routing-concepts.md index 88eebbd5f0..11674e69c2 100644 --- a/docs/router/routing/routing-concepts.md +++ b/docs/router/routing/routing-concepts.md @@ -564,7 +564,7 @@ routes/ │ ├── ... ``` -We can import from the excluded files into our posts route +We can import from the excluded files into our posts route: diff --git a/docs/start/config.json b/docs/start/config.json index e93688eb91..36af0e6e0d 100644 --- a/docs/start/config.json +++ b/docs/start/config.json @@ -36,6 +36,10 @@ { "label": "Migrate from Next.js", "to": "framework/react/migrate-from-next-js" + }, + { + "label": "Migrate from the Release Candidate", + "to": "framework/react/migrate-from-release-candidate" } ] }, @@ -53,14 +57,19 @@ { "label": "Build from Scratch", "to": "framework/solid/build-from-scratch" + }, + { + "label": "Migrate from the Release Candidate", + "to": "framework/solid/migrate-from-release-candidate" } ] } ] }, { - "label": "Guides", + "label": "Server & Execution", "children": [], + "collapsible": true, "frameworks": [ { "label": "react", @@ -81,6 +90,10 @@ "label": "Import Protection", "to": "framework/react/guide/import-protection" }, + { + "label": "Path Aliases", + "to": "framework/react/guide/path-aliases" + }, { "label": "Environment Variables", "to": "framework/react/guide/environment-variables" @@ -89,6 +102,10 @@ "label": "Server Functions", "to": "framework/react/guide/server-functions" }, + { + "label": "Streaming Data from Server Functions", + "to": "framework/react/guide/streaming-data-from-server-functions" + }, { "label": "Server Components", "to": "framework/react/guide/server-components" @@ -112,7 +129,72 @@ { "label": "Server Routes", "to": "framework/react/guide/server-routes" + } + ] + }, + { + "label": "solid", + "children": [ + { + "label": "Routing", + "to": "framework/solid/guide/routing" }, + { + "label": "Execution Model", + "to": "framework/solid/guide/execution-model" + }, + { + "label": "Code Execution Patterns", + "to": "framework/solid/guide/code-execution-patterns" + }, + { + "label": "Import Protection", + "to": "framework/solid/guide/import-protection" + }, + { + "label": "Path Aliases", + "to": "framework/solid/guide/path-aliases" + }, + { + "label": "Environment Variables", + "to": "framework/solid/guide/environment-variables" + }, + { + "label": "Server Functions", + "to": "framework/solid/guide/server-functions" + }, + { + "label": "Static Server Functions", + "to": "framework/solid/guide/static-server-functions" + }, + { + "label": "Environment Functions", + "to": "framework/solid/guide/environment-functions" + }, + { + "label": "Middleware", + "to": "framework/solid/guide/middleware" + }, + { + "label": "Error Boundaries", + "to": "framework/solid/guide/error-boundaries" + }, + { + "label": "Server Routes", + "to": "framework/solid/guide/server-routes" + } + ] + } + ] + }, + { + "label": "Rendering", + "children": [], + "collapsible": true, + "frameworks": [ + { + "label": "react", + "children": [ { "label": "Hydration Errors", "to": "framework/react/guide/hydration-errors" @@ -141,6 +223,10 @@ "label": "Server Entry Point", "to": "framework/react/guide/server-entry-point" }, + { + "label": "Client Entry Point", + "to": "framework/react/guide/client-entry-point" + }, { "label": "Early Hints", "to": "framework/react/guide/early-hints" @@ -148,108 +234,12 @@ { "label": "CDN Asset URLs", "to": "framework/react/guide/cdn-asset-urls" - }, - { - "label": "CSS Styling", - "to": "framework/react/guide/css-styling" - }, - { - "label": "Client Entry Point", - "to": "framework/react/guide/client-entry-point" - }, - { - "label": "Hosting", - "to": "framework/react/guide/hosting" - }, - { - "label": "Authentication Overview", - "to": "framework/react/guide/authentication-overview" - }, - { - "label": "Authentication Server Primitives", - "to": "framework/react/guide/authentication-server-primitives" - }, - { - "label": "Authentication", - "to": "framework/react/guide/authentication" - }, - { - "label": "Databases", - "to": "framework/react/guide/databases" - }, - { - "label": "Observability", - "to": "framework/react/guide/observability" - }, - { - "label": "Path Aliases", - "to": "framework/react/guide/path-aliases" - }, - { - "label": "Tailwind CSS Integration", - "to": "framework/react/guide/tailwind-integration" - }, - { - "label": "Rendering Markdown", - "to": "framework/react/guide/rendering-markdown" - }, - { - "label": "SEO", - "to": "framework/react/guide/seo" - }, - { - "label": "Generative Engine Optimization (GEO)", - "to": "framework/react/guide/geo" } ] }, { "label": "solid", "children": [ - { - "label": "Routing", - "to": "framework/solid/guide/routing" - }, - { - "label": "Execution Model", - "to": "framework/solid/guide/execution-model" - }, - { - "label": "Code Execution Patterns", - "to": "framework/solid/guide/code-execution-patterns" - }, - { - "label": "Import Protection", - "to": "framework/solid/guide/import-protection" - }, - { - "label": "Environment Variables", - "to": "framework/solid/guide/environment-variables" - }, - { - "label": "Server Functions", - "to": "framework/solid/guide/server-functions" - }, - { - "label": "Static Server Functions", - "to": "framework/solid/guide/static-server-functions" - }, - { - "label": "Environment Functions", - "to": "framework/solid/guide/environment-functions" - }, - { - "label": "Middleware", - "to": "framework/solid/guide/middleware" - }, - { - "label": "Error Boundaries", - "to": "framework/solid/guide/error-boundaries" - }, - { - "label": "Server Routes", - "to": "framework/solid/guide/server-routes" - }, { "label": "Hydration Errors", "to": "framework/solid/guide/hydration-errors" @@ -274,24 +264,90 @@ "label": "Server Entry Point", "to": "framework/solid/guide/server-entry-point" }, - { - "label": "Early Hints", - "to": "framework/solid/guide/early-hints" - }, - { - "label": "CSS Styling", - "to": "framework/solid/guide/css-styling" - }, { "label": "Client Entry Point", "to": "framework/solid/guide/client-entry-point" }, + { + "label": "Early Hints", + "to": "framework/solid/guide/early-hints" + } + ] + } + ] + }, + { + "label": "Deployment & Operations", + "children": [], + "collapsible": true, + "frameworks": [ + { + "label": "react", + "children": [ + { + "label": "Production Checklist", + "to": "framework/react/guide/production-checklist" + }, + { + "label": "Hosting", + "to": "framework/react/guide/hosting" + }, + { + "label": "Observability", + "to": "framework/react/guide/observability" + } + ] + }, + { + "label": "solid", + "children": [ { "label": "Hosting", "to": "framework/solid/guide/hosting" }, { - "label": "Authentication Overview", + "label": "Observability", + "to": "framework/solid/guide/observability" + } + ] + } + ] + }, + { + "label": "Authentication & Data", + "children": [], + "collapsible": true, + "frameworks": [ + { + "label": "react", + "children": [ + { + "label": "Choose Authentication", + "to": "framework/react/guide/authentication-overview" + }, + { + "label": "Authentication Server Primitives", + "to": "framework/react/guide/authentication-server-primitives" + }, + { + "label": "Implement Authentication", + "to": "framework/react/guide/authentication" + }, + { + "label": "Databases", + "to": "framework/react/guide/databases" + }, + { + "label": "TanStack Query", + "to": "framework/react/guide/tanstack-query" + } + ] + }, + { + "label": "solid", + "children": [ + { + "label": "Choose Authentication", "to": "framework/solid/guide/authentication-overview" }, { @@ -299,20 +355,53 @@ "to": "framework/solid/guide/authentication-server-primitives" }, { - "label": "Authentication", + "label": "Implement Authentication", "to": "framework/solid/guide/authentication" }, { "label": "Databases", "to": "framework/solid/guide/databases" + } + ] + } + ] + }, + { + "label": "Styling & Metadata", + "children": [], + "collapsible": true, + "frameworks": [ + { + "label": "react", + "children": [ + { + "label": "CSS Styling", + "to": "framework/react/guide/css-styling" }, { - "label": "Observability", - "to": "framework/solid/guide/observability" + "label": "Tailwind CSS Integration", + "to": "framework/react/guide/tailwind-integration" }, { - "label": "Path Aliases", - "to": "framework/solid/guide/path-aliases" + "label": "Rendering Markdown", + "to": "framework/react/guide/rendering-markdown" + }, + { + "label": "SEO", + "to": "framework/react/guide/seo" + }, + { + "label": "Generative Engine Optimization (GEO)", + "to": "framework/react/guide/geo" + } + ] + }, + { + "label": "solid", + "children": [ + { + "label": "CSS Styling", + "to": "framework/solid/guide/css-styling" }, { "label": "Tailwind CSS Integration", diff --git a/docs/start/framework/react/comparison.md b/docs/start/framework/react/comparison.md index e734263d9d..b72e286a76 100644 --- a/docs/start/framework/react/comparison.md +++ b/docs/start/framework/react/comparison.md @@ -1,338 +1,61 @@ --- title: Comparison | TanStack Start vs Next.js vs React Router +description: Compare rendering, server APIs, caching, forms, and deployment in TanStack Start, Next.js App Router, and React Router Framework Mode. toc: false --- -Choosing a full-stack React framework? This comparison focuses on the **full-stack framework features** that distinguish TanStack Start from Next.js and React Router (v7 Framework Mode). +This matrix compares full-stack framework capabilities. For the choice between Start and Next.js, read [TanStack Start vs Next.js](./start-vs-nextjs). For navigation and URL-state APIs, see the [TanStack Router comparison](/router/latest/docs/comparison). -> **🚨 IMPORTANT: Looking for routing features?** -> -> TanStack Start is built on **TanStack Router**, which provides industry-leading type-safe routing capabilities. For a comprehensive comparison of routing features (nested routes, search params, type safety, loaders, etc.), please see: -> -> ### [📖 TanStack Router Comparison vs React Router / Next.js →](/router/latest/docs/framework/react/comparison) -> -> That comparison covers all the routing features in detail. This page focuses specifically on **full-stack framework capabilities** like SSR, server functions, middleware, deployment, and more. +Checked September 11, 2026 against the linked documentation: TanStack Start's current guides, Next.js 16.3 App Router, and React Router 8.3 Framework Mode. -While we aim to provide an accurate and fair comparison, please note that this table may not capture every nuance or recent update of each framework. We recommend reviewing the official documentation and trying out each solution to make the most informed decision for your specific use case. +## Rendering and data -If you find any discrepancies or have suggestions for improvement, please don't hesitate to contribute via the "Edit this page on GitHub" link at the bottom of this page or open an issue in the [TanStack Router GitHub repository](https://github.com/TanStack/router). +| Capability | TanStack Start | Next.js App Router | React Router Framework Mode | +| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | +| Server rendering | [SSR with hydration by default](./overview) | [Server and Client Components contribute to initial HTML](https://nextjs.org/docs/app/getting-started/server-and-client-components) | [Server rendering is configurable](https://reactrouter.com/start/framework/rendering) | +| Rendering control | [Per-route full, data-only, or disabled SSR](./guide/selective-ssr) | [Server/Client Component boundaries](https://nextjs.org/docs/app/getting-started/server-and-client-components); `use client` does not disable initial SSR | [Global SSR setting and route-level client loaders](https://reactrouter.com/start/framework/rendering) | +| SPA applications | [Dedicated SPA mode](./guide/spa-mode) | [Documented SPA patterns](https://nextjs.org/docs/app/guides/single-page-applications) | [`ssr: false`](https://reactrouter.com/start/framework/rendering) | +| Static output | [Prerendering configuration](./guide/static-prerendering) | [Static export](https://nextjs.org/docs/app/guides/static-exports), with server-feature limitations | [Prerender selected URLs](https://reactrouter.com/start/framework/rendering) | +| React Server Components | [Experimental, opt-in](./guide/server-components) | [Core App Router component model](https://nextjs.org/docs/app/getting-started/server-and-client-components) | [Unstable RSC integration](https://reactrouter.com/how-to/react-server-components) | +| Client data reuse | [Router loader caching](/router/latest/docs/guide/data-loading), plus [Query integration](/router/latest/docs/integrations/query) | [Navigation caching and server cache APIs](https://nextjs.org/docs/app/getting-started/caching); a query library can manage additional client data | [Loader/action revalidation](https://reactrouter.com/start/framework/actions); separate client-data tools can be added | +| Revalidation after deployment | [HTTP caching and provider-specific ISR configuration](./guide/isr) | [ISR and cache coordination](https://nextjs.org/docs/app/guides/self-hosting) | [HTTP response headers](https://reactrouter.com/how-to/headers) and deployment infrastructure | -Feature/Capability Key: +A client loader cache, a cached server result, and a cached HTML response are different things. Compare invalidation behavior, persistence, and multi-instance coordination for the layer your application needs. A CDN honoring `stale-while-revalidate` is not proof of identical ISR behavior across providers. -- ✅ 1st-class, built-in, and ready to use with no added configuration or code -- 🟡 Partial Support (rated 1-5 where noted) -- 🟠 Supported via addon/community package -- 🔶 Possible, but requires custom code/implementation/casting -- 🛑 Not officially supported +## Server APIs and forms -| | TanStack Start | Next.js [_(Website)_][nextjs] | React Router [_(Website)_][react-router] | -| ----------------------------------------------------------------- | ------------------------------------------------ | --------------------------------------------- | ------------------------------------------ | -| Github Repo / Stars | [![][stars-tanstack-router]][gh-tanstack-router] | [![][stars-nextjs]][gh-nextjs] | [![][stars-react-router]][gh-react-router] | -| Bundle Size | [![][bp-tanstack-router]][bpl-tanstack-router] | ❓ | ❓ | -| -- | -- | -- | -- | -| **Routing Features** [_(See Full Comparison)_][router-comparison] | ✅ Built on TanStack Router | ✅ File-based App Router | ✅ File-based Nested Routes | -| -- | -- | -- | -- | -| **Full-Stack Features** | -- | -- | -- | -| SSR | ✅ | ✅ | ✅ | -| Streaming SSR | ✅ | ✅ | ✅ | -| Selective SSR (per-route) | ✅ | 🔶 | 🔶 | -| SPA Mode | ✅ | 🔶 (via "use client") | ✅ | -| Built-in Client-Side SWR Caching | ✅ (via TanStack Router) | 🔶 (fetch cache only) | 🛑 | -| Data Fetching Library Integration | ✅ (Official TanStack Query, Apollo, etc.) | 🔶 (manual integration) | 🔶 (manual integration) | -| Static Prerendering (SSG) | ✅ | ✅ | ✅ | -| Incremental Static Regeneration (ISR) | ✅ (via Cache-Control headers) | ✅ (Proprietary) | ✅ (via Cache-Control headers) | -| React Server Components | 🟡 (Experimental) | ✅ | 🟡 (Experimental) | -| Server Functions | ✅ (RPC-based) | ✅ (Server Actions) | ✅ (Actions) | -| Server Function Client Middleware | ✅ | 🛑 | 🛑 | -| Server Function Server Middleware | ✅ | 🛑 | ✅ | -| Request Middleware (All Routes) | ✅ | ✅ | ✅ | -| Server Function Input Validation | ✅ | 🔶 (manual) | 🔶 (manual) | -| API Routes / Server Routes / Resource Routes | ✅ | ✅ | ✅ | -| `
` API | 🛑 | 🟠 (via React 19 useActionState) | ✅ | -| -- | -- | -- | -- | -| **Developer Experience** | -- | -- | -- | -| Devtools | ✅ | 🛑 | 🟠 (3rd party) | -| CLI Tooling | ✅ | ✅ | ✅ | -| Dev Server Startup Speed | ✅ (Fast) | 🛑 (Slow) | ✅ (Fast) | -| HMR Speed | ✅ (Fast, Vite or Rsbuild) | 🛑 (Slow, Webpack/Turbopack) | ✅ (Fast, Vite) | -| Dev Navigation Speed | ✅ | 🟡 | ✅ | -| Dev Resource Usage (CPU/RAM) | ✅ (Lightweight) | 🛑 (Heavy) | ✅ (Lightweight) | -| TypeScript Support | ✅ | ✅ | ✅ | -| Type-First Architecture | ✅ | 🛑 | 🛑 | -| -- | -- | -- | -- | -| **Deployment & Hosting** | -- | -- | -- | -| Deployment Flexibility | ✅ (Vite and Rsbuild builds) | 🟡 (Optimized for Vercel, possible elsewhere) | ✅ (Multiple adapters) | -| Edge Runtime Support | ✅ | ✅ | ✅ | -| Serverless Support | ✅ | ✅ | ✅ | -| Node.js Support | ✅ | ✅ | ✅ | -| Docker Support | ✅ | ✅ | ✅ | -| Static Export | ✅ | ✅ | ✅ | -| Official Cloudflare Support | ✅ | 🟡 | ✅ | -| Official Netlify Support | ✅ | 🟡 | ✅ | -| Official Vercel Support | ✅ (via Nitro) | ✅ | ✅ | +| Capability | TanStack Start | Next.js App Router | React Router Framework Mode | +| -------------------------- | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | +| Server calls and mutations | [Typed server functions with GET or POST](./guide/server-functions) | [Server Actions](https://nextjs.org/docs/app/guides/forms) | [Route actions and fetchers](https://reactrouter.com/start/framework/actions) | +| Input validation | [Validator API with inferred types](./guide/server-functions) | [Validate action input with application code or a schema](https://nextjs.org/docs/app/guides/forms) | [Validate action input with application code](https://reactrouter.com/how-to/form-validation) | +| Middleware | [Request middleware and client/server function middleware](./guide/middleware) | [Request interception with Proxy](https://nextjs.org/docs/app/getting-started/proxy); action authorization belongs in server code | [Server and client route middleware](https://reactrouter.com/how-to/middleware) | +| Form handling | [Server functions](./guide/server-functions) can be called from event handlers; use a form library when needed | [Built-in `next/form`](https://nextjs.org/docs/app/api-reference/components/form), plus [Server Action forms](https://nextjs.org/docs/app/guides/forms) | [`Form`, actions, and fetchers](https://reactrouter.com/start/framework/actions) | +| Server endpoints | [Server routes](./guide/server-routes) | [Route Handlers](https://nextjs.org/docs/app/getting-started/route-handlers) | [Resource routes](https://reactrouter.com/how-to/resource-routes) | ---- +Type inference helps callers write valid code. It does not validate an incoming HTTP request or authorize access to a record. All three frameworks need runtime validation and server-side authorization for private operations. For Start, see [Authentication Server Primitives](./guide/authentication-server-primitives). -> **⚠️ Remember:** For detailed comparisons of **routing features** (type safety, search params, loaders, navigation, etc.), see the [**TanStack Router Comparison**][router-comparison]. This page focuses on full-stack framework capabilities. +## Tooling and deployment ---- +| Capability | TanStack Start | Next.js App Router | React Router Framework Mode | +| ----------------------- | ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | +| Build integration | [Vite or Rsbuild](./build-from-scratch) | [Turbopack](https://nextjs.org/docs/app/api-reference/turbopack) | [Framework tooling](https://reactrouter.com/start/framework/installation) | +| Type support | [Router inference](/router/latest/docs/guide/type-safety) and [server function inference](./guide/server-functions) | [Stable opt-in typed links](https://nextjs.org/docs/app/api-reference/config/next-config-js/typedRoutes) and TypeScript APIs | [Generated route-module types](https://reactrouter.com/how-to/route-module-type-safety) | +| Metadata | [Route head management and SEO guide](./guide/seo) | [Metadata API and file conventions](https://nextjs.org/docs/app/getting-started/metadata-and-og-images) | [Route-module metadata](https://reactrouter.com/start/framework/route-module) | +| Image and font handling | Choose CSS, an image service, or an integration for your deployment | Built-in [`next/image`](https://nextjs.org/docs/app/api-reference/components/image) and [`next/font`](https://nextjs.org/docs/app/api-reference/components/font) | Choose CSS, an image service, or an integration for your deployment | +| Hosting | [Provider and runtime guides](./guide/hosting) | [Self-hosting](https://nextjs.org/docs/app/guides/self-hosting) or a deployment provider | [Deployment templates and hosting options](https://reactrouter.com/start/framework/deploying) | -## Key Philosophical Differences - -### TanStack Start - -**Philosophy**: Maximum developer freedom with best-in-class type safety. - -- **Router-First**: Built on TanStack Router (see [full routing comparison][router-comparison]) -- **Deployment Agnostic**: Built on Vite and Rsbuild integrations, deploy without vendor lock-in -- **Composable Middleware**: Middleware system works at both the request level AND individual server function level (both client & server) -- **Selective SSR**: Fine-grained control over SSR behavior per route (full SSR, data-only, or client-only) -- **Developer Control**: Explicit, composable patterns over convention-based magic -- **Type Safety First**: End-to-end compile-time safety for server functions, loaders, and routing - -### Next.js - -**Philosophy**: Production-ready with optimal defaults, best with Vercel. - -- **RSC-First**: Deep integration with React Server Components as the primary paradigm -- **Vercel-Optimized**: Best performance and DX on Vercel's infrastructure -- **Convention over Configuration**: Opinionated structure with file-system routing conventions -- **Automatic Optimizations**: Many performance optimizations happen automatically -- **Production Grade**: Battle-tested at massive scale - -### React Router (v7 Framework Mode) - -**Philosophy**: Web fundamentals with progressive enhancement. - -- **Web Standards**: Embraces web platform primitives (fetch, FormData, Headers) -- **Progressive Enhancement**: Works without JavaScript by default -- **Nested Routes**: First-class support for nested routing and data loading -- **Action-Based**: Form submissions via actions follow web standards -- **Framework Evolution**: Successor to Remix, with Vite-based architecture - -## When to Choose Each Framework - -### Choose TanStack Start if you: - -- Want the absolute best type safety for routing (see [Router Comparison][router-comparison]) -- Need deployment flexibility without vendor lock-in (works with Vite and Rsbuild builds) -- Prefer composable, explicit patterns over convention -- Want fine-grained control over SSR behavior (selective SSR per route) -- Need composable middleware that works at both request and server function levels -- Are building a complex application that benefits from TanStack Router's advanced features -- Already use TanStack Query or other TanStack libraries - -### Choose Next.js if you: - -- Want to use React Server Components today with full ecosystem support -- Are deploying to Vercel or want a Vercel-optimized experience -- Prefer convention over configuration for faster initial development -- Want automatic image optimization and font loading - -### Choose React Router if you: - -- Prioritize progressive enhancement -- Want your app to work without JavaScript -- Prefer action-based mutations following web conventions - -## Feature Deep Dives - -### Built-in Client-Side Caching - -**TanStack Start** includes powerful built-in SWR (stale-while-revalidate) caching through TanStack Router: - -- **Out-of-the-box performance** - Loader data is automatically cached and revalidated -- **Fine-grained control** - Configure `staleTime`, `gcTime`, and revalidation per route -- **Structural sharing** - Efficient updates that only re-render what changed -- **Official integrations** - Turn-key support for TanStack Query, Apollo, and other data fetching libraries -- **More performant** - Optimized for the user experience with instant navigation and background updates - -```tsx -export const Route = createFileRoute('/posts/$postId')({ - loader: async ({ params }) => fetchPost(params.postId), - staleTime: 10_000, // Consider fresh for 10 seconds - gcTime: 5 * 60_000, // Keep in memory for 5 minutes -}) -``` - -For advanced scenarios, TanStack Start integrates seamlessly with TanStack Query: - -```tsx -import { queryOptions } from '@tanstack/react-query' - -const postQueryOptions = (postId: string) => - queryOptions({ - queryKey: ['post', postId], - queryFn: () => fetchPost(postId), - }) - -export const Route = createFileRoute('/posts/$postId')({ - loader: ({ context, params }) => - context.queryClient.ensureQueryData(postQueryOptions(params.postId)), -}) - -function Post() { - const { postId } = Route.useParams() - const { data } = useQuery(postQueryOptions(postId)) - // Automatically uses cached data from loader -} -``` - -**Next.js** has basic fetch caching but lacks fine-grained control and requires manual integration with libraries like React Query. - -**React Router** doesn't have built-in client-side caching - you need to manually integrate a caching solution. - -### Server Functions vs Server Actions - -**TanStack Start Server Functions**: - -```tsx -export const getTodos = createServerFn({ method: 'GET' }) - .validator(zodValidator(z.object({ userId: z.string() }))) - .middleware([authMiddleware]) - .handler(async ({ data, context }) => { - // Fully typed data and context - return db.todos.findMany({ where: { userId: data.userId } }) - }) - -// Call from anywhere with full type safety -const todos = await getTodos({ data: { userId: '123' } }) -``` - -**Next.js Server Actions**: - -```tsx -'use server' -export async function getTodos(userId: string) { - // Runs on server, called from client - return db.todos.findMany({ where: { userId } }) -} - -// Call from client component -const todos = await getTodos('123') -``` - -Key differences: - -- Start's server functions support both client and server middleware -- Start has built-in input validation -- Start's approach is more explicit about the client/server boundary -- Start's server functions support both GET and POST methods (configurable via the `method` option, defaults to GET), while Next.js Server Actions only support POST. -- Next.js Server Actions integrate more seamlessly with forms - -### Middleware Architecture - -**TanStack Start** has two types of middleware: - -1. **Request Middleware**: Runs for all requests (SSR, API routes, server functions) -2. **Server Function Middleware**: Runs specifically for server functions, supports both client-side and server-side execution - -This composability allows for: - -```tsx -const authMiddleware = createMiddleware({ type: 'function' }) - .client(async ({ next }) => { - // Run auth checks on client - return next({ - headers: { Authorization: `Bearer ${getToken()}` }, - }) - }) - .server(async ({ next }) => { - // Validate auth on server - return next({ context: { user: await getUser() } }) - }) -``` - -**Next.js** has a single middleware.ts file that runs on the Edge Runtime for all requests. It cannot access server-only resources like databases and has limitations compared to the Node.js runtime. - -### Deployment Flexibility - -**TanStack Start** leverages modern build tool ecosystems: - -- Deploy to Cloudflare Workers, Netlify, Vercel, Railway, Fly.io, AWS, etc. -- Use Nitro for universal deployment support -- No vendor-specific features or lock-in -- Same codebase works everywhere - -**Next.js** is optimized for Vercel: - -- Many features work best or only on Vercel (ISR, Image Optimization, Middleware) -- Self-hosting requires more configuration -- Deployment to other platforms may have limitations - -## React Server Components (RSC) - -**Current Status**: - -- **Next.js**: Full production support with extensive ecosystem -- **TanStack Start**: Experimental support available -- **React Router**: Experimental support available - -TanStack Start's RSC implementation takes a client-led composition approach: server components are treated as data that the client can fetch, cache, and compose. See the [Server Components guide](/start/latest/docs/framework/react/guide/server-components) for details. +Deployment support depends on the adapter, runtime, and features you use. Check streaming, image processing, filesystem access, background work, and shared-cache behavior on your chosen target. Next.js self-hosting includes image optimization and ISR configuration; those features should not be labeled Vercel-only. ## Performance Considerations -### Production Performance +This page does not establish a performance winner. Startup time, HMR, memory use, JavaScript shipped, and response latency require separate measurements. Comparing a router package's bundle size with an entire framework is not a valid application benchmark. -All three frameworks are capable of achieving excellent production performance and top Lighthouse scores. The differences come down to optimization strategies: +For a useful comparison, build the same representative application with recommended patterns in each framework. Record package versions, hardware, dependencies, route count, rendering and caching settings, deployment target, warm and cold runs, and the raw results. -- **TanStack Start**: Optimized bundler builds, SWR caching reduces server load, lightweight runtime -- **Next.js**: Automatic code splitting, image optimization, and built-in performance features -- **React Router**: Web standards-based caching and optimization +## When to Choose Each Framework -### Development Performance +- **TanStack Start:** you want typed route context and URL state, explicit loaders and server functions, and control over per-route rendering. +- **Next.js:** you want its Server Component model and integrated image, font, metadata, and form facilities. Existing team experience and integrations can also make staying with Next.js the better choice. +- **React Router Framework Mode:** you want route loaders and actions, fetchers, and form-driven workflows. Read its [progressive enhancement guide](https://reactrouter.com/explanation/progressive-enhancement) if operation before JavaScript loads matters to your application. -This is where the frameworks differ significantly: - -**TanStack Start & React Router:** - -- ⚡ **Instant dev server startup** - Vite and Rsbuild start quickly -- ⚡ **Lightning-fast HMR** - Changes reflect instantly without page refresh -- ⚡ **Fast dev navigation** - Full-speed routing during development -- ⚡ **Lightweight resource usage** - Minimal CPU and RAM consumption -- ⚡ **High dev throughput** - Handle many concurrent requests efficiently - -**Next.js:** - -- 🐌 **Slow dev server startup** - Can take many seconds to start, especially on larger projects -- 🐌 **Slow HMR** - Hot reloading is noticeably sluggish even with Turbopack -- 🐌 **Throttled dev navigation** - Navigation is artificially slowed during development -- 🐌 **Heavy resource usage** - Significant CPU and RAM consumption during development - -**Why This Matters:** - -Development performance directly impacts developer productivity. Faster feedback loops mean: - -- More iterations per hour -- Better flow state and focus -- Lower machine requirements -- Reduced frustration during development -- Faster CI/CD pipelines for development builds - -While Next.js's production performance is excellent, the development experience can be notably slower, especially on larger codebases or less powerful machines. - -## Community and Ecosystem - -- **Next.js**: Largest community, most third-party integrations, extensive learning resources -- **React Router**: One of the oldest and most widely used React libraries, strong community, excellent documentation -- **TanStack Start**: Growing community, part of TanStack ecosystem, excellent Discord support - -## Maturity - -- **Next.js**: Production-ready, used by thousands of companies, proven at scale -- **React Router**: Production-ready, powers millions of apps, v7 Framework Mode is the evolution of Remix -- **TanStack Start**: Release Candidate stage, feature-complete, rapidly stabilizing toward v1 - -[bp-tanstack-router]: https://badgen.net/bundlephobia/minzip/@tanstack/react-router -[bpl-tanstack-router]: https://bundlephobia.com/result?p=@tanstack/react-router -[gh-tanstack-router]: https://github.com/tanstack/router -[stars-tanstack-router]: https://img.shields.io/github/stars/tanstack/router?label=%F0%9F%8C%9F -[router-comparison]: /router/latest/docs/framework/react/comparison -[_]: _ -[nextjs]: https://nextjs.org/ -[gh-nextjs]: https://github.com/vercel/next.js -[stars-nextjs]: https://img.shields.io/github/stars/vercel/next.js?label=%F0%9F%8C%9F -[_]: _ -[react-router]: https://reactrouter.com/ -[gh-react-router]: https://github.com/remix-run/react-router -[stars-react-router]: https://img.shields.io/github/stars/remix-run/react-router?label=%F0%9F%8C%9F +Check Start's [overview](./overview) and [Server Components guide](./guide/server-components) for current release and experimental-feature status before adopting those features. To try Start, use [Getting Started](./getting-started) or [Migrate from Next.js](./migrate-from-next-js). diff --git a/docs/start/framework/react/getting-started.md b/docs/start/framework/react/getting-started.md index 565dc4b4cf..6e5bcd8841 100644 --- a/docs/start/framework/react/getting-started.md +++ b/docs/start/framework/react/getting-started.md @@ -3,6 +3,7 @@ id: getting-started title: Getting Started redirect_from: - /framework/react/quick-start +description: Create a TanStack Start application with TanStack Builder, the CLI, or a working example, then run it locally and start adding routes. --- ## Start a new project @@ -39,6 +40,7 @@ To use a different example, replace `start-basic` with one of the slugs below. #### Examples - [Basic](https://github.com/TanStack/router/tree/main/examples/react/start-basic) (`start-basic`) +- [Basic + Rsbuild](https://github.com/TanStack/router/tree/main/examples/react/start-basic-rsbuild) (`start-basic-rsbuild`) - [Basic + Auth](https://github.com/TanStack/router/tree/main/examples/react/start-basic-auth) (`start-basic-auth`) - [Counter](https://github.com/TanStack/router/tree/main/examples/react/start-counter) (`start-counter`) - [Basic + React Query](https://github.com/TanStack/router/tree/main/examples/react/start-basic-react-query) (`start-basic-react-query`) diff --git a/docs/start/framework/react/guide/authentication-overview.md b/docs/start/framework/react/guide/authentication-overview.md index 8b5838a9f9..e80ba97f8c 100644 --- a/docs/start/framework/react/guide/authentication-overview.md +++ b/docs/start/framework/react/guide/authentication-overview.md @@ -1,8 +1,11 @@ --- id: authentication-overview -title: Authentication +title: Choose Authentication for React Apps +description: Compare hosted services, auth libraries, and custom authentication for React apps built with TanStack Start. Choose an approach before implementing sessions and authorization. --- +Choose how your React app will handle identity, sessions, and permissions. This page compares approaches and providers. Once you have chosen an approach, use [Implement Authentication in React](./authentication.md) for the application workflow. + ## Authentication vs Authorization - **Authentication**: Who is this user? (Login/logout, identity verification) @@ -113,7 +116,7 @@ Build your own authentication system using TanStack Start's server functions and - **Full Control**: Complete customization over authentication flow - **Server Primitives**: Sessions, OAuth, CSRF, rate limiting — see [Authentication Server Primitives](./authentication-server-primitives.md) -- **Session Management**: HTTP-only cookies via `setResponseHeader`, read with `getRequestHeader` +- **Session Management**: HTTP-only cookies written with `setCookie`, read with `getCookie` - **Type Safety**: End-to-end type safety for authentication state ### 🌐 Other Excellent Options diff --git a/docs/start/framework/react/guide/authentication-server-primitives.md b/docs/start/framework/react/guide/authentication-server-primitives.md index 20cc143d2f..103e9c4455 100644 --- a/docs/start/framework/react/guide/authentication-server-primitives.md +++ b/docs/start/framework/react/guide/authentication-server-primitives.md @@ -3,7 +3,7 @@ id: authentication-server-primitives title: Authentication Server Primitives --- -This guide covers the **server-side primitives** for building authentication in TanStack Start: session cookies, session lookup, OAuth, password-reset hardening, CSRF, and rate limiting. It pairs with the [routing-side guide](../../../../router/guide/authenticated-routes.md) (`_authenticated` layout, `beforeLoad`, redirects, RBAC). +This guide covers the **server-side primitives** for building authentication in TanStack Start: session cookies, session lookup, OAuth, password-reset hardening, CSRF, and rate limiting. It pairs with the [routing-side guide](/router/latest/docs/framework/react/guide/authenticated-routes) (`_authenticated` layout, `beforeLoad`, redirects, RBAC). If you can use a managed solution like [Clerk](https://go.clerk.com/wOwHtuJ) or [WorkOS](https://workos.com/), prefer that — they handle most of what this guide describes. Read on if you're rolling your own. @@ -28,47 +28,39 @@ Whichever you choose, the cookie flags matter: ```ts // src/server/session.ts import { - getRequestHeader, - setResponseHeader, + deleteCookie, + getCookie, + setCookie, } from '@tanstack/react-start/server' const SESSION_COOKIE = '__Host-session' const ONE_DAY = 60 * 60 * 24 +const sessionCookieOptions = { + httpOnly: true, + secure: true, + sameSite: 'lax', + path: '/', +} as const + export function setSessionCookie(token: string) { - setResponseHeader( - 'Set-Cookie', - [ - `${SESSION_COOKIE}=${token}`, - `HttpOnly`, - `Secure`, - `SameSite=Lax`, - `Path=/`, - `Max-Age=${ONE_DAY}`, - ].join('; '), - ) + setCookie(SESSION_COOKIE, token, { + ...sessionCookieOptions, + maxAge: ONE_DAY, + }) } export function clearSessionCookie() { - setResponseHeader( - 'Set-Cookie', - `${SESSION_COOKIE}=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0`, - ) + deleteCookie(SESSION_COOKIE, sessionCookieOptions) } export function readSessionToken(): string | null { - const header = getRequestHeader('cookie') - if (!header) return null - for (const part of header.split(/;\s*/)) { - // Split only on the FIRST '=' — signed/base64 values often contain '='. - const eq = part.indexOf('=') - if (eq === -1) continue - if (part.slice(0, eq) === SESSION_COOKIE) return part.slice(eq + 1) - } - return null + return getCookie(SESSION_COOKIE) ?? null } ``` +Write cookies with `setCookie` (or `appendResponseHeader('set-cookie', serialized)` for a cookie that a library already serialized). Do not use `setResponseHeader('Set-Cookie', ...)` for this: it replaces every cookie on the outgoing response, including cookies set by other middleware or returned by a handler. + | Flag | Why | | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `HttpOnly` | JavaScript can't read the cookie. An XSS bug can't exfiltrate the session. | @@ -169,7 +161,7 @@ For OAuth authorization-code flow: // src/server/oauth.functions.ts import { createServerFn } from '@tanstack/react-start' import { redirect } from '@tanstack/react-router' -import { setResponseHeader } from '@tanstack/react-start/server' +import { setCookie } from '@tanstack/react-start/server' import crypto from 'node:crypto' const OAUTH_STATE_COOKIE = '__Host-oauth' @@ -190,10 +182,13 @@ export const startOAuth = createServerFn({ method: 'GET' }).handler( crypto.createHash('sha256').update(verifier).digest(), ) - setResponseHeader( - 'Set-Cookie', - `${OAUTH_STATE_COOKIE}=${signed({ state, verifier })}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=600`, - ) + setCookie(OAUTH_STATE_COOKIE, signed({ state, verifier }), { + httpOnly: true, + secure: true, + sameSite: 'lax', + path: '/', + maxAge: 600, + }) throw redirect({ href: @@ -349,7 +344,7 @@ See [Execution Model: Module-Level `process.env` Reads](./execution-model.md#mod ## See Also - [Authentication Overview](./authentication-overview.md) — choosing between partner solutions, OSS libraries, and DIY. -- [Authenticated Routes (Router)](../../../../router/guide/authenticated-routes.md) — the routing-side guide. +- [Authenticated Routes (Router)](/router/latest/docs/framework/react/guide/authenticated-routes) — the routing-side guide. - [Server Functions](./server-functions.md) — the RPC primitive that auth lives inside. - [Middleware](./middleware.md) — composing `authMiddleware`. - [OWASP Cheat Sheets — Authentication](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html), [Session Management](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html), [CSRF](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html). diff --git a/docs/start/framework/react/guide/authentication.md b/docs/start/framework/react/guide/authentication.md index da839e1fbe..c77c681ee0 100644 --- a/docs/start/framework/react/guide/authentication.md +++ b/docs/start/framework/react/guide/authentication.md @@ -1,11 +1,12 @@ --- id: authentication -title: Authentication +title: Implement Authentication in React +description: Implement sessions, sign-in, sign-out, protected routes, and server-side authorization in a TanStack Start React app. --- -This guide covers authentication patterns and shows how to implement your own authentication system with TanStack Start. +Implement the authentication workflow in your React app, from sessions and sign-in to protected routes and authorization. -> **📋 Before You Start:** Check our [Authentication Overview](./authentication-overview.md) for all available options including partner solutions and hosted services. +To compare libraries and hosted services, read [Choose Authentication for React Apps](./authentication-overview.md). ## Authentication Approaches @@ -34,7 +35,7 @@ Authentication involves many considerations including password security, session - **Authentication**: Who is this user? (Login/logout) - **Authorization**: What can this user do? (Permissions/roles) -TanStack Start provides the tools for both through server functions, sessions, and route protection. +TanStack Start provides server functions, request and cookie utilities, and route protection. Session storage and authentication come from your application or a library you choose. > Protect the data/API boundary first. Any server function, server route, or other API endpoint that returns or mutates private data must authorize the request itself. `beforeLoad` is useful for route UX: it keeps users out of screens they cannot use and avoids triggering work that would fail anyway. It is not the security boundary for the data. See [Authentication Server Primitives](./authentication-server-primitives.md) for the server-side pattern. @@ -47,6 +48,7 @@ Server functions handle sensitive authentication logic securely on the server: ```tsx import { createServerFn } from '@tanstack/react-start' import { redirect } from '@tanstack/react-router' +import { getAppSession } from '~/utils/session' // Login server function export const loginFn = createServerFn({ method: 'POST' }) @@ -60,11 +62,9 @@ export const loginFn = createServerFn({ method: 'POST' }) } // Create session - const session = await useAppSession() - await session.update({ - userId: user.id, - email: user.email, - }) + const session = await getAppSession() + session.userId = user.id + await session.save() // Redirect to protected area throw redirect({ to: '/dashboard' }) @@ -72,98 +72,131 @@ export const loginFn = createServerFn({ method: 'POST' }) // Logout server function export const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await useAppSession() - await session.clear() + const session = await getAppSession() + session.destroy() throw redirect({ to: '/' }) }) // Get current user export const getCurrentUserFn = createServerFn({ method: 'GET' }).handler( async () => { - const session = await useAppSession() - const userId = session.data.userId + const session = await getAppSession() + const userId = session.userId if (!userId) { return null } - return await getUserById(userId) + const user = await getUserById(userId) + return user ? { id: user.id, email: user.email, role: user.role } : null }, ) ``` ### 2. Session Management -TanStack Start provides secure HTTP-only cookie sessions: +Start does not provide a session API. This guide uses iron-session for encrypted cookie sessions. Start's cookie helpers connect it to server functions, server routes, and request middleware. + +For encrypted cookie sessions, install [iron-session](https://github.com/vvo/iron-session): + +```sh +pnpm add iron-session +``` + +This example uses iron-session 9's cookie adapter. Its Node runtime requires Node 22.13 or newer; check the library's runtime requirements for other deployment targets. ```tsx -// utils/session.ts -import { useSession } from '@tanstack/react-start/server' +// utils/session.ts — import only from server code +import { getIronSession } from 'iron-session' +import { getCookie, setCookie } from '@tanstack/react-start/server' type SessionData = { - userId?: string - email?: string - role?: string + userId: string + oauthState: string } -export function useAppSession() { - return useSession({ - // Session configuration - name: 'app-session', - password: process.env.SESSION_SECRET!, // At least 32 characters - // Optional: customize cookie settings - cookie: { - secure: process.env.NODE_ENV === 'production', - sameSite: 'lax', - httpOnly: true, +export function getAppSession(ttl = 7 * 24 * 60 * 60) { + const password = process.env.SESSION_SECRET + if (!password || password.length < 32) { + throw new Error('SESSION_SECRET must be at least 32 characters') + } + + return getIronSession( + { read: getCookie, write: setCookie }, + { + cookieName: 'app-session', + password, + ttl, + cookieOptions: { + secure: process.env.NODE_ENV === 'production', + sameSite: 'lax', + httpOnly: true, + path: '/', + }, }, - }) + ) } ``` +Read fields directly from the returned session, change them, then `await session.save()` before returning or redirecting. Missing or expired sessions have no user ID. `session.destroy()` removes the browser cookie. Keep one session object for the operation; another call to `getAppSession()` reads the incoming request again. For middleware, pass that object through request context when downstream code needs the same mutations. + +The `getAppSession` helper belongs to your application. Start does not cache sessions, choose expiration rules, or synchronize concurrent writes. Keep secrets and session objects in server code, and read request-specific configuration inside the active request. + ### 3. Authentication Context -Share authentication state across your application: +Load the current user in your root route's `beforeLoad` so the initial server render and child routes receive the same authentication state. `useServerFn` returns a callable function, not an object with `data`, `isLoading`, or `refetch`. You can call a server function directly from `beforeLoad`. + +Merge this pattern into your existing root route, keeping its metadata and document shell: ```tsx -// contexts/auth.tsx -import { createContext, useContext, ReactNode } from 'react' -import { useServerFn } from '@tanstack/react-start' +// routes/__root.tsx +import { + createRootRoute, + HeadContent, + Outlet, + Scripts, +} from '@tanstack/react-router' +import type { ReactNode } from 'react' import { getCurrentUserFn } from '../server/auth' -type User = { - id: string - email: string - role: string -} - -type AuthContextType = { - user: User | null - isLoading: boolean - refetch: () => void -} - -const AuthContext = createContext(undefined) - -export function AuthProvider({ children }: { children: ReactNode }) { - const { data: user, isLoading, refetch } = useServerFn(getCurrentUserFn) +export const Route = createRootRoute({ + headers: () => ({ 'Cache-Control': 'private, no-store' }), + beforeLoad: async () => ({ user: await getCurrentUserFn() }), + component: Outlet, + shellComponent: RootDocument, +}) +function RootDocument({ children }: { children: ReactNode }) { return ( - - {children} - + + + + + + {children} + + + ) } +``` -export function useAuth() { - const context = useContext(AuthContext) - if (!context) { - throw new Error('useAuth must be used within AuthProvider') - } - return context +The root includes session-specific data, so its responses use `Cache-Control: private, no-store`. Keep that policy on child routes that render this data, and do not override it with public caching at your CDN. + +Read that state from a descendant component: + +```tsx +// components/AuthStatus.tsx +import { Route } from '../routes/__root' + +export function AuthStatus() { + const { user } = Route.useRouteContext() + return {user ? user.email : 'Signed out'} } ``` +After login or logout changes the session, call `await router.invalidate()` to reload the current user and rerun route guards. Keep private-data authorization in the server function itself, even when a route already checks the user. + ### 4. Route Protection Protect routes using `beforeLoad`: @@ -240,8 +273,9 @@ export const registerFn = createServerFn({ method: 'POST' }) }) // Create session - const session = await useAppSession() - await session.update({ userId: user.id }) + const session = await getAppSession() + session.userId = user.id + await session.save() return { success: true, user: { id: user.id, email: user.email } } }) @@ -309,8 +343,9 @@ export const initiateOAuthFn = createServerFn({ method: 'POST' }) const state = generateRandomState() // Store state in session for CSRF protection - const session = await useAppSession() - await session.update({ oauthState: state }) + const session = await getAppSession() + session.oauthState = state + await session.save() // Generate OAuth URL const authUrl = generateOAuthUrl(provider, state) @@ -373,21 +408,9 @@ const hashedPassword = await bcrypt.hash(password, saltRounds) ### 2. Session Security -```tsx -// Use secure session configuration -export function useAppSession() { - return useSession({ - name: 'app-session', - password: process.env.SESSION_SECRET!, // 32+ characters - cookie: { - secure: process.env.NODE_ENV === 'production', // HTTPS only in production - sameSite: 'lax', // CSRF protection - httpOnly: true, // XSS protection - maxAge: 7 * 24 * 60 * 60, // 7 days - }, - }) -} -``` +Set the library's server-validated expiration as well as appropriate cookie attributes. In the iron-session example, `ttl` limits a sealed credential's lifetime from its latest save; saving again renews it. A numeric `cookieOptions.maxAge` controls browser retention. In iron-session 9, explicitly setting `maxAge: undefined` also disables seal expiry; omit the property to use the configured `ttl`. Use an application-validated timestamp or a server-side record if you also need an absolute lifetime that writes cannot extend. + +Use `httpOnly`, `sameSite`, and `path` deliberately, and require `secure: true` on HTTPS deployments. These cookie attributes complement server-side authorization and CSRF protections. Keep only the minimum session data and load current account permissions from their authoritative store. Logout removes a stateless cookie from the current browser; it cannot revoke a copy without server-side state. ### 3. Rate Limiting @@ -489,28 +512,69 @@ describe('Authentication Flow', () => { ### Loading States +Call the function returned by `useServerFn` with `{ data }`. Track pending state in the component, handle invalid credentials, and refresh route context after a successful login. This form uses the `loginFn` from the server-functions example above. It requires JavaScript, so the fields stay disabled until hydration; `method="post"` also prevents credentials appearing in a native GET submission. + ```tsx -function LoginForm() { +// components/LoginForm.tsx +import { useState } from 'react' +import type { FormEvent } from 'react' +import { useHydrated, useRouter } from '@tanstack/react-router' +import { useServerFn } from '@tanstack/react-start' +import { loginFn } from '../server/auth' + +export function LoginForm() { + const hydrated = useHydrated() const [isLoading, setIsLoading] = useState(false) - const loginMutation = useServerFn(loginFn) + const [error, setError] = useState('') + const login = useServerFn(loginFn) + const router = useRouter() + + const handleSubmit = async (event: FormEvent) => { + event.preventDefault() + const formData = new FormData(event.currentTarget) + const email = formData.get('email') + const password = formData.get('password') + if (typeof email !== 'string' || typeof password !== 'string') { + return + } - const handleSubmit = async (data: LoginData) => { setIsLoading(true) + setError('') try { - await loginMutation.mutate(data) - } catch (error) { - // Handle error + const result = await login({ data: { email, password } }) + if (result?.error) { + setError(result.error) + return + } + await router.invalidate() + } catch { + setError('Login failed. Please try again.') } finally { setIsLoading(false) } } return ( - - {/* Form fields */} - + +
+ + + +
+

{error}

) } @@ -525,16 +589,14 @@ export const loginFn = createServerFn({ method: 'POST' }) ) .handler(async ({ data }) => { const user = await authenticateUser(data.email, data.password) - if (!user) return { error: 'Invalid credentials' } + if (!user) { + return { error: 'Invalid credentials' } + } - const session = await useAppSession() - await session.update( - { userId: user.id }, - { - // Extend session if remember me is checked - maxAge: data.rememberMe ? 30 * 24 * 60 * 60 : undefined, // 30 days vs session - }, - ) + const ttl = data.rememberMe ? 30 * 24 * 60 * 60 : 8 * 60 * 60 + const session = await getAppSession(ttl) + session.userId = user.id + await session.save() return { success: true } }) @@ -562,7 +624,6 @@ If you're migrating from client-side authentication (localStorage, context only) ### From Other Frameworks - **Next.js**: Replace API routes with server functions, migrate NextAuth sessions -- **Remix**: Convert loaders/actions to server functions, adapt session patterns - **SvelteKit**: Move form actions to server functions, update route protection ## Production Considerations diff --git a/docs/start/framework/react/guide/cdn-asset-urls.md b/docs/start/framework/react/guide/cdn-asset-urls.md index 28c9c8c030..ac5f3e7b57 100644 --- a/docs/start/framework/react/guide/cdn-asset-urls.md +++ b/docs/start/framework/react/guide/cdn-asset-urls.md @@ -3,8 +3,6 @@ id: cdn-asset-urls title: CDN Asset URLs --- -# CDN Asset URLs - > **Experimental:** `transformAssets` is experimental and subject to change. Use this guide when you need TanStack Start to rewrite manifest-managed asset URLs at runtime. The most common use case is serving JavaScript and CSS from a CDN whose origin is known only when the server starts, or varies per request. diff --git a/docs/start/framework/react/guide/client-entry-point.md b/docs/start/framework/react/guide/client-entry-point.md index 02d0ecd426..3d81a13ac2 100644 --- a/docs/start/framework/react/guide/client-entry-point.md +++ b/docs/start/framework/react/guide/client-entry-point.md @@ -3,8 +3,6 @@ id: client-entry-point title: Client Entry Point --- -# Client Entry Point - > [!NOTE] > The client entry point is **optional** out of the box. If not provided, TanStack Start will automatically handle the client entry point for you using the below as a default. diff --git a/docs/start/framework/react/guide/databases.md b/docs/start/framework/react/guide/databases.md index cbafa13f51..774a9df61b 100644 --- a/docs/start/framework/react/guide/databases.md +++ b/docs/start/framework/react/guide/databases.md @@ -1,6 +1,7 @@ --- id: databases title: Databases +description: Connect a database to TanStack Start through server functions and server routes, and compare supported database providers. --- Databases are at the core of any dynamic application, providing the necessary infrastructure to store, retrieve, and manage data. TanStack Start makes it easy to integrate with a variety of databases, offering a flexible approach to managing your application's data layer. diff --git a/docs/start/framework/react/guide/deferred-hydration.md b/docs/start/framework/react/guide/deferred-hydration.md index 1dc4760fa7..ba07d65b24 100644 --- a/docs/start/framework/react/guide/deferred-hydration.md +++ b/docs/start/framework/react/guide/deferred-hydration.md @@ -244,7 +244,7 @@ chunks only exist when `split` is enabled, so TypeScript rejects strategy-form Use procedural prefetch when you need custom work: ```tsx -import { useQueryClient } from '@tanstack/react-query' +import { noop, useQueryClient } from '@tanstack/react-query' import { Hydrate } from '@tanstack/react-start' import { visible } from '@tanstack/react-start/hydration' @@ -255,8 +255,10 @@ function DeferredReviews() { { - await preload() - await queryClient.prefetchQuery(reviewsQueryOptions) + await Promise.all([ + preload(), + queryClient.query(reviewsQueryOptions).catch(noop), + ]) }} > diff --git a/docs/start/framework/react/guide/early-hints.md b/docs/start/framework/react/guide/early-hints.md index da633a84d7..2341215022 100644 --- a/docs/start/framework/react/guide/early-hints.md +++ b/docs/start/framework/react/guide/early-hints.md @@ -3,8 +3,6 @@ id: early-hints title: Early Hints --- -# Early Hints - > **Experimental:** Early Hints are experimental and subject to change. HTTP `103 Early Hints` lets your server tell the browser about important resources before the final HTML response is ready. TanStack Start can collect route assets and route `head().links`, then call your server entry so your runtime can send `103` responses. @@ -166,6 +164,7 @@ Static Early Hints are collected from the final Start manifest resolved for the - CDN URL rewrites are reflected in Early Hints. - `crossOrigin` returned from `transformAssets` is reflected in Early Hints. - JavaScript hints follow the client output format: `modulepreload` for module output, or `preload; as=script` for IIFE output. +- JavaScript hints carry `fetchpriority=low`, matching the generated HTML preload links, so they don't compete with render-blocking stylesheets. - Per-request transforms with `cache: false` are reflected in Early Hints for that request. - Inlined CSS assets are skipped when Start's [CSS inlining](./css-styling#inline-route-css-in-production) build option inlines them into the HTML. diff --git a/docs/start/framework/react/guide/environment-functions.md b/docs/start/framework/react/guide/environment-functions.md index f472a3a26a..94fbb52501 100644 --- a/docs/start/framework/react/guide/environment-functions.md +++ b/docs/start/framework/react/guide/environment-functions.md @@ -121,3 +121,37 @@ Environment functions are tree-shaken based on the environment for each bundle p Functions created using `createIsomorphicFn()` are tree-shaken. All codes inside `.client()` are not included in server bundle, and vice-versa. On the server, functions created using `createClientOnlyFn()` are replaced with a function that throws an `Error` on the server. The reverse is true for `createServerOnlyFn` functions on the client. + +## Troubleshooting + +### A loader works on refresh but throws during navigation + +If a loader throws `createServerOnlyFn() functions can only be called on the server!` after clicking a link, check whether it calls a server-only helper directly. Route loaders also run in the browser during client navigation. `createServerOnlyFn` guards a local function, it does not send a request to the server. + +Wrap the server work in `createServerFn` and call that function from the loader: + +```tsx +import { createFileRoute } from '@tanstack/react-router' +import { createServerFn, createServerOnlyFn } from '@tanstack/react-start' + +const readOnlyOnServer = createServerOnlyFn(() => 'Read on the server') +const readThroughRpc = createServerFn().handler(() => readOnlyOnServer()) + +export const Route = createFileRoute('/example')({ + loader: () => readThroughRpc(), +}) +``` + +The server function runs directly during SSR and makes a request to the server when called in the browser. Test both a direct page request and navigation from another route. A successful refresh alone does not exercise the browser loader. + +The [execution-boundary tests](https://github.com/TanStack/router/blob/main/e2e/react-start/basic/tests/environment-functions.spec.ts) include the failing direct call and the working server-function version. See [Server Functions](./server-functions.md) for validation and middleware when the function accepts user input. + +### Browser code throws `window is not defined` on the server + +This means browser-only code ran during server execution. Use the stack trace to find the first application or dependency module that reads `window`, `document`, or another browser API. + +For a browser-only component, render it inside `ClientOnly` from `@tanstack/react-router` with a useful fallback. The Start compiler removes its children from the server bundle, which lets the bundler remove imports used only by those children. The [ClientOnly example](https://github.com/TanStack/router/blob/main/e2e/react-start/basic/src/routes/client-only.tsx) covers a component that reads `window` at module scope, and its [tests](https://github.com/TanStack/router/blob/main/e2e/react-start/basic/tests/client-only.spec.ts) check the server fallback and hydrated content. + +A browser API used elsewhere, such as a route loader or server function, still needs the correct execution boundary. Move component side effects into an effect or event handler. For logic that needs different server and browser implementations, use `createIsomorphicFn` with both implementations. Wrapping a function in `createClientOnlyFn` does not defer its call until the browser, calling that wrapper on the server throws the client-only guard error instead. + +If the stack points into build tooling or the error persists in a minimal app with the correct boundary, include that app and the installed Start and bundler versions in a [bug report](https://github.com/TanStack/router/issues/new/choose). A compiler or dependency bug needs a reproducible fix, not a blanket change to rendering mode. diff --git a/docs/start/framework/react/guide/environment-variables.md b/docs/start/framework/react/guide/environment-variables.md index 8953c0a099..f1f6851602 100644 --- a/docs/start/framework/react/guide/environment-variables.md +++ b/docs/start/framework/react/guide/environment-variables.md @@ -394,14 +394,14 @@ Use Zod for runtime validation of environment variables: import { z } from 'zod' const envSchema = z.object({ - DATABASE_URL: z.string().url(), + DATABASE_URL: z.url(), JWT_SECRET: z.string().min(32), NODE_ENV: z.enum(['development', 'production', 'test']), }) const clientEnvSchema = z.object({ VITE_APP_NAME: z.string(), - VITE_API_URL: z.string().url(), + VITE_API_URL: z.url(), VITE_AUTH0_DOMAIN: z.string(), VITE_AUTH0_CLIENT_ID: z.string(), }) diff --git a/docs/start/framework/react/guide/hosting.md b/docs/start/framework/react/guide/hosting.md index aa1806c6bf..2d02f881b3 100644 --- a/docs/start/framework/react/guide/hosting.md +++ b/docs/start/framework/react/guide/hosting.md @@ -1,6 +1,7 @@ --- id: hosting title: Hosting +description: Deploy TanStack Start with Vite or Rsbuild using hosting guides for Cloudflare, Netlify, Railway, Vercel, Node.js, and other runtimes. --- Hosting is the process of deploying your application to the internet so that users can access it. This is a critical part of any web development project, ensuring your application is available to the world. TanStack Start supports Vite and Rsbuild, giving you flexible build outputs for different hosting providers and runtimes. @@ -115,6 +116,32 @@ Deploy your application to Cloudflare Workers using their one-click deployment p A full TanStack Start example for Cloudflare Workers is available [here](https://github.com/TanStack/router/tree/main/examples/react/start-basic-cloudflare). +#### Deployment fails even though the Vite build succeeds + +If Wrangler reports a missing server entry or unresolved Start virtual modules, check whether your deployment command passes `--config wrangler.jsonc`. With the Cloudflare Vite plugin, that file is the build input. The plugin generates a deployment config with the built server entry and client assets, then writes `.wrangler/deploy/config.json` so Wrangler can find it. Forcing Wrangler to read the source config bypasses that redirect. + +Run these commands from the application directory to validate the generated deployment without publishing: + +```sh +pnpm run build +pnpm exec wrangler deploy --dry-run +``` + +Check that Wrangler reports the generated config under `dist`, rather than just the source `wrangler.jsonc`. Keep the source `main` set to `@tanstack/react-start/server-entry` or your custom server entry, and let the Vite plugin generate the deployment entry. Marking unresolved Start modules as external does not fix the missing build transformation. + +If your build and deployment run in separate jobs, preserve the build output and `.wrangler/deploy/config.json` with their relative paths, or explicitly pass the generated deployment config. Do not edit generated files to repair the source configuration. See Cloudflare's [generated configuration documentation](https://developers.cloudflare.com/workers/wrangler/configuration/#generated-configuration) for how Wrangler finds that output. + +For a named Cloudflare environment, select it when building. For example, if `env.staging` is defined in your source config: + +```sh +CLOUDFLARE_ENV=staging pnpm run build +pnpm exec wrangler deploy --dry-run +``` + +The plugin resolves the environment into the generated config. A later `wrangler deploy --env staging` does not select a different built environment. See [Cloudflare environments](https://developers.cloudflare.com/workers/vite-plugin/reference/cloudflare-environments/). + +The [Cloudflare fixture tests](https://github.com/TanStack/router/blob/main/e2e/react-start/basic-cloudflare/tests/app.spec.ts) exercise a generated-config dry run and preview the built app locally. A dry run validates packaging, it does not verify account permissions, a live domain, or deployed bindings. + ### Netlify ⭐ _Official Partner_
@@ -474,7 +501,7 @@ In your Appwrite project, navigate to the **Sites** page from the sidebar. Click 3. Confirm the build settings: - **Install command:** `npm install` - **Build command:** `npm run build` - - **Output directory:** `./dist` (if you're using Nitro v2 or v3, this should be `./.output`) + - **Output directory:** `./dist` (if you're using Nitro, this should be `./.output`) 4. Add any required **environment variables** 5. Click **Deploy** diff --git a/docs/start/framework/react/guide/import-protection.md b/docs/start/framework/react/guide/import-protection.md index 8bf47c729a..451d405f81 100644 --- a/docs/start/framework/react/guide/import-protection.md +++ b/docs/start/framework/react/guide/import-protection.md @@ -3,8 +3,6 @@ id: import-protection title: Import Protection --- -> **Experimental:** Import protection is experimental and subject to change. - Import protection prevents server-only code from leaking into client bundles and client-only code from leaking into server bundles. It runs inside TanStack Start and is enabled by default. ## How It Works diff --git a/docs/start/framework/react/guide/isr.md b/docs/start/framework/react/guide/isr.md index 5704af1a11..98007d3f15 100644 --- a/docs/start/framework/react/guide/isr.md +++ b/docs/start/framework/react/guide/isr.md @@ -492,5 +492,5 @@ Track key metrics: - [Static Prerendering](./static-prerendering.md) - Build-time page generation - [Hosting](./hosting.md) - CDN deployment configurations - [Server Functions](./server-functions.md) - Creating dynamic data endpoints -- [Data Loading](../../../../router/guide/data-loading.md) - Client-side cache control +- [Data Loading](/router/latest/docs/guide/data-loading) - Client-side cache control - [Middleware](./middleware.md) - Request/response customization diff --git a/docs/start/framework/react/guide/path-aliases.md b/docs/start/framework/react/guide/path-aliases.md index ff9735df83..bd75dc01ed 100644 --- a/docs/start/framework/react/guide/path-aliases.md +++ b/docs/start/framework/react/guide/path-aliases.md @@ -26,9 +26,7 @@ After updating your `tsconfig.json` file, configure your build tool so it resolv # Vite -## Vite 8 - -Vite 8+ has [built-in support for path aliases](https://vite.dev/config/shared-options#resolve-tsconfigpaths), which is disabled by default. To enable it, simply add the following configuration to your `vite.config.ts` file: +Vite has [built-in support for path aliases](https://vite.dev/config/shared-options#resolve-tsconfigpaths), which is disabled by default. To enable it, add the following configuration to your `vite.config.ts` file: ```ts // vite.config.ts @@ -42,31 +40,6 @@ export default defineConfig({ }) ``` -## Vite 7 and earlier - -For Vite 7 and earlier, install the `vite-tsconfig-paths` plugin to enable path aliases in your TanStack Start project. You can do this by running the following command: - -```sh -npm install -D vite-tsconfig-paths -``` - -Now, you'll need to update your `vite.config.ts` file to include the following: - -```ts -// vite.config.ts -import { defineConfig } from 'vite' -import viteTsConfigPaths from 'vite-tsconfig-paths' - -export default defineConfig({ - plugins: [ - // this is the plugin that enables path aliases - viteTsConfigPaths({ - projects: ['./tsconfig.json'], - }), - ], -}) -``` - # Rsbuild Rsbuild reads the `paths` field from `tsconfig.json` by default. No extra config is needed when your aliases live in the root `tsconfig.json`. diff --git a/docs/start/framework/react/guide/production-checklist.md b/docs/start/framework/react/guide/production-checklist.md new file mode 100644 index 0000000000..b46cd70f2e --- /dev/null +++ b/docs/start/framework/react/guide/production-checklist.md @@ -0,0 +1,42 @@ +--- +id: production-checklist +title: Production Checklist +description: Check a TanStack Start production build for secret exposure, authorization, cache isolation, HTTP status codes, SEO, assets, logging, and deployment failures. +--- + +Run these checks against the production build and again through your public hostname. A passing development server does not verify your deployment adapter, runtime environment, or CDN. + +## Secrets and server boundaries + +- [ ] **Check required environment variables at runtime.** Start the production server with the same variable names and runtime bindings as your host. Missing configuration should fail clearly before it serves dependent requests. Look for undefined credentials, connections to a development database, or values that only existed during the build. See [Environment Variables](./environment-variables). +- [ ] **Keep secrets out of browser output.** Build with a harmless, unique test secret and search the emitted client files, source maps you publish, and response bodies for that value. Do not use a real secret for this check. A match means a value crossed the server boundary, even if its variable name lacks `VITE_`. Check server-function return values as well as imports. See [Environment Variables](./environment-variables#security-best-practices) and [Import Protection](./import-protection). + +## Authorization and mutations + +- [ ] **Test endpoints directly.** Record a private read and write, then repeat them while signed out and as a different account. Both must reject unauthorized access without changing data. A redirect in `beforeLoad` does not protect a separately callable endpoint. See [Authentication Server Primitives](./authentication-server-primitives#protect-data-first). +- [ ] **Exercise session expiry and sign-out.** Reload a private page, expire its session, sign out, and revisit it. Confirm the cookie's HTTPS flags and that old account data disappears from browser caches. Look for sessions that survive beyond your intended policy or another account's data appearing after switching accounts. See [Session Cookies](./authentication-server-primitives#session-cookies). +- [ ] **Reject invalid and cross-site writes.** Send malformed input and browser-like requests from an untrusted origin to each mutation entry point, including ordinary server-route forms. Use an authenticated test session for protected writes so an authentication failure cannot be mistaken for CSRF protection. Verify validation and your intended CSRF policy before any write occurs. Also test rapid or repeated submissions. A disabled button helps the interface, but the endpoint still needs its own checks. See [Authentication Server Primitives](./authentication-server-primitives) and [Server Functions](./server-functions). + +## Cache isolation and rendering + +- [ ] **Request the same private URL as two accounts concurrently.** Inspect each HTML response and any serialized loader or query data. Each response must contain only its own account's values. Repeat through the CDN and after a browser account switch. Shared personalized HTML or process-wide user caches are failures. See [Middleware](./middleware) and [Authentication Server Primitives](./authentication-server-primitives). +- [ ] **Check final cache headers and update behavior.** Use `Cache-Control: no-store` for personalized responses unless you have an explicit identity-partitioned cache key and lifecycle that prevents reuse across accounts. `private` alone does not prevent a browser cache from retaining one account's response after sign-out. For public cached content, perform a write and confirm it becomes visible within the freshness policy you chose. Inspect the final headers from your host, not just the values assigned in route code. Query invalidation, Router invalidation, and CDN invalidation affect different caches. See [Server Routes](./server-routes) and [Static Prerendering](./static-prerendering). +- [ ] **Compare a direct visit with client navigation.** Test initial HTML, hydration, back/forward navigation, and a reload for a parameterized route and a route with search values. Missing content, mismatched metadata, hydration warnings, or repeated immediate reads need investigation. See [Hydration Errors](./hydration-errors) and [Routing](./routing). + +## HTTP responses and search visibility + +- [ ] **Probe success, missing, redirect, and error responses.** A real missing public resource should return HTTP 404, a moved URL should use its intended redirect, and a failed request should not masquerade as a successful page. Check status codes before following redirects. Test a controlled failure in staging and confirm the error interface offers recovery without leaking sensitive details. See [Server Routes](./server-routes), [Error Boundaries](./error-boundaries), and [Router Not Found Errors](/router/latest/docs/guide/not-found-errors). +- [ ] **Inspect public HTML before JavaScript runs.** Verify useful content, a specific title and description, the public canonical URL, and relevant social metadata. Repeat after client navigation. Look for preview hostnames in canonicals, duplicate titles, or metadata that depends on a browser effect. See [SEO](./seo). +- [ ] **Check indexing rules and discovery files.** Fetch `robots.txt` and the sitemap from the deployed hostname. Sitemap URLs should resolve to intended public canonical pages. Remove accidental production `noindex` rules, but keep private and preview content out of search. Robots rules are not access control. See [SEO](./seo#sitemaps). + +## Assets, logging, and deployment + +- [ ] **Inspect the production network waterfall.** Test a representative page on a narrow viewport with slower network and CPU settings. Check large images, missing dimensions, font loading, third-party scripts, and failed asset requests. Record a baseline so later releases have something to compare against. Local lab results do not establish real-user performance. See [SEO performance guidance](./seo#performance-matters), [CDN Asset URLs](./cdn-asset-urls), and [Observability](./observability). +- [ ] **Trigger and find a controlled error.** Confirm your chosen logs or error service receive it with enough route and release context to investigate. Check that credentials, cookies, and sensitive payloads are absent. An error boundary that only changes the screen is not evidence of a working alert. See [Observability](./observability). +- [ ] **Run the deployed entry point and rehearse rollback.** Use your adapter's production output and start command, then test a direct deep link, a static asset, a server function, and a server route. Check that requests still work after a restart. Rehearse restoring a previous release and account for any database migration separately. Local success cannot prove host bindings, asset retention, or database rollback safety. See [Hosting](./hosting). + +## Keep a release record + +Record the tested commit, runtime, hostname, commands, and results. Turn repeatable HTTP and browser checks into CI tests; repeat host-specific checks after deployment changes. + +The [Next.js migration reference](../examples/start-next-migration) provides production browser checks for public HTML and metadata, search, redirects, missing pages, session reloads, and protected mutations. Its demo credentials and cookie session are for local comparison, not a production authentication system. Use its tests as a starting point, then add your own authorization rules, external services, CDN behavior, and operational checks. diff --git a/docs/start/framework/react/guide/rendering-markdown.md b/docs/start/framework/react/guide/rendering-markdown.md index 4258d6f4f1..bf644124d9 100644 --- a/docs/start/framework/react/guide/rendering-markdown.md +++ b/docs/start/framework/react/guide/rendering-markdown.md @@ -3,191 +3,85 @@ id: rendering-markdown title: Rendering Markdown --- -This guide covers two methods for importing and rendering markdown content in your TanStack Start application: +Use [TanStack Markdown](https://tanstack.com/markdown/latest/docs/overview) to render Markdown in your TanStack Start application. Its React renderer works synchronously during server rendering and client navigation, so content does not need to wait for a client effect. -1. **Static markdown** with `content-collections` for build-time loading (e.g., blog posts) -2. **Dynamic markdown** fetched at runtime from GitHub or any remote source +This guide covers static posts loaded with Content Collections and remote content fetched through a server function. Both use the same Markdown component. -Both methods share a common rendering pipeline using the `unified` ecosystem. +## Rendering Markdown -## Setting Up the Markdown Processor - -Both approaches use the same markdown-to-HTML processing pipeline. First, install the required dependencies: +Install TanStack Markdown: ```bash -npm install unified remark-parse remark-gfm remark-rehype rehype-raw rehype-slug rehype-autolink-headings rehype-stringify shiki html-react-parser gray-matter +npm install @tanstack/markdown ``` -Create a markdown processor utility: - -```tsx -// src/utils/markdown.ts -import { unified } from 'unified' -import remarkParse from 'remark-parse' -import remarkGfm from 'remark-gfm' -import remarkRehype from 'remark-rehype' -import rehypeRaw from 'rehype-raw' -import rehypeSlug from 'rehype-slug' -import rehypeAutolinkHeadings from 'rehype-autolink-headings' -import rehypeStringify from 'rehype-stringify' - -export type MarkdownHeading = { - id: string - text: string - level: number -} - -export type MarkdownResult = { - markup: string - headings: Array -} - -export async function renderMarkdown(content: string): Promise { - const headings: Array = [] - - const result = await unified() - .use(remarkParse) // Parse markdown - .use(remarkGfm) // Support GitHub Flavored Markdown - .use(remarkRehype, { allowDangerousHtml: true }) // Convert to HTML AST - .use(rehypeRaw) // Process raw HTML in markdown - .use(rehypeSlug) // Add IDs to headings - .use(rehypeAutolinkHeadings, { - behavior: 'wrap', - properties: { className: ['anchor'] }, - }) - .use(() => (tree) => { - // Extract headings for table of contents - const { visit } = require('unist-util-visit') - const { toString } = require('hast-util-to-string') - - visit(tree, 'element', (node: any) => { - if (['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(node.tagName)) { - headings.push({ - id: node.properties?.id || '', - text: toString(node), - level: parseInt(node.tagName.charAt(1), 10), - }) - } - }) - }) - .use(rehypeStringify) // Serialize to HTML string - .process(content) - - return { - markup: String(result), - headings, - } -} -``` - -## Creating a Markdown Component - -Create a React component that renders the processed HTML with custom element handling: +Create a shared component that accepts either Markdown source or a parsed document: ```tsx // src/components/Markdown.tsx -import parse, { type HTMLReactParserOptions, Element } from 'html-react-parser' -import { renderMarkdown, type MarkdownResult } from '~/utils/markdown' +import { Markdown as ReactMarkdown } from '@tanstack/markdown/react' +import type { MarkdownDocument } from '@tanstack/markdown' type MarkdownProps = { - content: string + content: string | MarkdownDocument className?: string } export function Markdown({ content, className }: MarkdownProps) { - const [result, setResult] = useState(null) - - useEffect(() => { - renderMarkdown(content).then(setResult) - }, [content]) - - if (!result) { - return
Loading...
- } - - const options: HTMLReactParserOptions = { - replace: (domNode) => { - if (domNode instanceof Element) { - // Customize rendering of specific elements - if (domNode.name === 'a') { - // Handle links - const href = domNode.attribs.href - if (href?.startsWith('/')) { - // Internal link - use your router's Link component - return ( - {domToReact(domNode.children, options)} - ) - } - } - - if (domNode.name === 'img') { - // Add lazy loading to images - return ( - - ) - } - } - }, - } - - return
{parse(result.markup, options)}
+ return ( +
+ {content} +
+ ) } ``` -## Method 1: Static Markdown with content-collections +Headings receive stable IDs, and `headingAnchors` adds links to them. Raw HTML is escaped and unsafe URL protocols are removed by default. Keep these defaults for remote or user-written content. TanStack Markdown does not execute MDX or implement every CommonMark or GFM feature, so check the [supported syntax](https://tanstack.com/markdown/latest/docs/core-concepts/syntax-profile) when migrating existing content. -The `content-collections` package is ideal for static content like blog posts that are included in your repository. It processes markdown files at build time and provides type-safe access to the content. - -### Installation - -```bash -npm install @content-collections/core @content-collections/vite -``` - -### Configuration - -Create a `content-collections.ts` file in your project root: +Use the `components` prop to customize elements, for example to lazy-load images: ```tsx + , + }} +> + {content} + +``` + +The examples below use `~/*` for the `src/*` import alias. The `prose` class is optional and requires your own typography styles, such as Tailwind Typography. + +## Static Markdown with Content Collections + +[Content Collections](https://www.content-collections.dev/docs/quickstart/tanstack-start) loads local Markdown files and validates their frontmatter. Pass the Markdown body from the generated collection to the shared renderer. + +### Installation and Configuration + +```bash +npm install -D @content-collections/core @content-collections/vite zod +``` + +```ts // content-collections.ts import { defineCollection, defineConfig } from '@content-collections/core' -import matter from 'gray-matter' - -function extractFrontMatter(content: string) { - const { data, content: body, excerpt } = matter(content, { excerpt: true }) - return { data, body, excerpt: excerpt || '' } -} +import { z } from 'zod' const posts = defineCollection({ name: 'posts', - directory: './src/blog', // Directory containing your .md files + directory: './src/blog', include: '*.md', - schema: (z) => ({ + schema: z.object({ title: z.string(), - published: z.string().date(), - description: z.string().optional(), - authors: z.string().array(), + published: z.string().regex(/^\d{4}-\d{2}-\d{2}$/), + description: z.string(), + authors: z.array(z.string()), + content: z.string(), + }), + transform: (post) => ({ + ...post, + slug: post._meta.path, }), - transform: ({ content, ...post }) => { - const frontMatter = extractFrontMatter(content) - - // Extract header image (first image in the document) - const headerImageMatch = content.match(/!\[([^\]]*)\]\(([^)]+)\)/) - const headerImage = headerImageMatch ? headerImageMatch[2] : undefined - - return { - ...post, - slug: post._meta.path, - excerpt: frontMatter.excerpt, - description: frontMatter.data.description, - headerImage, - content: frontMatter.body, - } - }, }) export default defineConfig({ @@ -195,39 +89,55 @@ export default defineConfig({ }) ``` -### Vite Integration +Content Collections already separates frontmatter from `content`, so this transform does not need a second frontmatter parser. -Add the content-collections plugin to your Vite config: +Add the plugin to your existing Vite configuration, keeping any deployment plugins your app needs: -```tsx -// app.config.ts -import { defineConfig } from '@tanstack/react-start/config' +```ts +// vite.config.ts import contentCollections from '@content-collections/vite' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' +import { defineConfig } from 'vite' +import tsConfigPaths from 'vite-tsconfig-paths' export default defineConfig({ - vite: { - plugins: [contentCollections()], - }, + plugins: [ + contentCollections(), + tsConfigPaths({ projects: ['./tsconfig.json'] }), + tanstackStart(), + viteReact(), + ], }) ``` -### Creating Blog Posts +Add the generated collection alias to your existing `tsconfig.json`: -Create markdown files in your designated directory: +```json +{ + "compilerOptions": { + "paths": { + "~/*": ["./src/*"], + "content-collections": ["./.content-collections/generated"] + } + } +} +``` + +Add `.content-collections` to `.gitignore`. Starting the Vite dev server or running a build generates the collection. + +### Creating a Post + +Create `src/blog/hello-world.md`: ````markdown -## - -title: Hello World -published: 2024-01-15 -authors: - -- Jane Doe - description: My first blog post - --- - -![Hero Image](/images/hero.jpg) +title: Hello World +published: '2026-01-15' +description: My first blog post +authors: + - Jane Doe +--- Welcome to my blog! This is my first post. @@ -240,13 +150,11 @@ console.log('Hello, world!') ``` ```` -### Using the Collection - -Access your posts through the generated collection: +### Listing Posts ```tsx // src/routes/blog.index.tsx -import { createFileRoute } from '@tanstack/react-router' +import { createFileRoute, Link } from '@tanstack/react-router' import { allPosts } from 'content-collections' export const Route = createFileRoute('/blog/')({ @@ -254,31 +162,30 @@ export const Route = createFileRoute('/blog/')({ }) function BlogIndex() { - // Posts are sorted by published date - const sortedPosts = allPosts.sort( - (a, b) => new Date(b.published).getTime() - new Date(a.published).getTime(), + const sortedPosts = [...allPosts].sort((a, b) => + b.published.localeCompare(a.published), ) return ( -
+

Blog

    {sortedPosts.map((post) => (
  • -

    {post.title}

    -

    {post.excerpt}

    - {post.published} + {post.title} +

    {post.description}

    +
  • ))}
-
+ ) } ``` -### Rendering a Single Post +### Rendering a Post ```tsx // src/routes/blog.$slug.tsx @@ -288,7 +195,7 @@ import { Markdown } from '~/components/Markdown' export const Route = createFileRoute('/blog/$slug')({ loader: ({ params }) => { - const post = allPosts.find((p) => p.slug === params.slug) + const post = allPosts.find((post) => post.slug === params.slug) if (!post) { throw notFound() } @@ -302,202 +209,169 @@ function BlogPost() { return (
-
-

{post.title}

-

- By {post.authors.join(', ')} on {post.published} -

-
+

{post.title}

+

+ By {post.authors.join(', ')} on {post.published} +

) } ``` -## Method 2: Dynamic Markdown from Remote Sources +The renderer parses the Markdown synchronously and renders React elements on both the server and client. -For content stored externally (like GitHub repositories), you can fetch and render markdown dynamically using server functions. +## Remote Markdown with a Server Function -### Creating a Fetch Utility +Fetch remote content in a server function and parse it before returning it to the route. Install `gray-matter` if the remote files contain frontmatter: -```tsx -// src/utils/docs.server.ts +```bash +npm install gray-matter +``` + +Keep the repository, branch, and content directory in server code. Validate the requested filename before building the URL: + +```ts +// src/utils/docs.ts import { createServerFn } from '@tanstack/react-start' +import { notFound } from '@tanstack/react-router' +import { parseMarkdown } from '@tanstack/markdown/parser' import matter from 'gray-matter' -type FetchDocsParams = { - repo: string // e.g., 'tanstack/router' - branch: string // e.g., 'main' - filePath: string // e.g., 'docs/guide/getting-started.md' -} - export const fetchDocs = createServerFn({ method: 'GET' }) - .validator((params: FetchDocsParams) => params) - .handler(async ({ data: { repo, branch, filePath } }) => { - const url = `https://raw.githubusercontent.com/${repo}/${branch}/${filePath}` - - const response = await fetch(url, { - headers: { - // Add GitHub token for private repos or higher rate limits - // Authorization: `token ${process.env.GITHUB_TOKEN}`, - }, - }) + .validator((slug: unknown) => { + if (typeof slug !== 'string' || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)) { + throw new Error('Invalid document slug') + } + return slug + }) + .handler(async ({ data: slug }) => { + // Replace this with your public repository's content directory. + const baseUrl = + 'https://raw.githubusercontent.com/your-org/your-repo/main/docs' + const response = await fetch(`${baseUrl}/${slug}.md`) + if (response.status === 404) { + throw notFound() + } if (!response.ok) { - throw new Error(`Failed to fetch: ${response.status}`) + throw new Error(`Failed to fetch document: ${response.status}`) } - const rawContent = await response.text() - const { data: frontmatter, content } = matter(rawContent) + const { data, content } = matter(await response.text()) return { - frontmatter, - content, - filePath, + title: typeof data.title === 'string' ? data.title : slug, + document: parseMarkdown(content), } }) ``` -### Adding Cache Headers - -For production, add appropriate cache headers: - ```tsx -export const fetchDocs = createServerFn({ method: 'GET' }) - .validator((params: FetchDocsParams) => params) - .handler(async ({ data: { repo, branch, filePath }, context }) => { - // Set cache headers for CDN caching - context.response.headers.set( - 'Cache-Control', - 'public, max-age=0, must-revalidate', - ) - context.response.headers.set( - 'CDN-Cache-Control', - 'max-age=300, stale-while-revalidate=300', - ) - - // ... fetch logic - }) -``` - -### Using Dynamic Markdown in Routes - -```tsx -// src/routes/docs.$path.tsx +// src/routes/docs.$slug.tsx import { createFileRoute } from '@tanstack/react-router' -import { fetchDocs } from '~/utils/docs.server' import { Markdown } from '~/components/Markdown' +import { fetchDocs } from '~/utils/docs' -export const Route = createFileRoute('/docs/$path')({ - loader: async ({ params }) => { - return fetchDocs({ - data: { - repo: 'your-org/your-repo', - branch: 'main', - filePath: `docs/${params.path}.md`, - }, - }) - }, +export const Route = createFileRoute('/docs/$slug')({ + loader: ({ params }) => fetchDocs({ data: params.slug }), component: DocsPage, }) function DocsPage() { - const { frontmatter, content } = Route.useLoaderData() + const { title, document } = Route.useLoaderData() return (
-

{frontmatter.title}

- +

{title}

+
) } ``` -### Fetching Directory Contents +Relative Markdown links and image URLs resolve against your app's URL, not the source repository. Use app-relative or absolute URLs in the content, or transform them for your site's route and asset layout. -To build navigation from a GitHub directory: +## Syntax Highlighting with TanStack Highlight -```tsx -// src/utils/docs.server.ts -type GitHubContent = { - name: string - path: string - type: 'file' | 'dir' -} +Install [TanStack Highlight](https://tanstack.com/highlight/latest/docs/overview). The Markdown adapter requires version `0.0.6` or newer: -export const fetchRepoContents = createServerFn({ method: 'GET' }) - .validator((params: { repo: string; branch: string; path: string }) => params) - .handler(async ({ data: { repo, branch, path } }) => { - const url = `https://api.github.com/repos/${repo}/contents/${path}?ref=${branch}` - - const response = await fetch(url, { - headers: { - Accept: 'application/vnd.github.v3+json', - // Authorization: `token ${process.env.GITHUB_TOKEN}`, - }, - }) - - if (!response.ok) { - throw new Error(`Failed to fetch contents: ${response.status}`) - } - - const contents: Array = await response.json() - - return contents - .filter((item) => item.type === 'file' && item.name.endsWith('.md')) - .map((item) => ({ - name: item.name.replace('.md', ''), - path: item.path, - })) - }) +```bash +npm install @tanstack/highlight ``` -## Adding Syntax Highlighting with Shiki +Register the languages your content uses and create the Markdown adapter: -For code blocks with syntax highlighting, integrate Shiki into your markdown processor: +```ts +// src/utils/markdown-highlighter.ts +import { createHighlighter } from '@tanstack/highlight/core' +import { js } from '@tanstack/highlight/languages/js' +import { plaintext } from '@tanstack/highlight/languages/plaintext' +import { ts } from '@tanstack/highlight/languages/ts' +import { tsx } from '@tanstack/highlight/languages/tsx' +import { createTanStackMarkdownHighlighter } from '@tanstack/highlight/markdown' -```tsx -// src/utils/markdown.ts -import { codeToHtml } from 'shiki' +const highlighter = createHighlighter({ + languages: [plaintext, js, ts, tsx], +}) -// Process code blocks after parsing -export async function highlightCode( - code: string, - language: string, -): Promise { - return codeToHtml(code, { - lang: language, - themes: { - light: 'github-light', - dark: 'tokyo-night', - }, - }) -} +export const highlightMarkdownCode = + createTanStackMarkdownHighlighter(highlighter) ``` -Then handle code blocks in your Markdown component: +Update the shared component to pass the highlighter and include its theme styles: ```tsx -// In your Markdown component's replace function -if (domNode.name === 'pre') { - const codeElement = domNode.children.find( - (child) => child instanceof Element && child.name === 'code', +// src/components/Markdown.tsx +import { createThemeCss } from '@tanstack/highlight/theme' +import { githubDarkTheme } from '@tanstack/highlight/themes/github-dark' +import { githubLightTheme } from '@tanstack/highlight/themes/github-light' +import { Markdown as ReactMarkdown } from '@tanstack/markdown/react' +import type { MarkdownDocument } from '@tanstack/markdown' +import { highlightMarkdownCode } from '~/utils/markdown-highlighter' + +const themeCss = createThemeCss({ + light: githubLightTheme, + dark: githubDarkTheme, + lightSelector: '.markdown-renderer', + darkSelector: '.dark .markdown-renderer', + codeBlockSelector: '.markdown-renderer pre.tm-code', + lineNumbersSelector: '.markdown-renderer .tm-code--line-numbers', +}) + +type MarkdownProps = { + content: string | MarkdownDocument + className?: string +} + +export function Markdown({ content, className }: MarkdownProps) { + return ( +
+ + + {content} + +
) - if (codeElement) { - const className = codeElement.attribs.class || '' - const language = className.replace('language-', '') || 'text' - const code = getText(codeElement) - - return - } } ``` -## Summary +The adapter returns escaped token markup inside the renderer's own `
` elements. Unknown languages fall back to plain text. Add a `dark` class to an ancestor to select the dark theme. See the [syntax highlighting guide](https://tanstack.com/markdown/latest/docs/guides/syntax-highlighting) for line numbers and highlighted lines.
 
-| Approach            | Best For                                  | Pros                                           | Cons                                      |
-| ------------------- | ----------------------------------------- | ---------------------------------------------- | ----------------------------------------- |
-| content-collections | Blog posts, static docs bundled with app  | Type-safe, build-time processing, fast runtime | Requires rebuild for content updates      |
-| Dynamic fetching    | External docs, frequently updated content | Always fresh, no rebuild needed                | Runtime overhead, requires error handling |
+## Table of Contents
 
-Choose the approach that best fits your content update frequency and deployment workflow. For hybrid scenarios, you can use both methods in the same application.
+To collect headings, add the docs preset when parsing the document:
+
+```ts
+import { docsMarkdownExtensions } from '@tanstack/markdown/extensions/docs'
+import { parseMarkdown } from '@tanstack/markdown/parser'
+
+const document = parseMarkdown(content, {
+  extensions: docsMarkdownExtensions(),
+})
+
+const headings = document.headings ?? []
+// Each heading has an id, text, and level.
+```
+
+Use this in the server function, then render links to each heading's `id`. The [docs preset guide](https://tanstack.com/markdown/latest/docs/guides/docs-preset) also covers callouts and custom comment components. Those features need the same extensions passed to the renderer.
diff --git a/docs/start/framework/react/guide/seo.md b/docs/start/framework/react/guide/seo.md
index 2d3e98757d..1a202503a8 100644
--- a/docs/start/framework/react/guide/seo.md
+++ b/docs/start/framework/react/guide/seo.md
@@ -1,6 +1,7 @@
 ---
 id: seo
 title: SEO
+description: Configure SEO in TanStack Start with page metadata, canonical URLs, structured data, server rendering, sitemaps, and robots.txt.
 ---
 
 > [!NOTE]
diff --git a/docs/start/framework/react/guide/server-components.md b/docs/start/framework/react/guide/server-components.md
index 893a633339..581ae145bd 100644
--- a/docs/start/framework/react/guide/server-components.md
+++ b/docs/start/framework/react/guide/server-components.md
@@ -74,7 +74,7 @@ import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild'
 
 export default defineConfig({
   plugins: [
-    pluginReact({ splitChunks: false }),
+    pluginReact(),
     tanstackStart({
       rsc: {
         enabled: true,
@@ -86,7 +86,7 @@ export default defineConfig({
 
 
 
-**Requirements:** React 19+, Vite 7+ or Rsbuild 2+
+**Requirements:** React 19+, Vite 8+ or Rsbuild 2+
 
 ## Quick Start
 
@@ -401,7 +401,10 @@ const postQueryOptions = (postId: string) => ({
 export const Route = createFileRoute('/posts/$postId')({
   loader: async ({ context, params }) => {
     // Prefetch during SSR - data reused on client without refetch
-    await context.queryClient.ensureQueryData(postQueryOptions(params.postId))
+    await context.queryClient.query({
+      ...postQueryOptions(params.postId),
+      staleTime: 'static',
+    })
   },
   component: PostPage,
 })
diff --git a/docs/start/framework/react/guide/server-entry-point.md b/docs/start/framework/react/guide/server-entry-point.md
index 5acc8ee550..5f74eb7846 100644
--- a/docs/start/framework/react/guide/server-entry-point.md
+++ b/docs/start/framework/react/guide/server-entry-point.md
@@ -3,38 +3,72 @@ id: server-entry-point
 title: Server Entry Point
 ---
 
-# Server Entry Point
-
 > [!NOTE]
-> The server entry point is **optional** out of the box. If not provided, TanStack Start will automatically handle the server entry point for you using the below as a default.
+> A custom server entry point is **optional**. Without one, TanStack Start uses its built-in entry, which renders requests and converts uncaught errors into HTTP responses automatically.
 
 The Server Entry Point supports the universal fetch handler format, commonly used by [Cloudflare Workers](https://developers.cloudflare.com/workers/runtime-apis/handlers/fetch/) and other WinterCG-compatible runtimes.
 
-To ensure interoperability, the default export must conform to our `ServerEntry` interface:
-
-```ts
-export default {
-  fetch(req: Request, opts?: RequestOptions): Response | Promise {
-    // ...
-  },
-}
-```
-
-TanStack Start exposes a wrapper to make creation type-safe. This is done in the `src/server.ts` file.
+The default export must provide a `fetch` method that accepts a `Request` and Start's request options, then returns a `Response` or `Promise`. Use `createServerEntry` to infer these types and keep the complete callback inside the request's context, including custom error handling. For example, this custom `src/server.ts` delegates to the built-in entry:
 
 ```tsx
 // src/server.ts
 import handler, { createServerEntry } from '@tanstack/react-start/server-entry'
 
 export default createServerEntry({
-  fetch(request) {
-    return handler.fetch(request)
+  fetch(request, opts) {
+    return handler.fetch(request, opts)
   },
 })
 ```
 
 Whether we are statically generating our app or serving it dynamically, the `server.ts` file is the entry point for doing all SSR-related work as well as for handling server routes and server function requests.
 
+## Configuring a Custom Server Entry
+
+Start automatically detects `src/server.ts`. If that file is absent, it uses the built-in entry. For a custom entry at another path, configure `server.entry` in your bundler plugin. This path is resolved relative to `srcDirectory`, which defaults to `src`.
+
+
+
+# Vite
+
+```ts title="vite.config.ts"
+import { defineConfig } from 'vite'
+import { tanstackStart } from '@tanstack/react-start/plugin/vite'
+import viteReact from '@vitejs/plugin-react'
+
+export default defineConfig({
+  plugins: [
+    tanstackStart({
+      server: {
+        entry: './server-entry.ts',
+      },
+    }),
+    viteReact(),
+  ],
+})
+```
+
+# Rsbuild
+
+```ts title="rsbuild.config.ts"
+import { defineConfig } from '@rsbuild/core'
+import { pluginReact } from '@rsbuild/plugin-react'
+import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild'
+
+export default defineConfig({
+  plugins: [
+    pluginReact(),
+    tanstackStart({
+      server: {
+        entry: './server-entry.ts',
+      },
+    }),
+  ],
+})
+```
+
+
+
 ## Custom Server Handlers
 
 You can create custom server handlers to modify how your application is rendered:
@@ -53,16 +87,155 @@ const customHandler = defineHandlerCallback((ctx) => {
   return defaultStreamHandler(ctx)
 })
 
-const fetch = createStartHandler(customHandler)
+const startHandler = createStartHandler(customHandler)
 
 export default createServerEntry({
-  fetch,
+  fetch(request, opts) {
+    return startHandler(request, opts)
+  },
 })
 ```
 
+## Error Handling
+
+The built-in entry uses `createServerEntry` to catch errors that escape the Start handler and call `handleStartError(error)` inside the active request context. This works without a custom `src/server.ts`. Response helpers such as `setResponseStatus`, `setResponseHeader`, and `setCookie` are applied to the error response.
+
+For an uncaught error, Start returns a generic JSON error body with status `500` unless a response helper or HTTP-style error property supplies an error status. A thrown `Response` keeps its body and response metadata, with response helpers applied, and loses its body for `HEAD` requests and for statuses `204`, `205`, and `304`, including one selected by a helper. The generic error body Start generates always uses an error status, so only `HEAD` removes it.
+
+For example, a request to this server route returns `401` with a `WWW-Authenticate` header:
+
+```tsx
+// src/routes/api/protected.ts
+import { createFileRoute } from '@tanstack/react-router'
+import { createMiddleware } from '@tanstack/react-start'
+import {
+  setResponseHeader,
+  setResponseStatus,
+} from '@tanstack/react-start/server'
+
+const authMiddleware = createMiddleware().server(() => {
+  setResponseStatus(401, 'Unauthorized')
+  setResponseHeader('www-authenticate', 'Bearer')
+  throw new Error('Unauthorized')
+})
+
+export const Route = createFileRoute('/api/protected')({
+  server: {
+    middleware: [authMiddleware],
+    handlers: {
+      GET: () => new Response('Protected content'),
+    },
+  },
+})
+```
+
+Error conversion preserves:
+
+- Error statuses (`400`-`599`) and their status text from `setResponseStatus`
+- Header operations from the response helpers
+- Cookies from `setCookie` and `appendResponseHeader('set-cookie', ...)`, including multiple `Set-Cookie` headers
+- HTTP-style error metadata such as `error.status`, `error.statusText`, `error.headers`, and `error.cause.headers`
+
+Start builds a new JSON body for an error, so it never copies the framing and connection headers `Content-Length`, `Content-Encoding`, `Transfer-Encoding`, `Trailer`, `Connection`, `Keep-Alive`, `Proxy-Connection`, and `TE` from error metadata. When `error.cause` is a `Response`, such as a failed upstream `fetch` from any fetch implementation, Start uses its status and status text but none of its headers, because they were written for that upstream reply.
+
+Explicit helper error statuses, their status text, and header operations take precedence over error metadata. An error response only uses an error status (`400`-`599`). A status set with `setResponseStatus` before the error applies only when it is an error status. A success, redirect, or bodyless status such as `200`, `201`, `302`, or `204` describes the response that the failure replaced, so Start discards it together with its status text and uses the error's own status or `500`. Error metadata such as `error.status` or `error.statusCode` likewise applies only when it is `400` or higher.
+
+Start logs the error to the server console unless the error's own metadata marks it as an HTTP error with a status of `400` or higher, even when a helper selected the status. The generic JSON body does not expose the error's message or stack.
+
+Errors that Router handles through route error components do not reach this top-level catch. Server function calls and their request middleware use a separate error response path that preserves the RPC serialization protocol. Failures during initialization, before that path is established, fall back to the top-level error response. Errors in a streamed body after the entry has returned its `Response` cannot replace that response's status or headers.
+
+You can use `createServerEntry` with your own `try`/`catch`, including for error reporting with Sentry. Your catch runs first; the wrapper converts only errors that escape your callback. Call the handler returned by `createStartHandler(...)` inside that catch, because it rethrows the original uncaught value:
+
+```tsx
+// src/server.ts
+import {
+  createStartHandler,
+  defaultStreamHandler,
+  handleStartError,
+} from '@tanstack/react-start/server'
+import { createServerEntry } from '@tanstack/react-start/server-entry'
+
+const startHandler = createStartHandler(defaultStreamHandler)
+
+export default createServerEntry({
+  async fetch(request, opts) {
+    try {
+      return await startHandler(request, opts)
+    } catch (error) {
+      // Report the original error here, for example to Sentry.
+      return handleStartError(error)
+    }
+  },
+})
+```
+
+After reporting, choose how to finish the catch:
+
+- Return `handleStartError(error)` to obtain Start's error response explicitly.
+- Rethrow `error` to let `createServerEntry` produce that same error response.
+- Return your own `Response` to choose its body, status, and headers.
+
+All three options keep `createServerEntry` and its request context. The first two preserve Start's response-helper state.
+
+The wrapper creates the request context before calling your `fetch` callback. The entire callback, including its own catch and code after `await`, runs inside that context. Calling the Start handler with the same `Request` reuses it. `handleStartError` therefore uses the correct request's state even when the thrown value is a primitive, or several requests throw the same `Error` object. Start does not attach request state to errors or remember them for a later catch. A catch outside this wrapper cannot recover a completed request's helper state from the error.
+
+The default export from `@tanstack/react-start/server-entry` is already wrapped. Calling its `fetch` method converts uncaught errors before an outer catch can see them. Use the handler returned by `createStartHandler(...)` inside your callback when you need to catch the original error, as above.
+
+Delegating to the default entry or another wrapped entry with the same `Request` object shares the current request context. A cloned or rewritten `Request` starts a separate context. When passing a new request to a raw `createStartHandler` handler, wrap that invocation with `createServerEntry` too, so errors are converted before leaving the new context:
+
+```tsx
+import {
+  createStartHandler,
+  defaultStreamHandler,
+} from '@tanstack/react-start/server'
+import { createServerEntry } from '@tanstack/react-start/server-entry'
+
+const rewrittenEntry = createServerEntry({
+  fetch: createStartHandler(defaultStreamHandler),
+})
+
+export default createServerEntry({
+  fetch(request, opts) {
+    const url = new URL(request.url)
+    if (url.pathname === '/legacy-home') {
+      url.pathname = '/'
+    }
+    return rewrittenEntry.fetch(new Request(url, request), opts)
+  },
+})
+```
+
+The rewritten request owns its response helper state. Catching a raw rewritten handler's error only in the original request's scope would not recover the rewritten request's headers or cookies.
+
+To replace an uncaught error response completely, return your own response from the custom catch:
+
+```tsx
+// src/server.ts
+import {
+  createStartHandler,
+  defaultStreamHandler,
+} from '@tanstack/react-start/server'
+import { createServerEntry } from '@tanstack/react-start/server-entry'
+
+const startHandler = createStartHandler(defaultStreamHandler)
+
+export default createServerEntry({
+  async fetch(request, opts) {
+    try {
+      return await startHandler(request, opts)
+    } catch (error) {
+      console.error(error)
+      return new Response('Internal Server Error', { status: 500 })
+    }
+  },
+})
+```
+
+`createServerEntry` returns custom responses as-is, whether they come from a catch or a successful callback. Such responses do not automatically inherit helper state. Likewise, helper writes after `await handler.fetch(...)` are not automatically applied to its returned response; modify that response directly or put the helper writes in Start middleware. Call `handleStartError` in a catch when the error response should inherit helper state.
+
 ## Request context
 
-When your server needs to pass additional, typed data into request handlers (for example, authenticated user info, a database connection, or per-request flags), register a request context type via TypeScript module augmentation. The registered context is delivered as the second argument to the server `fetch` handler and is available throughout the server-side middleware chain — including global middleware, request/function middleware, server routes, server functions, and the router itself.
+When your server needs to pass additional, typed data into request handlers (for example, authenticated user info, a database connection, or per-request flags), register a request context type via TypeScript module augmentation. Pass the runtime values through the `context` property of the second argument to `handler.fetch`. Type registration does not create these values. The context is available throughout the server-side middleware chain — including global middleware, request/function middleware, server routes, server functions, and the router itself.
 
 To add types for your request context, augment the `Register` interface from `@tanstack/react-router` with a `server.requestContext` property. The runtime `context` you pass to `handler.fetch` will then match that type. Example:
 
@@ -83,8 +256,11 @@ declare module '@tanstack/react-router' {
 }
 
 export default createServerEntry({
-  async fetch(request) {
-    return handler.fetch(request, { context: { hello: 'world', foo: 123 } })
+  fetch(request, opts) {
+    return handler.fetch(request, {
+      ...opts,
+      context: { hello: 'world', foo: 123 },
+    })
   },
 })
 ```
diff --git a/docs/start/framework/react/guide/server-functions.md b/docs/start/framework/react/guide/server-functions.md
index 903e5d7b86..879aa9e867 100644
--- a/docs/start/framework/react/guide/server-functions.md
+++ b/docs/start/framework/react/guide/server-functions.md
@@ -390,7 +390,7 @@ Stream typed data from server functions to the client. See the [Streaming Data f
 
 ### Raw Responses
 
-Return `Response` objects binary data, or custom content types.
+Return a `Response` for binary data or custom content types, and the call resolves with it. Throw a `Response` instead to reject the call with it. Either way, the caller receives its body and headers, and its status unless a response helper set one. The browser follows a `Response` with a redirect status and a `Location` header before the caller sees it, so use `redirect()` to send the user elsewhere.
 
 ### Progressive Enhancement
 
@@ -425,7 +425,9 @@ Customization:
 
 You can customize function ID generation for the production build by providing a `generateFunctionId` function when configuring the TanStack Start build tool plugin.
 
-Prefer deterministic inputs (filename + functionName) so IDs remain stable between builds.
+Return `undefined` (or an empty string) to use the default ID. Prefer deterministic inputs (filename + functionName) so IDs remain stable between builds.
+
+The ID becomes one segment of the server function's URL (`/_serverFn/`), unencoded, so use only ASCII letters, digits, `-`, `.`, `_`, `~` and `$`, and not `.` or `..`. An ID with whitespace, a control or non-ASCII character, or any of `"`, `#`, `/`, `<`, `>`, `?`, `\`, `^`, `` ` ``, `{` and `}`, an ID that is `.` or `..`, or one with a percent-encoding the server reads as another ID (`%41` for `A`, lowercase hex, `%2E`) or rejects, fails the build with an error naming the file, the function and the ID: the request would reach another function or none. Other characters (`%`, `+`, `:`, `;`, `@`, `'`, `|`, `[`, `]`, …) still work, with a deprecation warning: the next major version rejects them, since proxies and servers may encode or normalise them in the URL. `filename` contains `/`, so hash it (as in the example below) rather than embedding it as is.
 
 Please note that this customization is **experimental** and subject to change.
 
diff --git a/docs/start/framework/react/guide/tanstack-query.md b/docs/start/framework/react/guide/tanstack-query.md
new file mode 100644
index 0000000000..dec42ca26c
--- /dev/null
+++ b/docs/start/framework/react/guide/tanstack-query.md
@@ -0,0 +1,158 @@
+---
+id: tanstack-query
+title: TanStack Query
+updated: '2026-09-11'
+testedWith:
+  '@tanstack/react-start': '1.168.52'
+  '@tanstack/react-query': '5.102.0'
+  react: '19.2.3'
+  vite: '8.0.14'
+description: Use TanStack Query with TanStack Start for request-isolated SSR, hydration, route preloading, streaming, and mutation invalidation.
+---
+
+TanStack Start uses Router loaders to coordinate navigation. TanStack Query can own the fetched data, freshness, and mutation state. Use them together when your application needs a query cache across routes, background updates, or mutation-driven invalidation.
+
+The [React Query example](../examples/start-basic-react-query) includes a `/preferences` page that reads and updates a display name stored in a cookie. Its [tests](https://github.com/TanStack/router/blob/main/examples/react/start-basic-react-query/tests/preferences.spec.ts) check server-rendered data, isolation between requests, hydration without a duplicate read, and invalidation after a server function. The preference cookie is not an authentication mechanism.
+
+## Install and create a QueryClient per router
+
+Install `@tanstack/react-query` and `@tanstack/react-router-ssr-query`. The example uses Query 5.102 or newer, including `queryClient.query`. See the [integration reference](/router/latest/docs/integrations/query) for its options.
+
+```tsx title="src/router.tsx"
+import { QueryClient } from '@tanstack/react-query'
+import { createRouter } from '@tanstack/react-router'
+import { setupRouterSsrQueryIntegration } from '@tanstack/react-router-ssr-query'
+import { routeTree } from './routeTree.gen'
+
+export function getRouter() {
+  const queryClient = new QueryClient({
+    defaultOptions: { queries: { staleTime: 30_000 } },
+  })
+  const router = createRouter({
+    routeTree,
+    context: { queryClient },
+    defaultPreload: 'intent',
+    defaultPreloadStaleTime: 0,
+  })
+
+  setupRouterSsrQueryIntegration({ router, queryClient })
+  return router
+}
+```
+
+Create the client inside `getRouter`, not at module scope. Start creates a router for each SSR request. A process-wide QueryClient could reuse one reader's cached data in another reader's HTML. The browser then keeps the client attached to its router during navigation.
+
+Declare `queryClient: QueryClient` in the root route's `createRootRouteWithContext` type so child loaders can access it. The integration supplies the Query provider and handles SSR dehydration, hydration, and streaming. Do not add a second QueryClient or independently dehydrate the same cache. If you already own the provider wrapper, use the integration's `wrapQueryClient: false` option.
+
+`defaultPreloadStaleTime: 0` lets Query decide whether a preload needs data. The example's 30-second Query `staleTime` prevents an immediate repeat read when the browser receives fresh SSR data. Choose the freshness window for your application, rather than treating 30 seconds as a universal setting.
+
+## Share query options between the loader and component
+
+Keep a query's key and function together. Privileged reads belong in a server function, because a normal route loader can also run in the browser during navigation.
+
+```tsx title="src/utils/preferences.ts"
+import { queryOptions } from '@tanstack/react-query'
+import { createServerFn } from '@tanstack/react-start'
+import { getCookie, setResponseHeader } from '@tanstack/react-start/server'
+
+export const getReaderName = createServerFn({ method: 'GET' }).handler(() => {
+  setResponseHeader('Cache-Control', 'private, no-store')
+  return getCookie('reader-name') || 'Guest'
+})
+
+export const readerNameOptions = queryOptions({
+  queryKey: ['reader-name'],
+  queryFn: () => getReaderName(),
+})
+```
+
+The route awaits the query for content that must appear in the initial HTML:
+
+```tsx title="src/routes/preferences.tsx"
+import { useSuspenseQuery } from '@tanstack/react-query'
+import { createFileRoute } from '@tanstack/react-router'
+import { readerNameOptions } from '../utils/preferences'
+
+export const Route = createFileRoute('/preferences')({
+  loader: async ({ context }) => {
+    await context.queryClient.query(readerNameOptions)
+  },
+  headers: () => ({ 'Cache-Control': 'private, no-store' }),
+  component: Preferences,
+})
+
+function Preferences() {
+  const { data: name } = useSuspenseQuery(readerNameOptions)
+  return 

Hello, {name}

+} +``` + +Both calls use the same query key and options. The loader populates the request's cache; the component reads it; the integration transfers it to the browser. The component does not need to call the server function again in an effect. + +For a parameterized resource, include its identity in the key, such as `['post', postId]`. If search values affect the result, validate them and include them in both `loaderDeps` and the query key. Keep secrets out of keys and serialized query data. + +## Await critical data and stream secondary data + +Await queries that determine the page's main content, title, authorization, redirects, or whether it exists. Return title and description data from the loader when a route's `head` needs them, as the example's post route does. + +Secondary content can begin loading without blocking the loader, then render inside a Suspense boundary. Keep that query under the SSR integration so its result can stream to the browser. Handle the imperative query promise's rejection as well as the component's error boundary; a fire-and-forget promise should not become an unhandled server rejection. + +The example's existing `/deferred` route shows a separate Suspense boundary. See [streaming and prefetching](/router/latest/docs/integrations/query#prefetching-and-streaming) for the integration's behavior. A plain `useQuery` that has no loader prefetch is not a guarantee that its data will be in the server-rendered HTML. + +## Invalidate Query after a server mutation + +The preference example validates the display name and writes its cookie inside a POST server function. Its `src/start.ts` enables Start's CSRF middleware for server-function requests. The component calls that function through `useServerFn`, then invalidates the query that reads the cookie: + +```tsx +const queryClient = useQueryClient() +const save = useServerFn(saveReaderName) +const mutation = useMutation({ + mutationFn: (name: string) => save({ data: name }), + onSuccess: () => + queryClient.invalidateQueries({ queryKey: readerNameOptions.queryKey }), +}) +``` + +Returning the invalidation promise keeps the mutation pending until its active query's refetch finishes. The form can use `mutation.isPending` and `mutation.isError` for feedback. The example also disables its JavaScript-dependent form until hydration and uses a POST method so a native submission cannot put form values in the URL. + +Invalidate the data's actual owner. `queryClient.invalidateQueries` refreshes Query data; `router.invalidate()` reloads Router-owned loader data and route context. Use both only when the mutation changes both, such as a login that changes root authentication context and private queries. Neither call purges your CDN or invalidates a database cache. + +If a mutation returns the complete updated resource, `setQueryData` can update that cache entry directly instead. Optimistic updates need cancellation, rollback on failure, and reconciliation with the server result. This example uses a confirmed write followed by invalidation, not an optimistic update. + +## Keep account data isolated beyond SSR + +Request-scoped QueryClients prevent cross-request cache sharing on the server. They do not authorize reads or automatically clear a browser cache when its account changes. + +For authenticated applications, authorize every private read and mutation on the server, including resource-level permissions. On sign-out or account switching, cancel and remove the previous account's private queries, then reload the relevant route context. Include account or tenant identity in keys when that is part of the resource's identity, but do not treat a key as an access-control check. + +The `/preferences` route and its server functions return `Cache-Control: private, no-store` because their output varies by cookie. Verify the final response through your hosting provider and CDN. Do not publicly cache personalized HTML merely because the QueryClient itself is isolated. + +## Diagnose extra requests + +Check when and where each request occurs. A background refresh after the freshness window, a reconnect, or a deliberate invalidation can be expected. + +| Symptom | Check | +| --------------------------------------------------- | --------------------------------------------------------------------------------------------- | +| A read repeats immediately after hydration | Query `staleTime`, hydration configuration, matching keys, and accidental extra QueryClients | +| Navigation loads different data than a direct visit | Search validation, `loaderDeps`, query keys, and server-only boundaries | +| A mutation succeeds but old data stays visible | Which cache owns the displayed value and which keys were invalidated | +| A second account sees the first account's data | Module-scoped server clients, browser cache cleanup, account keys, and shared HTTP caches | +| SSR contains only a loading state | Whether the loader awaited critical data and whether the component reads the prefetched query | + +Start with the same options object in the loader and component. Avoid adding manual hydration code or disabling all refetching to hide a duplicate request. + +## Run the example's checks + +From the repository root, install dependencies and build the framework packages as described in [Contributing](https://github.com/TanStack/router/blob/main/CONTRIBUTING.md). Then: + +```sh +cd examples/react/start-basic-react-query +pnpm exec playwright install chromium +pnpm test:e2e +pnpm build +QUERY_EXAMPLE_PRODUCTION=1 pnpm test:e2e +``` + +The tests send concurrent SSR requests with different preference cookies while using the same query key. Each HTML response must contain only its own reader's value. The browser test then requires zero additional reads during hydration, exactly one read after mutation invalidation, and no extra read after a reload hydrates fresh data. + +The post and user demos use JSONPlaceholder. The preference tests run without that external API. diff --git a/docs/start/framework/react/migrate-from-next-js.md b/docs/start/framework/react/migrate-from-next-js.md index 2f4d988449..dc5377df08 100644 --- a/docs/start/framework/react/migrate-from-next-js.md +++ b/docs/start/framework/react/migrate-from-next-js.md @@ -1,510 +1,187 @@ --- id: migrate-from-next-js title: Migrate from Next.js +description: Move a Next.js App Router application to TanStack Start while preserving routes, metadata, authentication, mutations, and deployment behavior. --- -This guide provides a step-by-step process to migrate a project from the Next.js App Router to **TanStack Start**. We respect the powerful features of Next.js and aim to make this transition as smooth as possible. +This guide migrates a Next.js App Router application to TanStack Start. The [runnable before-and-after example](https://github.com/TanStack/router/tree/main/examples/react/start-next-migration) implements the same article site in both frameworks, including public articles, URL search, sign-in, a private saved-article page, and a mutation. -## Step-by-Step (Basics) +Start does not interpret Next.js route conventions or configuration. Keep your application behavior, then translate each framework boundary. If your application relies heavily on React Server Components, read the [comparison](./start-vs-nextjs) and [RSC guide](./guide/server-components) first. Start's RSC support is experimental and opt-in; the example uses ordinary route components and server functions. -This step-by-step guide provides an overview of how to migrate your Next.js App Router project to TanStack Start. The goal is to help you understand the basic steps involved in the migration process so you can adapt them to your specific project needs. +## Run the reference application -### Prerequisites - -Before we begin, this guide assumes your project structure looks like this: - -```txt -├── next.config.ts -├── package.json -├── postcss.config.mjs -├── public -│ ├── file.svg -│ ├── globe.svg -│ ├── next.svg -│ ├── vercel.svg -│ └── window.svg -├── README.md -├── src -│ └── app -│ ├── favicon.ico -│ ├── globals.css -│ ├── layout.tsx -│ └── page.tsx -└── tsconfig.json -``` - -Alternatively, you can follow along by cloning the following [starter template](https://github.com/nrjdalal/awesome-templates/tree/main/next.js-apps/next.js-start): +Use Node 24 or newer and pnpm 12: ```sh -npx gitpick nrjdalal/awesome-templates/tree/main/next.js-apps/next.js-start next.js-start-er +git clone --depth 1 https://github.com/TanStack/router.git +cd router +pnpm install +pnpm nx run @tanstack/react-start:build +cd examples/react/start-next-migration ``` -This structure is a basic Next.js application using the App Router, which we will migrate to TanStack Start. +Follow the example's [README](https://github.com/TanStack/router/blob/main/examples/react/start-next-migration/README.md) to set `SESSION_PASSWORD` and `DEMO_PASSWORD`. Run `pnpm dev:next` at `http://localhost:3100` and `pnpm dev` in another terminal at `http://localhost:3101`. -### 1. Remove Next.js +The example's single account is `reader@example.com`. It stores one saved-article flag in a session cookie so you can exercise a protected mutation without connecting a database. It is not a production authentication implementation. Both apps use iron-session with different cookie names, so sign in separately to each. -First, uninstall Next.js and remove related configuration files: +With those ports free, run: ```sh -npm uninstall @tailwindcss/postcss next -rm postcss.config.* next.config.* +pnpm exec playwright install chromium +pnpm test:e2e +pnpm build:next +pnpm build +MIGRATION_PRODUCTION=1 pnpm test:e2e ``` -### 2. Install Required Dependencies +The same browser tests run against both apps. They check public URLs, server-rendered metadata, query filtering, redirects, missing pages, sitemap entries, sign-in errors, session persistence, private response caching, mutations, and server rejection after sign-out. -TanStack Start leverages TanStack Router and supports [Vite](https://vite.dev) or [Rsbuild](https://rsbuild.dev/) as the build tool. The Vite setup below includes [Nitro](https://nitro.build/) as a deployment plugin. +## Inventory the application before changing it - +Record your current paths and observable behavior. Include dynamic paths, query parameters, redirects, trailing slashes, locale prefixes, response status, title, description, canonical, robots directives, and sitemap membership. Keep representative HTML responses and run your existing application tests against the replacement. -# Vite +Inventory Next.js-specific code separately: `next/*` imports, `'use server'`, server-only modules, metadata exports, `generateStaticParams`, `revalidatePath`, `revalidateTag`, cache directives, route configuration, Proxy or middleware, and image/font configuration. A route that renders successfully can still have lost authentication, cache invalidation, or an important search URL. -```sh -npm i @tanstack/react-router @tanstack/react-start nitro vite @vitejs/plugin-react +| Request | Required behavior | +| -------------------------- | -------------------------------------------------------------------- | +| `/` | Article list, title, description, self-referencing canonical | +| `/?q=metadata` | Filtered article list; canonical remains `/` | +| `/posts/keeping-your-urls` | Same article, title, description, canonical, and Open Graph title | +| `/posts/missing` | HTTP 404 | +| `/old-notes` | HTTP 308 to `/posts/keeping-your-urls` | +| `/saved` | Signed-out users reach sign-in; private HTML is not shared-cacheable | +| `/sitemap.xml` | Public pages only | + +For your application, decide which query variants deserve indexing. Do not copy the example's canonical policy onto meaningful product filters or paginated results without checking their content. + +## Set up Start alongside the existing app + +Create a Start application using [Getting Started](./getting-started) and [Build from Scratch](./build-from-scratch). Keep the Next.js app runnable until the migrated routes pass their checks. You do not need to remove Next.js, its configuration, or its CSS tooling before you can test Start. + +```text +next-app/ # Before: Next.js App Router + app/ + layout.tsx + page.tsx + posts/[slug]/page.tsx + actions.ts +src/ # After: TanStack Start + router.tsx + routes/ + __root.tsx + index.tsx + posts.$slug.tsx + server/account.ts +vite.config.ts ``` -# Rsbuild +The Start Vite plugin generates `src/routeTree.gen.ts`. `src/router.tsx` returns a new router using that tree. The root route renders `HeadContent` in the document head and `Scripts` in the body. Merge your existing CSS, document attributes, and providers into that root. -```sh -npm i @tanstack/react-router @tanstack/react-start @rsbuild/core @rsbuild/plugin-react -``` +The reference uses Vite and Nitro's Node output. If you use another host or build tool, follow its [hosting instructions](./guide/hosting) and test its actual build output. A Next.js deployment adapter does not become a Start adapter by changing dependencies. - +## Preserve paths while changing route files -For Tailwind CSS, install the build tool integration you want to use: +| Next.js App Router | Default Start route directory | +| ------------------------------ | ---------------------------------------------- | +| `app/layout.tsx` | `src/routes/__root.tsx` | +| `app/page.tsx` | `src/routes/index.tsx` | +| `app/posts/page.tsx` | `src/routes/posts.index.tsx` | +| `app/posts/[slug]/page.tsx` | `src/routes/posts.$slug.tsx` | +| `app/docs/[...parts]/page.tsx` | `src/routes/docs.$.tsx` | +| `app/api/hello/route.ts` | `src/routes/api.hello.ts` with server handlers | - +`src/routes` is a source directory, not a URL prefix. A route for `/posts/example` uses `createFileRoute('/posts/$slug')`, not `/app/posts/$slug`. -# Vite +Nested layouts, pathless layouts, route groups, optional parameters, catch-alls, parallel routes, and intercepting routes need individual mapping. Read [routing concepts](/router/latest/docs/routing/routing-concepts) instead of mechanically renaming every file. The reference does not reproduce Next.js parallel or intercepting route behavior. -```sh -npm i -D @tailwindcss/vite tailwindcss -``` - -# Rsbuild - -```sh -npm i -D @tailwindcss/postcss tailwindcss -``` - - - -### 3. Update Project Configuration - -Now that you've installed the necessary dependencies, update your project configuration files to work with TanStack Start. - - - -# Vite - -```json -{ - "type": "module", - "scripts": { - "dev": "vite dev", - "build": "vite build", - "start": "node .output/server/index.mjs" - } -} -``` - -# Rsbuild - -```json -{ - "type": "module", - "scripts": { - "dev": "rsbuild dev", - "build": "rsbuild build" - } -} -``` - - - - - -# Vite - -```ts title="vite.config.ts" -import { defineConfig } from 'vite' -import { tanstackStart } from '@tanstack/react-start/plugin/vite' -import viteReact from '@vitejs/plugin-react' -import tailwindcss from '@tailwindcss/vite' -import { nitro } from 'nitro/vite' - -export default defineConfig({ - server: { - port: 3000, - }, - resolve: { - // Enables Vite to resolve imports using path aliases. - tsconfigPaths: true, - }, - plugins: [ - tailwindcss(), - tanstackStart({ - srcDirectory: 'src', // This is the default - router: { - // Specifies the directory TanStack Router uses for your routes. - routesDirectory: 'app', // Defaults to "routes", relative to srcDirectory - }, - }), - viteReact(), - nitro(), - ], -}) -``` - -# Rsbuild - -```ts title="rsbuild.config.ts" -import { defineConfig } from '@rsbuild/core' -import { pluginReact } from '@rsbuild/plugin-react' -import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' - -export default defineConfig({ - server: { - port: 3000, - }, - plugins: [ - pluginReact(), - tanstackStart({ - srcDirectory: 'src', // This is the default - router: { - // Specifies the directory TanStack Router uses for your routes. - routesDirectory: 'app', // Defaults to "routes", relative to srcDirectory - }, - }), - ], -}) -``` - -```js title="postcss.config.mjs" -export default { - plugins: { - '@tailwindcss/postcss': {}, - }, -} -``` - - - -By default, `routesDirectory` is set to `routes`. To maintain consistency with Next.js App Router conventions, you can set it to `app` instead. - -### 4. Adapt the Root Layout - -> TanStack Start uses a routing approach similar to Remix, with some changes to support nested structures and special features using tokens. Learn more about it at [Routing Concepts](/router/latest/docs/framework/react/routing/routing-concepts) guide. - -Instead of `layout.tsx`, create a file named `__root.tsx` in the `src/app` directory. This file will serve as the root layout for your application. - -- `src/app/layout.tsx` to `src/app/__root.tsx` +Replace `next/link` with Router's `Link`. Dynamic paths use typed `params`: ```tsx -- import type { Metadata } from "next" // [!code --] -import { - Outlet, - createRootRoute, - HeadContent, - Scripts, -} from "@tanstack/react-router" -import appCss from "./globals.css?url" + + {article.title} + +``` -- export const metadata: Metadata = { // [!code --] -- title: "Create Next App", // [!code --] -- description: "Generated by create next app", // [!code --] -- } // [!code --] -export const Route = createRootRoute({ - head: () => ({ - meta: [ - { charSet: "utf-8" }, - { - name: "viewport", - content: "width=device-width, initial-scale=1", - }, - { title: "TanStack Start Starter" } - ], - links: [ - { - rel: 'stylesheet', - href: appCss, - }, - ], +Check direct requests, client navigation, back/forward, and reload for each representative path. Update your redirects and sitemap from the same route inventory. + +## Validate URL search state + +Next.js passes `searchParams` to an App Router page. Start validates URL state in the route: + +```tsx +export const Route = createFileRoute('/')({ + validateSearch: (search) => ({ + q: typeof search.q === 'string' ? search.q : '', }), - component: RootLayout, + component: Articles, }) -- export default function RootLayout({ // [!code --] -- children, // [!code --] -- }: Readonly<{ // [!code --] -- children: React.ReactNode // [!code --] -- }>) { // [!code --] -- return ( // [!code --] -- // [!code --] -- {children} // [!code --] -- // [!code --] -- ) // [!code --] -- } // [!code --] -function RootLayout() { - return ( - - - - - - - - - - ) +function Articles() { + const { q } = Route.useSearch() + return

Searching for: {q}

} ``` -### 5. Adapt the Home Page +If a loader depends on search state, declare the relevant values in `loaderDeps`. That makes those values part of the loader's dependency and cache behavior. Validate page numbers, sorting, and filters at runtime; TypeScript types alone do not validate an incoming URL. See [search parameters](/router/latest/docs/guide/search-params) and [data loading](/router/latest/docs/guide/data-loading). -Instead of `page.tsx`, create an `index.tsx` file for the `/` route. +## Move server reads into server functions -- `src/app/page.tsx` to `src/app/index.tsx` +An ordinary Start route loader can execute on the server for the initial request and in the browser during navigation. Do not move a database query, credential, or privileged SDK directly from an async Next.js Server Component into an ordinary loader. -```tsx -+ import { createFileRoute } from '@tanstack/react-router' // [!code ++] +Put the privileged read inside a [server function](./guide/server-functions), then call it from the loader. The reference's `/saved` route calls `getAccount`, checks the result, and redirects signed-out readers. Its public article loader only reads bundled public content. -- export default function Home() { // [!code --] -+ export const Route = createFileRoute('/')({ // [!code ++] -+ component: Home, // [!code ++] -+ }) // [!code ++] +Return the data the browser is allowed to see, not an entire database record. Keep connection setup and secrets on the server. For a database-backed application, preserve your schema and access layer where possible, and change the framework-facing handler around them. -+ function Home() { // [!code ++] - return ( -
- ) -} -``` +## Translate mutations and their invalidation -### 6. Are we migrated yet? +The reference's Next.js form calls a Server Action. That Action authorizes the session, changes the saved flag, and calls `revalidatePath('/saved')`. The Start version calls a POST server function through `useServerFn`, then awaits `router.invalidate()` to reload the active route data. -Before you can run the development server, you need to create a file that will define the behavior of TanStack Router within TanStack Start. +These invalidation APIs operate on different caches. `router.invalidate()` does not purge a CDN, clear a database cache, or revalidate all statically generated pages. If the app uses TanStack Query, invalidate the relevant query keys as well. Map each existing `revalidatePath`, tag, and cache directive to the layer that owns the replacement data. -- `src/router.tsx` +The Start function checks authorization even though the route already checks it. A caller can invoke the mutation without visiting the page. Validate every untrusted input inside the server boundary and preserve resource-level permissions. -```tsx -import { createRouter } from '@tanstack/react-router' -import { routeTree } from './routeTree.gen' +`useServerFn` returns a callable function. The reference keeps pending and error state in the component and reloads route data after a successful mutation. It also tests replaying the mutation after sign-out. -export function getRouter() { - const router = createRouter({ - routeTree, - scrollRestoration: true, - }) +Next.js Action forms and these Start event-handler forms have different no-JavaScript behavior. The latter require JavaScript and keep their fields disabled until hydration. If progressive enhancement is a requirement, use a FormData-compatible [server function URL](./guide/server-functions#progressive-enhancement) or an ordinary form POST to a [server route](./guide/server-routes). Include validation, CSRF protection, and an appropriate response or redirect. Do not treat `createServerFn` as a drop-in replacement for the React form Action protocol. - return router -} -``` +## Preserve authentication and session boundaries -> 🧠 Here you can configure everything from the default [preloading functionality](/router/latest/docs/framework/react/guide/preloading) to [caching staleness](/router/latest/docs/framework/react/guide/data-loading). +Follow the [authentication guide](./guide/authentication) for the route-context pattern. Check sessions on the server for private reads and mutations. A hidden button or a client route guard is not authorization. -Don't worry if you see some TypeScript errors at this point; the next step will resolve them. +The example keeps `iron-session` and replaces Next.js `cookies()` with a small adapter using Start's `getCookie` and `setCookie`. Start does not provide a session API. The example uses different cookie names to keep its two local apps independent; sharing a library alone does not make every session configuration compatible. A real migration can keep its existing auth provider or session service and adapt the request boundary instead. If sessions must survive cutover or rollback, verify cookie names, domains, paths, signing/encryption formats, expiration, key rotation, and logout in both deployments. -### 7. Verify the Migration +Private pages need a cache policy that prevents another user receiving personalized HTML. The Start reference returns `Cache-Control: private, no-store` for `/saved`. Check the final response through your deployment and CDN, including after sign-in and sign-out. Do not prerender or publicly cache pages that include private account data. -Run the development server: +## Preserve metadata and search responses -```sh -npm run dev -``` +Next.js `metadata` and `generateMetadata` become a Start route's `head` configuration. The article route derives title, description, Open Graph title, and canonical from its loader result. Keep `HeadContent` in the root document so those values appear in the response. -Then, visit `http://localhost:3000`. You should see the TanStack Start welcome page with its logo and a documentation link. +Compare HTML responses before JavaScript runs, then check the head after client navigation. Keep the public canonical origin independent of a local or preview host. Preserve locale alternates and social images where your app has them. See [SEO](./guide/seo) and [head management](/router/latest/docs/guide/document-head-management). -> If you encounter issues, review the steps above and ensure that file names and paths match exactly. For a reference implementation, see the [post-migration repository](https://github.com/nrjdalal/next-to-start). +Next.js metadata file conventions also need replacements. The reference turns `app/sitemap.ts` into a Start server route at `/sitemap.xml`. Migrate `robots.txt`, icons, manifests, and generated social images explicitly. Return real 404s for missing content and maintain intentional permanent redirects. Avoid redirecting every missing URL to the homepage. -## Next Steps (Advanced) +## Replace image and font services deliberately -Now that you have migrated the basic structure of your Next.js application to TanStack Start, you can explore more advanced features and concepts. +Start does not automatically provide the Next.js image optimizer. Preserve image dimensions, responsive sources, loading behavior, alt text, and cache policy. Plain `` works for preprocessed assets; an image component such as Unpic needs a compatible image service or prepared sources to provide transformations. It does not create Next.js's image processing backend by itself. Next.js also supports its optimizer when [self-hosted](https://nextjs.org/docs/app/guides/self-hosting). -### Routing Concepts +Replace `next/font` with self-hosted font files, a package such as Fontsource, or another chosen font delivery method. CSS `@font-face` does not require Tailwind. Preserve font weights and subsets, set an appropriate `font-display`, and check layout shift and network requests. Copy public assets and update imports only after confirming their resulting URLs. -| Route Example | Next.js | TanStack Start | -| ------------------------------ | ---------------------------------- | ------------------------- | -| Root Layout | `src/app/layout.tsx` | `src/app/__root.tsx` | -| `/` (Home Page) | `src/app/page.tsx` | `src/app/index.tsx` | -| `/posts` (Static Route) | `src/app/posts/page.tsx` | `src/app/posts.tsx` | -| `/posts/[slug]` (Dynamic) | `src/app/posts/[slug]/page.tsx` | `src/app/posts/$slug.tsx` | -| `/posts/[...slug]` (Catch-All) | `src/app/posts/[...slug]/page.tsx` | `src/app/posts/$.tsx` | -| `/api/endpoint` (API Route) | `src/app/api/endpoint/route.ts` | `src/app/api/endpoint.ts` | +The reference uses text and the browser's default font. It does not claim to verify your image transformations or font loading. -Learn more about the [Routing Concepts](/router/latest/docs/framework/react/routing/routing-concepts). +## Rebuild caching and deployment behavior -### Dynamic and Catch-All Routes +List each cache separately: browser data, Router loaders, Query, server data, generated pages, and CDN responses. Define what populates it, its key, expiration, and the operation that invalidates it. Test after changing data, signing out, and deploying a new version. -Retrieving dynamic route parameters in TanStack Start is straightforward. +Next.js cache directives, revalidation, and `generateStaticParams` do not carry across automatically. Use [static prerendering](./guide/static-prerendering) only for suitable public routes, and review [ISR](./guide/isr) with your hosting provider's actual behavior. A cache header alone is not proof of equivalent regeneration or invalidation. -```tsx -- export default async function Page({ // [!code --] -- params, // [!code --] -- }: { // [!code --] -- params: Promise<{ slug: string }> // [!code --] -- }) { // [!code --] -+ export const Route = createFileRoute('/app/posts/$slug')({ // [!code ++] -+ component: Page, // [!code ++] -+ }) // [!code ++] +Move server-only environment variables into the server runtime. Audit any public variable prefix changes rather than exposing the old environment wholesale. Verify API/webhook URLs, forwarded host/protocol, cookies behind a proxy, asset paths, streaming, and runtime limits in the deployment you will use. -+ function Page() { // [!code ++] -- const { slug } = await params // [!code --] -+ const { slug } = Route.useParams() // [!code ++] - return
My Post: {slug}
-} -``` +## Cut over with a rollback path -> Note: If you've made a catch-all route (like `src/app/posts/$.tsx`), you can access the parameters via `const { _splat } = Route.useParams()`. +1. Build both applications and run the contract checks against a staging deployment of Start. Include real representative data, authenticated sessions, and the CDN in that check. +2. Keep the current database schema compatible with both versions during the transition. Separate destructive schema changes from the framework cutover. +3. Preserve the public origin and paths where possible. If paths must change, deploy tested redirects and update internal links, canonicals, and sitemaps together. +4. Record the previous deployment and routing configuration. Know how to route traffic back, and what happens to sessions and writes if you do. +5. Monitor error rates, login and mutation failures, response status, indexing signals, and application conversion events after cutover. Compare against the baseline rather than assuming a framework change will improve search traffic. -Similarly, you can access `searchParams` using `const { page, filter, sort } = Route.useSearch()`. - -Learn more about the [Dynamic and Catch-All Routes](/router/latest/docs/framework/react/routing/routing-concepts#dynamic-route-segments). - -### Links - -```tsx -- import Link from "next/link" // [!code --] -+ import { Link } from "@tanstack/react-router" // [!code ++] - -function Component() { -- return Dashboard // [!code --] -+ return Dashboard // [!code ++] -} -``` - -Learn more about the [Links](/router/latest/docs/framework/react/guide/navigation#link-component). - -### Images - -Next.js uses the `next/image` component for optimized images. In TanStack Start, you can use the package called [Unpic](https://unpic.pics/) for similar functionality -and almost a drop-in replacement. - -```tsx -import Image from 'next/image' // [!code --] -import { Image } from '@unpic/react' // [!code ++] -function Component() { - return ( - Description - ) -} -``` - -### Server ~Actions~ Functions - -```tsx -- 'use server' // [!code --] -+ import { createServerFn } from "@tanstack/react-start" // [!code ++] - -- export const create = async () => { // [!code --] -+ export const create = createServerFn().handler(async () => { // [!code ++] - return true -- } // [!code --] -+ }) // [!code ++] -``` - -Learn more about the [Server Functions](./guide/server-functions). - -### Server Routes ~Handlers~ - -```ts -- export async function GET() { // [!code --] -+ export const Route = createFileRoute('/api/hello')({ // [!code ++] -+ server: { // [!code ++] -+ handlers: { // [!code ++] -+ GET: async () => { // [!code ++] -+ return Response.json("Hello, World!") -+ } // [!code ++] -+ } // [!code ++] -+ } // [!code ++] -+ }) // [!code ++] -``` - -Learn more about the [Server Routes](./guide/server-routes). - -### Fonts - -```tsx -- import { Inter } from "next/font/google" // [!code --] - -- const inter = Inter({ // [!code --] -- subsets: ["latin"], // [!code --] -- display: "swap", // [!code --] -- }) // [!code --] - -- export default function Page() { // [!code --] -- return

Font Sans

// [!code --] -- } // [!code --] -``` - -Instead of `next/font`, use Tailwind CSS’s CSS-first approach. Install fonts (for example, from [Fontsource](https://github.com/fontsource/fontsource)): - -```sh -npm i -D @fontsource-variable/dm-sans @fontsource-variable/jetbrains-mono -``` - -Add the following to `src/app/globals.css`: - -```css -@import 'tailwindcss' source('../'); - -@import '@fontsource-variable/dm-sans'; /* [!code ++] */ -@import '@fontsource-variable/jetbrains-mono'; /* [!code ++] */ - -@theme inline { - --font-sans: 'DM Sans Variable', sans-serif; /* [!code ++] */ - --font-mono: 'JetBrains Mono Variable', monospace; /* [!code ++] */ - /* ... */ -} - -/* ... */ -``` - -### Fetching Data - -```tsx -- export default async function Page() { // [!code --] -+ export const Route = createFileRoute('/')({ // [!code ++] -+ component: Page, // [!code ++] -+ loader: async () => { // [!code ++] -+ const res = await fetch('https://api.vercel.app/blog') // [!code ++] -+ return res.json() // [!code ++] -+ }, // [!code ++] -+ }) // [!code ++] - -+ function Page() { // [!code ++] -- const data = await fetch('https://api.vercel.app/blog') // [!code --] -- const posts = await data.json() // [!code --] -+ const posts = Route.useLoaderData() // [!code ++] - - return ( -
    - {posts.map((post) => ( -
  • {post.title}
  • - ))} -
- ) -} -``` +Remove Next.js and its unused configuration after the migrated behavior and rollback plan are verified. Retain historical redirects and any assets still referenced by public content. diff --git a/docs/start/framework/react/migrate-from-release-candidate.md b/docs/start/framework/react/migrate-from-release-candidate.md new file mode 100644 index 0000000000..5cfa614cda --- /dev/null +++ b/docs/start/framework/react/migrate-from-release-candidate.md @@ -0,0 +1,39 @@ +--- +id: migrate-from-release-candidate +title: Migrate from the Release Candidate +description: Upgrade a TanStack Start release-candidate app to the first stable release, 1.169. +--- + +`@tanstack/react-start` 1.169 is the first stable release of TanStack Start. Upgrading from a release candidate means replacing the removed APIs below and checking the behavior changes that apply to your app. + +## Vite 8 + +Start requires Vite 8 when you build with Vite. Upgrade with Vite's [migration guide](https://vite.dev/guide/migration). + +## Removed APIs + +| Removed | Use instead | +| ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `@tanstack/nitro-v2-vite-plugin` | `nitro()` from `nitro/vite`. See [Nitro hosting](./guide/hosting#nitro). | +| `useSession` | A session library such as iron-session. See [Session Management](./guide/authentication#2-session-management). The new library cannot read existing Start session cookies: use a new cookie name and sign users in again, or test a migration that reads the old cookies first. | +| `.inputValidator()` on server functions and middleware | `.validator()`, which takes the same validator. | + +## Errors + +- A handler returned by `createStartHandler(...)` now rethrows the original error. `createServerEntry` converts errors to responses, and the built-in entry already uses it. In a custom entry, catch inside the `createServerEntry` callback and `return handleStartError(error)` or rethrow. See [Error Handling](./guide/server-entry-point#error-handling). +- Uncaught errors produce a generic JSON body with a status from `400` to `599` (`500` by default), even if a success status was set before the error. Return a `Response` when an endpoint needs a specific error payload. +- A server-function call rejects with whatever was thrown, including a `Response` and falsy values such as `undefined`. Return a `Response` to resolve the call with it. See [Raw Responses](./guide/server-functions#raw-responses). +- Errors thrown by request middleware during a server-function call are sent to the client with their message, and their status is no longer always `500`. + +## Responses + +- Response helpers override the response you return or throw. `setResponseStatus(401)` followed by returning a `200` response sends `401`. +- `setResponseHeader('set-cookie', cookie)` replaces all outgoing cookies. Use `setCookie` or `appendResponseHeader('set-cookie', cookie)` to add one. +- `setResponseStatus` ignores codes outside `200`-`599` and warns outside production. +- Serialized server-function replies never carry `Location`, `Content-Encoding`, or `Content-Length` from helpers, and ignore a helper `204`, `205`, or `304`. Use `redirect()` to redirect. + +## Requests and middleware + +- `getRequestHeader(name)` returns `''` for a header that is present but empty, and `undefined` only when it is missing. +- A path with invalid percent-encoding, such as `/%E0%A4%A`, gets `400 Bad Request` before your server entry or middleware runs. +- When no function middleware sends context, `sendContext` is `undefined` instead of `{}`. diff --git a/docs/start/framework/react/overview.md b/docs/start/framework/react/overview.md index 3494b7a187..ced7b65458 100644 --- a/docs/start/framework/react/overview.md +++ b/docs/start/framework/react/overview.md @@ -1,12 +1,11 @@ --- id: overview title: TanStack Start Overview +description: Build full-stack React applications with TanStack Start, including server rendering, streaming, server functions, and type-safe routing. --- > [!NOTE] -> TanStack Start is currently in the **Release Candidate** stage! This means it is considered feature-complete and its API is considered stable. -> **This does not mean it is bug-free or without issues, which is why we invite you to try it out and provide feedback!** -> The road to v1 will likely be a quick one, so don't wait too long to try it out! +> TanStack Start is stable. If you're upgrading from a release candidate, follow [Migrate from the Release Candidate](./migrate-from-release-candidate). TanStack Start is a full-stack React framework powered by TanStack Router. It provides a full-document SSR, streaming, server functions, client/server builds, and more. With [Vite](https://vite.dev/) and [Rsbuild](https://rsbuild.dev/) support, it's ready to develop and deploy to the hosting provider or runtime you want. diff --git a/docs/start/framework/react/start-vs-nextjs.md b/docs/start/framework/react/start-vs-nextjs.md index 27b814725f..f1dd175a41 100644 --- a/docs/start/framework/react/start-vs-nextjs.md +++ b/docs/start/framework/react/start-vs-nextjs.md @@ -1,286 +1,67 @@ --- id: start-vs-nextjs title: TanStack Start vs Next.js +description: Compare TanStack Start and Next.js for routing, rendering, server functions, caching, deployment, and the work each framework handles for you. --- -Choosing between TanStack Start and Next.js isn't just about features - it's about understanding what each framework optimizes for and how those decisions cascade through your entire development experience. +TanStack Start is a good fit when you want TanStack Router's typed navigation, search parameters, and loaders in a full-stack application. Next.js is a good fit when you want the App Router's Server Component model and integrated image, font, and metadata tools. Both can build interactive applications and server-rendered websites. -This page explains the fundamental differences, addresses common misconceptions, and helps you make an informed decision. For a feature-by-feature matrix, see the [full comparison table](./comparison). Ready to switch? See the [migration guide](./migrate-from-next-js). +This comparison was checked on September 11, 2026 against the linked documentation, including Next.js 16.3. For a broader feature matrix, see [Start, Next.js, and React Router](./comparison). For a practical migration, see [Migrate from Next.js](./migrate-from-next-js). -**A note on benchmarks:** If someone quotes performance numbers comparing Start and Next without methodology, app complexity, hosting details, and configuration specifics - those numbers are meaningless. Comparisons must assume best practices on both sides. You can't give Next the benefit of optimized usage while assuming Start users misconfigure things. +## Rendering and interactivity -## Two Different Visions of React +Start's React components are server-rendered and hydrated by default. You can change rendering behavior per route with [selective SSR](./guide/selective-ssr), including data-only and client-only rendering. You do not need React Server Components to use Start's server functions or SSR. -Both frameworks want to help you build great React applications. But they start from different assumptions about what "great" means. +Next.js App Router layouts and pages are Server Components by default. A `use client` boundary enables client-side state, effects, and event handlers. It applies to the imported module tree, so you do not add the directive to every interactive component. Client Components can still contribute server-rendered HTML on the initial request. [Next.js component model](https://nextjs.org/docs/app/getting-started/server-and-client-components). -### Next.js: The Platform Play - -Next.js optimizes for **Vercel's vision of the web**: server-first rendering, tight platform integration, and automatic optimizations that work best on their infrastructure. - -The core bet: most web content is static or near-static. Server Components should be the default. Interactivity is the exception you opt into. The framework should make decisions for you, and those decisions should be optimized for their infrastructure. - -This works well if: - -- You're deploying to Vercel and want tight platform integration -- Your app is content-heavy with islands of interactivity -- You want the framework to make architectural decisions for you - -### TanStack Start: The Developer-First Play - -TanStack Start optimizes for **developer control and correctness**: type safety everywhere, explicit over implicit, composable primitives, and deployment freedom. - -The core bet: developers know their apps better than frameworks do. Server rendering is an optimization you opt into where it makes sense. The framework should give you powerful primitives and get out of your way. - -This works well if: - -- You want your deployment target to be a decision you make, not one the framework makes for you -- Your app is highly interactive -- You value type safety and explicit control -- You want to understand exactly what your code is doing - -## The Mental Model Gap - -This is the most important difference to understand. Everything else flows from it. - -### Both SSR - Different Defaults for Interactivity - -Let's be clear: both frameworks SSR by default, and both support static generation and React Server Components. The difference isn't capability - it's how you access those capabilities and how much control you have. - -**Next.js** defaults to Server Components. Every component is a Server Component unless you add `"use client"`. Server Components can't use state, effects, or event handlers - so the path to interactivity requires understanding the framework's implicit boundaries, caching layers, and serialization rules. - -**TanStack Start** defaults to interactive components (traditional React). Your components SSR and hydrate, ready for state and event handlers out of the box. You opt into Server Components where they provide value - for heavy static content, keeping secrets server-side, or reducing bundle size. - -Both approaches get you to the same destination. The question is: which direction feels like swimming upstream for _your_ app? - -Consider: - -- If most of your components need state, effects, or event handlers, Next's defaults mean constant `"use client"` annotations and thinking about serialization boundaries -- If most of your content is static, Start lets you explicitly opt those components into server-only rendering - with clearer control over caching and hydration -- Either way, Start gives you more granular control over _how_ things render, not just _where_ - -### Implicit vs Explicit - -Both frameworks handle the fundamentals - code splitting, caching, SSR, static optimization. The difference is visibility and predictability. **Next.js** layers implicit behaviors: multi-layer server-side caching with a history of breaking changes and community frustration, data fetching conventions tied to file structure, optimizations that require understanding the framework's internals to override. - -**TanStack Start** is explicit without being verbose. Loader functions, cache configuration, middleware chains - they're visible in your code, not hidden behind conventions. This doesn't mean more code; it means the code you write maps directly to what happens at runtime. - -## Architecture Deep Dive - -### The Build Pipeline - -**Next.js** uses a custom build system (historically Webpack, now Turbopack). It's tightly integrated with their architecture, which enables optimizations but limits flexibility. Turbopack has improved dev speed, but it's still no match for Vite or Rsbuild. - -**TanStack Start** supports Vite and Rsbuild. This means: - -- Faster dev server startup -- Faster HMR -- Access to modern plugin ecosystems -- Standard tooling that transfers to other projects - -### The Runtime - -**Next.js** ships a substantial runtime to support Server Components, server-side caching, automatic optimizations, and the App Router's conventions. This runtime has real weight. - -**TanStack Start** ships a minimal runtime. The router is powerful but lean. Server functions are thin RPC wrappers. There's no framework magic layer between you and React. - -Bundle size isn't everything, but it's the baseline everything else builds on. Start's architecture is designed to minimize runtime overhead - even with RSC support, the runtime stays lean. Much of Next's bundle weight is architectural tax, not feature weight. - -### The Type System - -**Next.js** has TypeScript support. **TanStack Start** is built around TypeScript. - -The difference matters: - -- In Next.js, the boundary between client and server creates type gaps. Server Actions can receive data that doesn't match what TypeScript expects. You need runtime validation to be safe. -- In Start, server functions have end-to-end type safety. Input validation, return types, middleware context, route parameters - all checked at compile time. - -In the age of AI-assisted development, end-to-end type safety should be non-negotiable. Types aren't just "nice for DX" - they're correctness guarantees that prevent production errors. +Start's [Server Components support](./guide/server-components) is **experimental and opt-in**. It uses client-led composition of server-produced UI. That is a different integration model from Next.js, and experimental support should not be presented as production feature parity. ## Routing -This is where TanStack shines brightest. TanStack Router (which powers Start) is the most powerful, type-safe router in any framework. +Start inherits [TanStack Router's routing model](/router/latest/docs/guide/type-safety). Route definitions connect the types for links, path parameters, validated search parameters, loaders, and route context. This is useful when application state lives in the URL or when many screens share typed data dependencies. -**Features Next.js doesn't have:** +Next.js also provides compile-time checking for links through its stable, opt-in [`typedRoutes`](https://nextjs.org/docs/app/api-reference/config/next-config-js/typedRoutes) option. Describing it as only IDE hints is inaccurate. The distinction is the scope of inference and validation across your application, not whether Next.js supports TypeScript. -- **Typesafe search params** - Define, validate, and parse search params with full type inference. Next gives you `?foo=bar` as strings; Start gives you validated, typed objects -- **Search param validation & middleware** - Transform and validate search params at the route level -- **Typesafe path params** - Path params are inferred and validated, not just `string | string[]` -- **Typesafe route context** - Pass typed context down through nested routes -- **Path param validation & custom parsing** - Parse `/users/123` as a number, validate it exists -- **Route mount/transition/unmount events** - Hook into the route lifecycle -- **Code-based routes** - Define routes in code when file-based doesn't fit -- **Built-in devtools** - Inspect router state, cache, and pending navigations -- **Element scroll restoration** - Restore scroll position for specific elements, not just the page -- **Navigation blocking** - `useBlocker` for unsaved changes warnings +In either framework, a valid route type does not prove that a database record exists or that a user may access it. Handle missing data and authorization at runtime. -**Type safety that actually works:** - -- Route paths are fully typed - typos are compile errors -- Links validate their destinations - no broken links in production -- Loaders know their route context - no guessing what data is available -- Search params are typed end-to-end - from URL to component - -Next.js has file-based routing that works, but the type safety is superficial (an IDE plugin for link hints) compared to TanStack Router's compile-time guarantees. - -**First-class integrations:** - -TanStack Router was designed from the ground up for isomorphism and hydration. This makes it the foundation for first-class integrations with TanStack Query and other data-fetching libraries. In Next, you wire up Query manually; in Start, it's a supported pattern with official integrations. - -See the [full router comparison](/router/latest/docs/framework/react/comparison) for the complete feature matrix. - -## The Caching Question - -Caching is where the philosophical differences become most visible. - -### Next.js: Implicit and Server-Side - -Next.js caches aggressively by default (or did - they've changed this multiple times). The caching happens in layers: - -- Request memoization -- Data cache -- Full route cache -- Router cache - -Each layer has its own invalidation semantics. The system has been rewritten multiple times with community criticism for being unpredictable. Next 15 simplified the defaults, but the fundamental complexity of server-side RSC stream caching remains. - -When people talk about "component caching," they're referring to caching serialized RSC streams on the server. This is more complicated than most realize: - -- You're caching text streams with complex invalidation semantics -- This happens in lambda-style environments with their own constraints -- Granular invalidation requires explicit tagging setup -- Cache misses cascade through the component tree in ways that aren't always predictable - -**Ask anyone claiming server-side component caching is special:** "How do you invalidate a cached RSC stream when a data dependency changes?" Most can't answer clearly. - -### TanStack Start: RSCs Are Just Data - -Start treats Server Component output the same as any other data flowing through your app. There's no special "component cache" with its own semantics - RSC payloads are data, and you cache data however you want: - -- **TanStack Router** - Built-in SWR-style caching with `staleTime` and `gcTime` -- **TanStack Query** - Full-featured async state management -- **CDN caching** - Standard HTTP cache headers at the edge -- **Redis, database, whatever** - It's just data; use your existing infrastructure - -```tsx -export const Route = createFileRoute('/posts/$postId')({ - loader: async ({ params }) => fetchPost(params.postId), - staleTime: 10_000, // Fresh for 10 seconds - gcTime: 5 * 60_000, // Keep in memory for 5 minutes -}) -``` - -This is the same SWR pattern TanStack Query has battle-tested across millions of applications. No new mental model. No framework-specific caching semantics to learn. No chasing ghosts. - -The caching layers are well-understood and compose naturally: - -- Client-side SWR caching (built into the router) -- CDN caching at the edge (standard HTTP semantics) -- Server-side caching where you want it (explicit, opt-in) - -You already know how to cache data. Start doesn't make you learn a new way. - -### The Bottom Line on RSCs - -Start has full RSC support with feature parity to Next.js. The difference is mental model and cognitive overhead. - -In Next, RSCs are the paradigm - you build around them, think about them constantly, manage their boundaries everywhere. In Start, RSCs are just another data primitive. Fetch them, cache them, compose them - using patterns you already know from TanStack Query and Router. - -We call our approach **Composite Components** - server-produced React components that the client can fetch, cache, stream, and assemble. The client owns composition; the server ships UI pieces. No new mental model. No framework-specific caching semantics. Just data flowing through tools you already understand. - -For the full deep-dive, see [Composite Components: Server Components with Client-Led Composition](https://tanstack.com/blog/composite-components). +For detailed navigation features, see the [Router comparison](/router/latest/docs/comparison). ## Server Functions vs Server Actions -Both frameworks let you call server code from the client. The approaches differ significantly. +Start's [server functions](./guide/server-functions) provide callable server endpoints with inferred inputs and outputs. You can choose GET or POST, supply an input validator, and compose [function middleware](./guide/middleware). Use runtime validation for untrusted inputs and server-side authorization for private data. -### Next.js Server Actions +Next.js Server Actions integrate with forms and React's pending and error-state APIs. They can validate input with a schema too. Receiving `FormData` does not prevent validation, and a TypeScript annotation does not perform validation in either framework. [Next.js forms and validation](https://nextjs.org/docs/app/guides/forms). -```tsx -'use server' +Choose the API that fits your application's data flow. A typed RPC call and a form action solve overlapping problems, but they are not interchangeable in every workflow. -export async function createPost(formData: FormData) { - const title = formData.get('title') - // No compile-time type safety on inputs - return db.posts.create({ title }) -} -``` +## Caching -Server Actions integrate with forms and transitions. They're convenient for simple cases but provide limited type safety at the boundary. +Start uses [TanStack Router's loader cache](/router/latest/docs/guide/data-loading) for navigation data, with options such as `staleTime` and `gcTime`. You can also use the [official Query integration](/router/latest/docs/integrations/query) when you need a separate query cache. Browser data caching, server data caching, and CDN response caching serve different purposes. -### TanStack Server Functions +Next.js documents explicit caching through Cache Components, enabled with `cacheComponents: true`. Its `use cache`, `cacheLife`, and tag-based revalidation APIs control reuse and invalidation. Applications without that option use a different documented caching model. Compare the configuration you intend to run, rather than treating every Next.js version and configuration as having the same defaults. [Next.js caching](https://nextjs.org/docs/app/getting-started/caching). -```tsx -export const createPost = createServerFn({ method: 'POST' }) - .validator(z.object({ title: z.string().min(1) })) - .middleware([authMiddleware]) - .handler(async ({ data, context }) => { - // data is typed and validated - // context comes from middleware, also typed - return db.posts.create({ title: data.title }) - }) -``` +Start's [ISR guide](./guide/isr) describes HTTP caching and provider-specific options. A `Cache-Control` header alone does not guarantee the same regeneration, invalidation, or shared-cache behavior on every host. Verify those behaviors on your deployment target. -Server functions give you: +## Build tools -- **Input validation** - Define schemas, get runtime validation and compile-time types -- **Middleware** - Composable, works on both client and server -- **Full type inference** - From input to output to error handling -- **Explicit RPC** - Clear mental model of what's happening +Start supports [Vite and Rsbuild](./build-from-scratch). Next.js integrates [Turbopack](https://nextjs.org/docs/app/api-reference/turbopack), with its own supported configuration and plugin surface. Your existing build tooling can make one choice easier to adopt. -**Security note:** Start's architecture doesn't parse Flight data on the server - payloads flow one direction (server to client). Recent React security advisories around RSC serialization vulnerabilities don't apply to Start's model. +There is no benchmark in this comparison establishing a startup, HMR, build-time, memory, or runtime-size winner. A router package's bundle size is not the bundle size of a complete Start application. Measure the same application, dependencies, rendering behavior, hardware, and production deployment before drawing performance conclusions. + +## Deployment + +Start has [deployment guides](./guide/hosting) for several providers and runtimes. Check the guide for your chosen bundler and target, especially when you need streaming, image processing, background work, or cache invalidation. + +Next.js supports self-hosting. Its image optimizer works with `next start`, and its documentation covers ISR, shared caches, streaming, and multi-instance deployments. These features are not inherently Vercel-only. Operating them yourself still requires infrastructure configuration. [Next.js self-hosting](https://nextjs.org/docs/app/guides/self-hosting). ## Where Next.js Has the Advantage -Next.js has been around longer. That's not a technical advantage, but it creates real ecosystem effects: +Next.js is worth choosing when your application depends on its established Server Component integration, or when you want the built-in [`next/image`](https://nextjs.org/docs/app/api-reference/components/image), [`next/font`](https://nextjs.org/docs/app/api-reference/components/font), and [metadata conventions](https://nextjs.org/docs/app/getting-started/metadata-and-og-images). Replacing those facilities is migration work, even when alternatives exist. -**More content** - More tutorials, more Stack Overflow answers, more blog posts, more example repos. When you Google a problem, you're more likely to find a Next-specific answer. +If your team already maintains a working Next.js application, keep that experience and migration cost in the decision. A different routing model is not, by itself, a reason to rewrite a healthy application. -**Mindshare** - Next is the default recommendation in many circles. That means more developers have used it, which means more content, which reinforces the cycle. +## When to Choose TanStack Start -**Vercel integration** - Next.js is built by Vercel, so new Vercel platform features often ship with Next.js support first. That said, Start works great on Vercel too - you're not giving up preview deployments or edge functions by choosing Start. You're just not locked into Vercel as the only first-class option. +Start is worth choosing when typed URL state, route context, explicit loaders, and callable server functions fit how you build applications. Its [Router integration](./guide/routing), [selective SSR](./guide/selective-ssr), and [middleware](./guide/middleware) are concrete reasons to try it. -**Built-in image/font optimization** - Start supports image optimization via pluggable solutions (like [Unpic](https://unpic.pics/)), but it's not built-in. Whether "built-in" is better than "pluggable" depends on whether you want the framework making that choice for you. - -None of these are technical superiority - they're ecosystem and business model advantages. On the technical merits, we're confident in Start's approach. - -## What Start Does Better - -With RSC support, the question isn't "what does Start lack?" - it's: **"Why give up Start's router, type safety, caching design, and simpler mental model for Next's API design?"** - -**Type safety** - End-to-end, not bolted on. This prevents bugs and enables confident refactoring. - -**Routing** - The most powerful, type-safe router in any framework. Search params, path params, loaders, middleware - all fully typed. - -**Caching model** - Explicit SWR primitives you already understand if you've used TanStack Query. No implicit layers to debug. - -**Dev experience** - Vite and Rsbuild are fast. Instant startup, fast HMR, lower resource usage. This compounds over a workday - and even more so when AI agents are iterating on your code in tight loops. - -**Deployment as a feature** - Start treats deployment flexibility as a first-class feature. Cloudflare, Netlify, AWS, Fly, Railway, your own servers - they're all equally supported. Your app works the same everywhere because it's built on standards, not platform-specific optimizations. This means you can: - -- Choose hosting based on price, performance, or proximity to your users -- Switch providers without rewriting deployment logic -- Run the same code in development, staging, and production across different platforms -- Avoid accumulating platform-specific patterns that create friction later - -**Middleware** - Composable middleware that works at both the request level AND the server function level, on both client and server. - -**Debugging** - Predictable execution. When something breaks, you can trace it. No abstraction layers hiding behavior. - -## Summary - -| Aspect | TanStack Start | Next.js | -| -------------------- | ------------------------------------ | ------------------------------------- | -| **Philosophy** | Developer control, explicit patterns | Platform integration, conventions | -| **Components** | Interactive by default, opt into RSC | Server Components by default | -| **Type safety** | End-to-end, compile-time | TypeScript support with boundary gaps | -| **Server functions** | Typed, validated, middleware support | Untyped boundary, no middleware | -| **Caching** | Explicit SWR primitives | Multi-layer implicit caching | -| **Build tool** | Vite or Rsbuild | Turbopack/Webpack | -| **Deployment** | Equal support everywhere | Optimized for Vercel | -| **Routing** | Best-in-class type safety | File-based, basic types | -| **RSC** | Supported | Supported | -| **Maturity** | 2+ years, approaching 1.0 | 8+ years, historically unstable APIs | - ---- - -> **Ready to try Start?** See the [Getting Started guide](./getting-started) or [migrate from Next.js](./migrate-from-next-js). +Build one representative route before committing to a migration: load real data, validate search parameters, submit a mutation, handle unauthorized access, and deploy it. If those tasks become easier to maintain, you have evidence that Start fits your application. Continue with [Getting Started](./getting-started) or the [Next.js migration guide](./migrate-from-next-js). diff --git a/docs/start/framework/react/tutorial/reading-writing-file.md b/docs/start/framework/react/tutorial/reading-writing-file.md index 11b1be0794..f4af4480f1 100644 --- a/docs/start/framework/react/tutorial/reading-writing-file.md +++ b/docs/start/framework/react/tutorial/reading-writing-file.md @@ -152,7 +152,7 @@ export type JokesData = Joke[] ### Step 1.3: Create Server Functions to Read the File -Let's create a new file `src/serverActions/jokesActions.ts` to create a server function to perform a read-write operation. We will be creating a server function using [`createServerFn`](https://tanstack.com/start/latest/docs/framework/react/server-functions). +Let's create a new file `src/serverActions/jokesActions.ts` to create a server function to perform a read-write operation. We will be creating a server function using [`createServerFn`](https://tanstack.com/start/latest/docs/framework/react/guide/server-functions). ```tsx // src/serverActions/jokesActions.ts diff --git a/docs/start/framework/solid/guide/authentication.md b/docs/start/framework/solid/guide/authentication.md index 8ae205ef21..460a58747c 100644 --- a/docs/start/framework/solid/guide/authentication.md +++ b/docs/start/framework/solid/guide/authentication.md @@ -1,11 +1,12 @@ --- id: authentication -title: Authentication +title: Implement Authentication in SolidJS +description: Implement sessions, sign-in, sign-out, protected routes, and server-side authorization in a TanStack Start SolidJS app. --- -This guide covers authentication patterns and shows how to implement your own authentication system with TanStack Start. +Implement the authentication workflow in your SolidJS app, from sessions and sign-in to protected routes and authorization. -> **📋 Before You Start:** Check our [Authentication Overview](./authentication-overview.md) for all available options including partner solutions and hosted services. +To compare libraries and hosted services, read [Choose Authentication for SolidJS Apps](./authentication-overview.md). ## Authentication Approaches @@ -34,7 +35,7 @@ Authentication involves many considerations including password security, session - **Authentication**: Who is this user? (Login/logout) - **Authorization**: What can this user do? (Permissions/roles) -TanStack Start provides the tools for both through server functions, sessions, and route protection. +TanStack Start provides server functions, request and cookie utilities, and route protection. Session storage and authentication come from your application or a library you choose. > Protect the data/API boundary first. Any server function, server route, or other API endpoint that returns or mutates private data must authorize the request itself. `beforeLoad` is useful for route UX: it keeps users out of screens they cannot use and avoids triggering work that would fail anyway. It is not the security boundary for the data. See [Authentication Server Primitives](./authentication-server-primitives.md) for the server-side pattern. @@ -47,6 +48,7 @@ Server functions handle sensitive authentication logic securely on the server: ```tsx import { createServerFn } from '@tanstack/solid-start' import { redirect } from '@tanstack/solid-router' +import { getAppSession } from '~/utils/session' // Login server function export const loginFn = createServerFn({ method: 'POST' }) @@ -60,11 +62,9 @@ export const loginFn = createServerFn({ method: 'POST' }) } // Create session - const session = await useAppSession() - await session.update({ - userId: user.id, - email: user.email, - }) + const session = await getAppSession() + session.userId = user.id + await session.save() // Redirect to protected area throw redirect({ to: '/dashboard' }) @@ -72,98 +72,131 @@ export const loginFn = createServerFn({ method: 'POST' }) // Logout server function export const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await useAppSession() - await session.clear() + const session = await getAppSession() + session.destroy() throw redirect({ to: '/' }) }) // Get current user export const getCurrentUserFn = createServerFn({ method: 'GET' }).handler( async () => { - const session = await useAppSession() - const userId = session.get('userId') + const session = await getAppSession() + const userId = session.userId if (!userId) { return null } - return await getUserById(userId) + const user = await getUserById(userId) + return user ? { id: user.id, email: user.email, role: user.role } : null }, ) ``` ### 2. Session Management -TanStack Start provides secure HTTP-only cookie sessions: +Start does not provide a session API. This guide uses iron-session for encrypted cookie sessions. Start's cookie helpers connect it to server functions, server routes, and request middleware. + +For encrypted cookie sessions, install [iron-session](https://github.com/vvo/iron-session): + +```sh +pnpm add iron-session +``` + +This example uses iron-session 9's cookie adapter. Its Node runtime requires Node 22.13 or newer; check the library's runtime requirements for other deployment targets. ```tsx -// utils/session.ts -import { useSession } from '@tanstack/solid-start/server' +// utils/session.ts — import only from server code +import { getIronSession } from 'iron-session' +import { getCookie, setCookie } from '@tanstack/solid-start/server' type SessionData = { - userId?: string - email?: string - role?: string + userId: string + oauthState: string } -export function useAppSession() { - return useSession({ - // Session configuration - name: 'app-session', - password: process.env.SESSION_SECRET!, // At least 32 characters - // Optional: customize cookie settings - cookie: { - secure: process.env.NODE_ENV === 'production', - sameSite: 'lax', - httpOnly: true, +export function getAppSession(ttl = 7 * 24 * 60 * 60) { + const password = process.env.SESSION_SECRET + if (!password || password.length < 32) { + throw new Error('SESSION_SECRET must be at least 32 characters') + } + + return getIronSession( + { read: getCookie, write: setCookie }, + { + cookieName: 'app-session', + password, + ttl, + cookieOptions: { + secure: process.env.NODE_ENV === 'production', + sameSite: 'lax', + httpOnly: true, + path: '/', + }, }, - }) + ) } ``` +Read fields directly from the returned session, change them, then `await session.save()` before returning or redirecting. Missing or expired sessions have no user ID. `session.destroy()` removes the browser cookie. Keep one session object for the operation; another call to `getAppSession()` reads the incoming request again. For middleware, pass that object through request context when downstream code needs the same mutations. + +The `getAppSession` helper belongs to your application. Start does not cache sessions, choose expiration rules, or synchronize concurrent writes. Keep secrets and session objects in server code, and read request-specific configuration inside the active request. + ### 3. Authentication Context -Share authentication state across your application: +Load the current user in your root route's `beforeLoad` so the initial server render and child routes receive the same authentication state. `useServerFn` returns a callable function, not an object with `data`, `isLoading`, or `refetch`. You can call a server function directly from `beforeLoad`. + +Merge this pattern into your existing root route, keeping its metadata and document shell: ```tsx -// contexts/auth.tsx -import { createContext, useContext } from 'solid-js' -import { useServerFn } from '@tanstack/solid-start' +// routes/__root.tsx +import { + createRootRoute, + HeadContent, + Outlet, + Scripts, +} from '@tanstack/solid-router' +import type { JSX } from 'solid-js' import { getCurrentUserFn } from '../server/auth' -type User = { - id: string - email: string - role: string -} - -type AuthContextType = { - user: User | null - isLoading: boolean - refetch: () => void -} - -const AuthContext = createContext(undefined) - -export function AuthProvider(props) { - const { data: user, isLoading, refetch } = useServerFn(getCurrentUserFn) +export const Route = createRootRoute({ + headers: () => ({ 'Cache-Control': 'private, no-store' }), + beforeLoad: async () => ({ user: await getCurrentUserFn() }), + component: Outlet, + shellComponent: RootDocument, +}) +function RootDocument({ children }: { children: JSX.Element }) { return ( - - {props.children} - + + + + + + {children} + + + ) } +``` -export function useAuth() { - const context = useContext(AuthContext) - if (!context) { - throw new Error('useAuth must be used within AuthProvider') - } - return context +The root includes session-specific data, so its responses use `Cache-Control: private, no-store`. Keep that policy on child routes that render this data, and do not override it with public caching at your CDN. + +Read that state from a descendant component: + +```tsx +// components/AuthStatus.tsx +import { Route } from '../routes/__root' + +export function AuthStatus() { + const context = Route.useRouteContext() + return {context().user?.email ?? 'Signed out'} } ``` +After login or logout changes the session, call `await router.invalidate()` to reload the current user and rerun route guards. Keep private-data authorization in the server function itself, even when a route already checks the user. + ### 4. Route Protection Protect routes using `beforeLoad`: @@ -240,8 +273,9 @@ export const registerFn = createServerFn({ method: 'POST' }) }) // Create session - const session = await useAppSession() - await session.update({ userId: user.id }) + const session = await getAppSession() + session.userId = user.id + await session.save() return { success: true, user: { id: user.id, email: user.email } } }) @@ -309,8 +343,9 @@ export const initiateOAuthFn = createServerFn({ method: 'POST' }) const state = generateRandomState() // Store state in session for CSRF protection - const session = await useAppSession() - await session.update({ oauthState: state }) + const session = await getAppSession() + session.oauthState = state + await session.save() // Generate OAuth URL const authUrl = generateOAuthUrl(provider, state) @@ -373,21 +408,9 @@ const hashedPassword = await bcrypt.hash(password, saltRounds) ### 2. Session Security -```tsx -// Use secure session configuration -export function useAppSession() { - return useSession({ - name: 'app-session', - password: process.env.SESSION_SECRET!, // 32+ characters - cookie: { - secure: process.env.NODE_ENV === 'production', // HTTPS only in production - sameSite: 'lax', // CSRF protection - httpOnly: true, // XSS protection - maxAge: 7 * 24 * 60 * 60, // 7 days - }, - }) -} -``` +Set the library's server-validated expiration as well as appropriate cookie attributes. In the iron-session example, `ttl` limits a sealed credential's lifetime from its latest save; saving again renews it. A numeric `cookieOptions.maxAge` controls browser retention. In iron-session 9, explicitly setting `maxAge: undefined` also disables seal expiry; omit the property to use the configured `ttl`. Use an application-validated timestamp or a server-side record if you also need an absolute lifetime that writes cannot extend. + +Use `httpOnly`, `sameSite`, and `path` deliberately, and require `secure: true` on HTTPS deployments. These cookie attributes complement server-side authorization and CSRF protections. Keep only the minimum session data and load current account permissions from their authoritative store. Logout removes a stateless cookie from the current browser; it cannot revoke a copy without server-side state. ### 3. Rate Limiting @@ -489,28 +512,70 @@ describe('Authentication Flow', () => { ### Loading States +Call the function returned by `useServerFn` with `{ data }`. Track pending state in the component, handle invalid credentials, and refresh route context after a successful login. This form uses the `loginFn` from the server-functions example above. It requires JavaScript, so the fields stay disabled until hydration; `method="post"` also prevents credentials appearing in a native GET submission. + ```tsx -function LoginForm() { +// components/LoginForm.tsx +import { createSignal } from 'solid-js' +import { useHydrated, useRouter } from '@tanstack/solid-router' +import { useServerFn } from '@tanstack/solid-start' +import { loginFn } from '../server/auth' + +export function LoginForm() { + const hydrated = useHydrated() const [isLoading, setIsLoading] = createSignal(false) - const loginMutation = useServerFn(loginFn) + const [error, setError] = createSignal('') + const login = useServerFn(loginFn) + const router = useRouter() + + const handleSubmit = async ( + event: SubmitEvent & { currentTarget: HTMLFormElement }, + ) => { + event.preventDefault() + const formData = new FormData(event.currentTarget) + const email = formData.get('email') + const password = formData.get('password') + if (typeof email !== 'string' || typeof password !== 'string') { + return + } - const handleSubmit = async (data: LoginData) => { setIsLoading(true) + setError('') try { - await loginMutation.mutate(data) - } catch (error) { - // Handle error + const result = await login({ data: { email, password } }) + if (result?.error) { + setError(result.error) + return + } + await router.invalidate() + } catch { + setError('Login failed. Please try again.') } finally { setIsLoading(false) } } return ( -
- {/* Form fields */} - + +
+ + + +
+

{error()}

) } @@ -525,16 +590,14 @@ export const loginFn = createServerFn({ method: 'POST' }) ) .handler(async ({ data }) => { const user = await authenticateUser(data.email, data.password) - if (!user) return { error: 'Invalid credentials' } + if (!user) { + return { error: 'Invalid credentials' } + } - const session = await useAppSession() - await session.update( - { userId: user.id }, - { - // Extend session if remember me is checked - maxAge: data.rememberMe ? 30 * 24 * 60 * 60 : undefined, // 30 days vs session - }, - ) + const ttl = data.rememberMe ? 30 * 24 * 60 * 60 : 8 * 60 * 60 + const session = await getAppSession(ttl) + session.userId = user.id + await session.save() return { success: true } }) @@ -554,7 +617,6 @@ If you're migrating from client-side authentication (localStorage, context only) ### From Other Frameworks - **Next.js**: Replace API routes with server functions, migrate NextAuth sessions -- **Remix**: Convert loaders/actions to server functions, adapt session patterns - **SvelteKit**: Move form actions to server functions, update route protection ## Production Considerations diff --git a/docs/start/framework/solid/guide/client-entry-point.md b/docs/start/framework/solid/guide/client-entry-point.md index b73408e8e4..929efc7a2d 100644 --- a/docs/start/framework/solid/guide/client-entry-point.md +++ b/docs/start/framework/solid/guide/client-entry-point.md @@ -3,8 +3,6 @@ id: client-entry-point title: Client Entry Point --- -# Client Entry Point - > [!NOTE] > The client entry point is **optional** out of the box. If not provided, TanStack Start will automatically handle the client entry point for you using the below as a default. diff --git a/docs/start/framework/solid/guide/reading-writing-file.md b/docs/start/framework/solid/guide/reading-writing-file.md deleted file mode 100644 index 5aa48d8188..0000000000 --- a/docs/start/framework/solid/guide/reading-writing-file.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -ref: docs/start/framework/react/guide/reading-writing-file.md -replace: - { '@tanstack/react-start': '@tanstack/solid-start', 'React': 'SolidJS' } ---- diff --git a/docs/start/framework/solid/migrate-from-release-candidate.md b/docs/start/framework/solid/migrate-from-release-candidate.md new file mode 100644 index 0000000000..9f988a14fc --- /dev/null +++ b/docs/start/framework/solid/migrate-from-release-candidate.md @@ -0,0 +1,8 @@ +--- +ref: docs/start/framework/react/migrate-from-release-candidate.md +replace: + { + '@tanstack/react-start': '@tanstack/solid-start', + '@tanstack/react-router': '@tanstack/solid-router', + } +--- diff --git a/docs/start/framework/solid/tutorial/reading-writing-file.md b/docs/start/framework/solid/tutorial/reading-writing-file.md index de3d4d472e..09b58c38f5 100644 --- a/docs/start/framework/solid/tutorial/reading-writing-file.md +++ b/docs/start/framework/solid/tutorial/reading-writing-file.md @@ -1,6 +1,8 @@ --- id: reading-and-writing-file title: Building a Full Stack DevJokes App with TanStack Start +redirect_from: + - /framework/solid/guide/reading-writing-file --- This tutorial will guide you through building a complete full-stack application using TanStack Start. You'll create a DevJokes app where users can view and add developer-themed jokes, demonstrating key concepts of TanStack Start including server functions, file-based data storage, and Solid components. @@ -152,7 +154,7 @@ export type JokesData = Joke[] ### Step 1.3: Create Server Functions to Read the File -Let's create a new file `src/serverActions/jokesActions.ts` to create a server function to perform a read-write operation. We will be creating a server function using [`createServerFn`](https://tanstack.com/start/latest/docs/framework/solid/server-functions). +Let's create a new file `src/serverActions/jokesActions.ts` to create a server function to perform a read-write operation. We will be creating a server function using [`createServerFn`](https://tanstack.com/start/latest/docs/framework/solid/guide/server-functions). ```tsx // src/serverActions/jokesActions.ts diff --git a/e2e/AGENTS.md b/e2e/AGENTS.md new file mode 100644 index 0000000000..f373ecba4f --- /dev/null +++ b/e2e/AGENTS.md @@ -0,0 +1,9 @@ +# E2E tests + +- Read the project's `package.json` and test config. Inspect resolved targets with `CI=1 NX_DAEMON=false pnpm nx show project --json`: `nx.metadata.playwrightModes` generates modes, variants, and shards. The aggregate `test:e2e` can also run extra package-script suites. For focused Playwright runs, select an executable test target (a mode/shard target when inferred) and append filters after `--` (e.g. `-- tests/navigation.spec.ts --grep "redirect"`). +- Check Playwright's `webServer.command` to select dev or production coverage. A mode named `ssr` can still start a dev server. `e2e/eslint-plugin-start` uses Vitest instead of Playwright. +- For inferred Playwright modes, Nx builds first and supplies `MODE`, `E2E_TOOLCHAIN`, `E2E_DIST_DIR`, and `E2E_PORT_KEY`. Preserve these in server/config changes; let Nx own the build while `webServer.command` only starts the selected server. Target generation lives in [`scripts/nx/playwright-plugin.ts`](../scripts/nx/playwright-plugin.ts). +- Use the same `E2E_PORT_KEY`-aware key throughout config, app, and dummy-server setup/teardown. Clean only that key's port files, before allocation, when `TEST_WORKER_INDEX === undefined`; worker config reloads must not remap a running server's port. +- For new browser tests, reuse the local error-checking fixture. The shared `test` from `@tanstack/router-e2e-utils` fails on unexpected `console.error`, including hydration errors; allow only expected errors with `whitelistErrors`. +- HMR/watch tests edit real app sources. Reuse existing edit/restore helpers such as `createHmrFileEditor`, restore edits in teardown even after failures, and preserve the suites' single-worker and Nx `parallelism: false` settings. +- `@tanstack/router-e2e-utils:test:unit` is a placeholder. Validate helper changes through consuming e2e projects. diff --git a/e2e/e2e-utils/mock-api.mjs b/e2e/e2e-utils/mock-api.mjs new file mode 100644 index 0000000000..f92ec840e5 --- /dev/null +++ b/e2e/e2e-utils/mock-api.mjs @@ -0,0 +1,4 @@ +import { setupServer } from 'msw/node' +import { apiHandlers } from './src/api-handlers.ts' + +setupServer(...apiHandlers).listen({ onUnhandledRequest: 'bypass' }) diff --git a/e2e/e2e-utils/package.json b/e2e/e2e-utils/package.json index a0708e0475..fcfa5f8dc0 100644 --- a/e2e/e2e-utils/package.json +++ b/e2e/e2e-utils/package.json @@ -5,7 +5,7 @@ "clean": "rimraf ./dist && rimraf ./coverage", "build": "vite build", "test:eslint": "eslint ./src", - "test:unit": "exit 0; vitest --typecheck" + "test:unit": "vitest run" }, "type": "module", "types": "dist/types/index.d.ts", @@ -22,7 +22,8 @@ "default": "./dist/cjs/index.cjs" } }, - "./package.json": "./package.json" + "./package.json": "./package.json", + "./mock-api": "./mock-api.mjs" }, "sideEffects": false, "files": [ @@ -30,12 +31,14 @@ "src" ], "engines": { - "node": ">=20.19" + "node": "^22.18.0 || >=24.0.0" }, - "dependencies": {}, "devDependencies": { - "get-port-please": "^3.2.0", + "@msw/playwright": "0.6.7", + "msw": "2.15.0", + "rimraf": "catalog:", "vite": "^8.0.14", - "vite-plugin-dts": "^4.5.4" + "vite-plugin-dts": "^4.5.4", + "vitest": "catalog:" } } diff --git a/e2e/e2e-utils/src/api-fixture.ts b/e2e/e2e-utils/src/api-fixture.ts new file mode 100644 index 0000000000..90ca1912a3 --- /dev/null +++ b/e2e/e2e-utils/src/api-fixture.ts @@ -0,0 +1,17 @@ +import { test as base } from '@playwright/test' +import { defineNetworkFixture } from '@msw/playwright' +import { apiHandlers } from './api-handlers' + +// Opt in only for suites that consume the canned API. Playwright routing +// disables HTTP caching; other suites keep their normal browser behavior. +export const apiTest = base.extend<{ mockApi: void }>({ + mockApi: [ + async ({ context }, use) => { + const network = defineNetworkFixture({ context, handlers: apiHandlers }) + await network.enable() + await use() + await network.disable() + }, + { auto: true }, + ], +}) diff --git a/e2e/e2e-utils/src/api-handlers.ts b/e2e/e2e-utils/src/api-handlers.ts new file mode 100644 index 0000000000..4e2c0498f4 --- /dev/null +++ b/e2e/e2e-utils/src/api-handlers.ts @@ -0,0 +1,32 @@ +import { HttpResponse, http } from 'msw' +import { posts } from './posts.ts' +import { users } from './users.ts' + +export const apiHandlers = [ + ...Object.entries({ posts, users }).flatMap(([resource, data]) => [ + http.get(`https://jsonplaceholder.typicode.com/${resource}`, () => + HttpResponse.json(data), + ), + http.get( + `https://jsonplaceholder.typicode.com/${resource}/:id`, + ({ params }) => { + const id = parseInt(String(params.id)) + if (Number.isNaN(id)) { + return HttpResponse.json( + { error: `invalid ${resource.slice(0, -1)} id` }, + { status: 404 }, + ) + } + const item = data.find((entry) => entry.id === id) + return item + ? HttpResponse.json(item) + : new HttpResponse(null, { + headers: { 'content-type': 'application/json' }, + }) + }, + ), + ]), + http.all('https://jsonplaceholder.typicode.com/*', () => + HttpResponse.error(), + ), +] diff --git a/e2e/e2e-utils/src/derivePort.ts b/e2e/e2e-utils/src/derivePort.ts deleted file mode 100644 index 3ecb86cb53..0000000000 --- a/e2e/e2e-utils/src/derivePort.ts +++ /dev/null @@ -1,27 +0,0 @@ -import fs from 'node:fs' -import { getRandomPort } from 'get-port-please' - -/** - * Check if a port has been allocated, if it hasn't generate a random port and save it. - * @param {string} input - port test allocation - * @returns {number} A random port. - */ -export async function derivePort(input: string): Promise { - const portFile = `port-${input}.txt` - - if (!fs.existsSync(portFile)) { - fs.writeFileSync(portFile, (await getRandomPort()).toString()) - } - - const portNumber = parseInt(await fs.promises.readFile(portFile, 'utf-8')) - console.info(`Mapped "${input}" to port ${portNumber}`) - return portNumber -} - -export async function getDummyServerPort(input: string): Promise { - return await derivePort(`${input}-external`) -} - -export async function getTestServerPort(input: string): Promise { - return await derivePort(input) -} diff --git a/e2e/e2e-utils/src/e2eSetupTeardown.ts b/e2e/e2e-utils/src/e2eSetupTeardown.ts deleted file mode 100644 index d1acf4740e..0000000000 --- a/e2e/e2e-utils/src/e2eSetupTeardown.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { localDummyServer } from './localDummyServer' -import { getDummyServerPort } from './derivePort' - -export async function e2eStartDummyServer(input: string) { - const port = await getDummyServerPort(input) - - return await localDummyServer(port) -} - -export async function e2eStopDummyServer(input: string) { - const port = await getDummyServerPort(input) - - await fetch(`http://localhost:${port}/stop`, { - method: 'POST', - }) -} diff --git a/e2e/e2e-utils/src/index.ts b/e2e/e2e-utils/src/index.ts index 17e58f82e5..960a01a9be 100644 --- a/e2e/e2e-utils/src/index.ts +++ b/e2e/e2e-utils/src/index.ts @@ -1,10 +1,9 @@ -export { derivePort, getDummyServerPort, getTestServerPort } from './derivePort' -export { localDummyServer } from './localDummyServer' -export { toRuntimePath } from './to-runtime-path' -export { resolveRuntimeSuffix } from './resolve-runtime-suffix' -export { e2eStartDummyServer, e2eStopDummyServer } from './e2eSetupTeardown' +export { apiTest } from './api-fixture' export { preOptimizeDevServer, waitForServer } from './devServerWarmup' +export { collectBrowserErrors, test } from './fixture' export { createHmrFileEditor, replaceAll } from './hmrFileEditor' export type { HmrFileEditorOptions } from './hmrFileEditor' export type { Post } from './posts' -export { collectBrowserErrors, test } from './fixture' +export { resolveRuntimeSuffix } from './resolve-runtime-suffix' +export { toRuntimePath } from './to-runtime-path' +export { appServerReady, appServerReadyPattern } from './webServer' diff --git a/e2e/e2e-utils/src/localDummyServer.ts b/e2e/e2e-utils/src/localDummyServer.ts deleted file mode 100644 index d452f54c59..0000000000 --- a/e2e/e2e-utils/src/localDummyServer.ts +++ /dev/null @@ -1,128 +0,0 @@ -import http from 'node:http' -import { posts } from './posts' -import { users } from './users' - -// some tests redirect to an external host -// however, in CI this is unstable due to network conditions -// so here we spawn a local server to simulate the external host - -export async function localDummyServer(port: number) { - const server = http.createServer((req, res) => { - // Set CORS headers - res.setHeader('Access-Control-Allow-Origin', '*') - res.setHeader('Access-Control-Request-Method', '*') - res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST') - res.setHeader('Access-Control-Allow-Headers', '*') - - if (req.method === 'OPTIONS') { - res.writeHead(200) - res.end() - return - } - }) - - server.on('request', (req, res) => { - const url = new URL(req.url!, 'http://localhost') - - if (res.req.method === 'GET' && url.pathname === '/') { - res.writeHead(200, { 'Content-Type': 'text/html' }) - res.end('Hello World') - } - }) - - server.on('request', (req, res) => { - const url = new URL(req.url!, `http://localhost`) - - if (res.req.method === 'POST' && url.pathname === '/stop') { - server.close() - console.info( - `stopped local dummy server running at http://localhost:${port}`, - ) - - res.writeHead(200) - res.end() - } - }) - - server.on('request', (req, res) => { - const url = new URL(req.url ?? '/', `http://localhost`) - - if (req.method === 'GET' && url.pathname.startsWith('/posts')) { - const parts = url.pathname.split('/') - - if (parts.length === 2) { - res.writeHead(200, { 'content-type': 'application/json' }) - res.end(JSON.stringify(posts)) - return - } - - if (parts[2]) { - const postId = parseInt(parts[2]) - - if (isNaN(postId)) { - res.writeHead(404) - res.end(JSON.stringify({ error: 'invalid post id' })) - return - } - - const post = posts.find((post) => post.id === postId) - - res.writeHead(200, { 'content-type': 'application/json' }) - res.end(JSON.stringify(post)) - return - } - - res.writeHead(404) - res.end(JSON.stringify({ error: 'invalid posts path' })) - return - } - }) - - server.on('request', (req, res) => { - const url = new URL(req.url ?? '/', `http://localhost`) - - if (req.method === 'GET' && url.pathname.startsWith('/users')) { - const parts = url.pathname.split('/') - - if (parts.length === 2) { - res.writeHead(200, { 'content-type': 'application/json' }) - res.end(JSON.stringify(users)) - return - } - - if (parts[2]) { - const userId = parseInt(parts[2]) - - if (isNaN(userId)) { - res.writeHead(404) - res.end(JSON.stringify({ error: 'invalid user id' })) - return - } - - const user = users.find((user) => user.id === userId) - - res.writeHead(200, { 'content-type': 'application/json' }) - res.end(JSON.stringify(user)) - return - } - - res.writeHead(404) - res.end(JSON.stringify({ error: 'invalid users path' })) - return - } - }) - - const startServer = new Promise((resolve) => { - server.listen(port, 'localhost', () => { - console.info( - `started local dummy server running at http://localhost:${port}`, - ) - resolve() - }) - }) - - await startServer - - await new Promise((r) => setTimeout(r, 500)) - return server -} diff --git a/e2e/e2e-utils/src/webServer.ts b/e2e/e2e-utils/src/webServer.ts new file mode 100644 index 0000000000..77536e4c69 --- /dev/null +++ b/e2e/e2e-utils/src/webServer.ts @@ -0,0 +1,9 @@ +// Vite, Rsbuild, srvx, serve, and the custom E2E servers print their bound +// address only after listening. Playwright exports named captures to workers. +export const appServerReadyPattern = + /(?:Local:|Listening on|Accepting connections at|E2E app:)[^\n]*?https?:\/\/(?:localhost|127\.0\.0\.1|\[::\]):(?\d+)/ + +export const appServerReady = { + stdout: appServerReadyPattern, + stderr: appServerReadyPattern, +} diff --git a/e2e/e2e-utils/tests/mock-api.test.ts b/e2e/e2e-utils/tests/mock-api.test.ts new file mode 100644 index 0000000000..ba25c1254d --- /dev/null +++ b/e2e/e2e-utils/tests/mock-api.test.ts @@ -0,0 +1,53 @@ +import { execFile } from 'node:child_process' +import { promisify } from 'node:util' +import { fileURLToPath } from 'node:url' +import { expect, test } from 'vitest' + +const execFileAsync = promisify(execFile) +const preload = fileURLToPath(new URL('../mock-api.mjs', import.meta.url)) + +test('independent Node processes mock the API with networking disabled', async () => { + const script = ` + const { Socket } = await import('node:net') + Socket.prototype.connect = () => { throw new Error('Network disabled') } + const posts = await fetch('https://jsonplaceholder.typicode.com/posts').then(r => r.json()) + const user = await fetch('https://jsonplaceholder.typicode.com/users/1').then(r => r.json()) + const invalid = await fetch('https://jsonplaceholder.typicode.com/posts/invalid') + const missing = await fetch('https://jsonplaceholder.typicode.com/posts/999') + console.log(JSON.stringify({ post: posts[0].id, user: user.id, invalid: invalid.status, missing: await missing.text() })) + ` + const results = await Promise.all( + [0, 1].map(() => + execFileAsync(process.execPath, ['--import', preload, '--eval', script]), + ), + ) + for (const result of results) { + expect(JSON.parse(result.stdout)).toEqual({ + post: 1, + user: 1, + invalid: 404, + missing: '', + }) + } +}) + +test('unhandled API requests fail without reaching the network', async () => { + const script = ` + const { Socket } = await import('node:net') + let connections = 0 + Socket.prototype.connect = () => { connections++; throw new Error('Network disabled') } + try { + await fetch('https://jsonplaceholder.typicode.com/unhandled') + process.exitCode = 1 + } catch { + console.log(JSON.stringify({ connections })) + } + ` + const result = await execFileAsync(process.execPath, [ + '--import', + preload, + '--eval', + script, + ]) + expect(JSON.parse(result.stdout)).toEqual({ connections: 0 }) +}) diff --git a/e2e/e2e-utils/tests/webServer.test.ts b/e2e/e2e-utils/tests/webServer.test.ts new file mode 100644 index 0000000000..fd3a8b239c --- /dev/null +++ b/e2e/e2e-utils/tests/webServer.test.ts @@ -0,0 +1,23 @@ +import { stripVTControlCharacters } from 'node:util' +import { expect, test } from 'vitest' +import { appServerReadyPattern } from '../src/webServer' + +test.each([ + '➜ Local: http://localhost:49152/', + '\u001b[32m➜\u001b[39m \u001b[1mLocal\u001b[22m: \u001b[36mhttp://localhost:\u001b[1m49152\u001b[22m/\u001b[39m', + 'Listening on http://[::]:49152', + 'E2E app: http://localhost:49152', + 'Accepting connections at http://localhost:49152', + 'Local: https://localhost:49152/', +])('captures a bound application port from %s', (line) => { + expect( + appServerReadyPattern.exec(stripVTControlCharacters(line))?.groups + ?.E2E_APP_PORT, + ).toBe('49152') +}) + +test('does not confuse an arbitrary URL with app readiness', () => { + expect(appServerReadyPattern.test('fetching http://localhost:49152')).toBe( + false, + ) +}) diff --git a/e2e/e2e-utils/tsconfig.json b/e2e/e2e-utils/tsconfig.json index 9b21ee123b..5561f5d28f 100644 --- a/e2e/e2e-utils/tsconfig.json +++ b/e2e/e2e-utils/tsconfig.json @@ -1,4 +1,7 @@ { "extends": "../../tsconfig.json", - "include": ["src", "vite.config.ts", "tests"] + "include": ["src", "vite.config.ts", "tests"], + "compilerOptions": { + "rewriteRelativeImportExtensions": true + } } diff --git a/e2e/eslint-plugin-start/package.json b/e2e/eslint-plugin-start/package.json index 87bc81bfe9..e3591d7d1b 100644 --- a/e2e/eslint-plugin-start/package.json +++ b/e2e/eslint-plugin-start/package.json @@ -61,6 +61,6 @@ "eslint": "^9.22.0", "react": "^19.0.0", "typescript": "^5.7.2", - "vitest": "^4.1.4" + "vitest": "catalog:" } } diff --git a/e2e/react-router/basepath-file-based/package.json b/e2e/react-router/basepath-file-based/package.json index a155cc2173..3dfbb58180 100644 --- a/e2e/react-router/basepath-file-based/package.json +++ b/e2e/react-router/basepath-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", diff --git a/e2e/react-router/basepath-file-based/playwright.config.ts b/e2e/react-router/basepath-file-based/playwright.config.ts index 6069bbe59f..4eead86444 100644 --- a/e2e/react-router/basepath-file-based/playwright.config.ts +++ b/e2e/react-router/basepath-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/basepath-file-based/src/routeTree.gen.ts b/e2e/react-router/basepath-file-based/src/routeTree.gen.ts index 2989a394d3..3badc3f843 100644 --- a/e2e/react-router/basepath-file-based/src/routeTree.gen.ts +++ b/e2e/react-router/basepath-file-based/src/routeTree.gen.ts @@ -9,25 +9,15 @@ // 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 ScrollErrorRouteImport } from './routes/scroll-error' -import { Route as RedirectReloadRouteImport } from './routes/redirectReload' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as RedirectReloadRouteImport } from './routes/redirectReload' +import { Route as ScrollErrorRouteImport } from './routes/scroll-error' -const ScrollErrorRoute = ScrollErrorRouteImport.update({ - id: '/scroll-error', - path: '/scroll-error', - getParentRoute: () => rootRouteImport, -} as any) -const RedirectReloadRoute = RedirectReloadRouteImport.update({ - id: '/redirectReload', - path: '/redirectReload', - getParentRoute: () => rootRouteImport, -} as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AboutRoute = AboutRouteImport.update({ @@ -35,9 +25,19 @@ const AboutRoute = AboutRouteImport.update({ path: '/about', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', + getParentRoute: () => rootRouteImport, +} as any) +const RedirectReloadRoute = RedirectReloadRouteImport.update({ + id: '/redirectReload', + path: '/redirectReload', + getParentRoute: () => rootRouteImport, +} as any) +const ScrollErrorRoute = ScrollErrorRouteImport.update({ + id: '/scroll-error', + path: '/scroll-error', getParentRoute: () => rootRouteImport, } as any) @@ -87,25 +87,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/scroll-error': { - id: '/scroll-error' - path: '/scroll-error' - fullPath: '/scroll-error' - preLoaderRoute: typeof ScrollErrorRouteImport - parentRoute: typeof rootRouteImport - } - '/redirectReload': { - id: '/redirectReload' - path: '/redirectReload' - fullPath: '/redirectReload' - preLoaderRoute: typeof RedirectReloadRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/about': { @@ -115,11 +101,25 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport + } + '/redirectReload': { + id: '/redirectReload' + path: '/redirectReload' + fullPath: '/redirectReload' + preLoaderRoute: typeof RedirectReloadRouteImport + parentRoute: typeof rootRouteImport + } + '/scroll-error': { + id: '/scroll-error' + path: '/scroll-error' + fullPath: '/scroll-error' + preLoaderRoute: typeof ScrollErrorRouteImport parentRoute: typeof rootRouteImport } } diff --git a/e2e/react-router/basepath-file-based/tests/scroll-restoration-session-storage-error.test.ts b/e2e/react-router/basepath-file-based/tests/scroll-restoration-session-storage-error.test.ts index 06b90f6528..d6a50de840 100644 --- a/e2e/react-router/basepath-file-based/tests/scroll-restoration-session-storage-error.test.ts +++ b/e2e/react-router/basepath-file-based/tests/scroll-restoration-session-storage-error.test.ts @@ -1,5 +1,41 @@ -/* eslint-disable */ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' +import type { Page } from '@playwright/test' + +async function reloadAfterStorageFailure(page: Page) { + const errors: Array = [] + page.on('pageerror', (error) => errors.push(error.message)) + const snapshot = await page.evaluate(async () => { + let failures = 0 + const setItem = Storage.prototype.setItem + Storage.prototype.setItem = function (...args) { + try { + return setItem.apply(this, args) + } catch (error) { + failures++ + throw error + } + } + const scrolled = new Promise((resolve) => + addEventListener('scroll', () => resolve(), { once: true }), + ) + scrollTo(0, 200) + await scrolled + // Handler integration; genuine reload handoff is covered by the Start suite. + dispatchEvent(new PageTransitionEvent('pagehide', { persisted: false })) + return { mode: history.scrollRestoration, failures } + }) + expect(snapshot.failures).toBeGreaterThan(0) + // Storage failure must still allow native fallback; failure to restore is not a requirement. + expect(snapshot.mode).toBe('auto') + await page.reload() + await page.waitForLoadState('networkidle') + await expect( + page.getByRole('heading', { name: 'Scroll Error Test' }), + ).toBeVisible() + expect(await page.evaluate(() => history.scrollRestoration)).toBe('manual') + expect(errors).toEqual([]) +} test.describe('Scroll Restoration with Session Storage Error', () => { test('should not crash when sessionStorage.setItem throws an error', async ({ @@ -9,22 +45,12 @@ test.describe('Scroll Restoration with Session Storage Error', () => { await page.waitForLoadState('networkidle') await page.evaluate(() => { - sessionStorage.setItem = () => { + Storage.prototype.setItem = () => { throw new Error('Test Error') } }) - await page.evaluate(() => window.scrollTo(0, 200)) - await page.waitForTimeout(150) - - await page.reload() - await page.waitForLoadState('networkidle') - - const heading = page.locator('h1:has-text("Scroll Error Test")') - await expect(heading).toBeVisible() - - const scrollPosition = await page.evaluate(() => window.scrollY) - expect(scrollPosition).not.toBe(200) + await reloadAfterStorageFailure(page) }) test('should not crash when sessionStorage quota is exceeded', async ({ @@ -47,16 +73,6 @@ test.describe('Scroll Restoration with Session Storage Error', () => { } }) - await page.evaluate(() => window.scrollTo(0, 200)) - await page.waitForTimeout(150) - - await page.reload() - await page.waitForLoadState('networkidle') - - const heading = page.locator('h1:has-text("Scroll Error Test")') - await expect(heading).toBeVisible() - - const scrollPosition = await page.evaluate(() => window.scrollY) - expect(scrollPosition).not.toBe(200) + await reloadAfterStorageFailure(page) }) }) diff --git a/e2e/react-router/basepath-file-based/tests/setup/global.setup.ts b/e2e/react-router/basepath-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/basepath-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-router/basepath-file-based/tests/setup/global.teardown.ts b/e2e/react-router/basepath-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/basepath-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-router/basic-esbuild-file-based/package.json b/e2e/react-router/basic-esbuild-file-based/package.json index 2ff977a4f4..59210c24d7 100644 --- a/e2e/react-router/basic-esbuild-file-based/package.json +++ b/e2e/react-router/basic-esbuild-file-based/package.json @@ -7,7 +7,7 @@ "build": "esbuild src/main.tsx --bundle --outfile=dist/main.js && tsc --noEmit", "serve": "esbuild src/main.tsx --bundle --outfile=dist/main.js --servedir=.", "start": "dev", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -15,7 +15,7 @@ "@tanstack/router-plugin": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "zod": "^4.4.3" }, "devDependencies": { diff --git a/e2e/react-router/basic-esbuild-file-based/playwright.config.ts b/e2e/react-router/basic-esbuild-file-based/playwright.config.ts index ca0fb7a1da..a38252921f 100644 --- a/e2e/react-router/basic-esbuild-file-based/playwright.config.ts +++ b/e2e/react-router/basic-esbuild-file-based/playwright.config.ts @@ -1,12 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' + +const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +13,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `pnpm run build && pnpm run serve --serve=${PORT} --define:process.env.NODE_ENV=\\"test\\" --define:process.env.EXTERNAL_PORT="${EXTERNAL_PORT}"`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm run build && pnpm run serve --serve=${PORT} --define:process.env.NODE_ENV=\\"test\\"`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/basic-esbuild-file-based/src/esbuild.config.js b/e2e/react-router/basic-esbuild-file-based/src/esbuild.config.js index 5f0f4fce03..954ddc026f 100644 --- a/e2e/react-router/basic-esbuild-file-based/src/esbuild.config.js +++ b/e2e/react-router/basic-esbuild-file-based/src/esbuild.config.js @@ -2,9 +2,5 @@ import { tanstackRouter } from '@tanstack/router-plugin/esbuild' export default { // ... - plugins: [ - tanstackRouter({ - autoCodeSplitting: true, - }), - ], + plugins: [tanstackRouter()], } diff --git a/e2e/react-router/basic-esbuild-file-based/src/posts.tsx b/e2e/react-router/basic-esbuild-file-based/src/posts.tsx index 8f74b8c9aa..97c96d77eb 100644 --- a/e2e/react-router/basic-esbuild-file-based/src/posts.tsx +++ b/e2e/react-router/basic-esbuild-file-based/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (process.env.NODE_ENV === 'test') { - queryURL = `http://localhost:${process.env.EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-router/basic-esbuild-file-based/tests/app.spec.ts b/e2e/react-router/basic-esbuild-file-based/tests/app.spec.ts index 7b322a8b1d..c52191a7d4 100644 --- a/e2e/react-router/basic-esbuild-file-based/tests/app.spec.ts +++ b/e2e/react-router/basic-esbuild-file-based/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/basic-esbuild-file-based/tests/setup/global.setup.ts b/e2e/react-router/basic-esbuild-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/basic-esbuild-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-router/basic-esbuild-file-based/tests/setup/global.teardown.ts b/e2e/react-router/basic-esbuild-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/basic-esbuild-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-router/basic-file-based-code-splitting/package.json b/e2e/react-router/basic-file-based-code-splitting/package.json index f3654137be..82ebb90e93 100644 --- a/e2e/react-router/basic-file-based-code-splitting/package.json +++ b/e2e/react-router/basic-file-based-code-splitting/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -17,6 +17,7 @@ "@tanstack/router-plugin": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, diff --git a/e2e/react-router/basic-file-based-code-splitting/playwright.config.ts b/e2e/react-router/basic-file-based-code-splitting/playwright.config.ts index 22c9bdcd7e..4eead86444 100644 --- a/e2e/react-router/basic-file-based-code-splitting/playwright.config.ts +++ b/e2e/react-router/basic-file-based-code-splitting/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/basic-file-based-code-splitting/src/posts.tsx b/e2e/react-router/basic-file-based-code-splitting/src/posts.tsx index ae7142c5b6..97c96d77eb 100644 --- a/e2e/react-router/basic-file-based-code-splitting/src/posts.tsx +++ b/e2e/react-router/basic-file-based-code-splitting/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-router/basic-file-based-code-splitting/src/routeTree.gen.ts b/e2e/react-router/basic-file-based-code-splitting/src/routeTree.gen.ts index 618ad52e34..c7a15cd84e 100644 --- a/e2e/react-router/basic-file-based-code-splitting/src/routeTree.gen.ts +++ b/e2e/react-router/basic-file-based-code-splitting/src/routeTree.gen.ts @@ -9,31 +9,25 @@ // 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 WithoutLoaderRouteImport } from './routes/without-loader' -import { Route as ViewportTestRouteImport } from './routes/viewport-test' -import { Route as SharedSingletonRouteImport } from './routes/shared-singleton' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as IndexRouteImport } from './routes/index' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as SharedSingletonRouteImport } from './routes/shared-singleton' +import { Route as ViewportTestRouteImport } from './routes/viewport-test' +import { Route as WithoutLoaderRouteImport } from './routes/without-loader' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' -const WithoutLoaderRoute = WithoutLoaderRouteImport.update({ - id: '/without-loader', - path: '/without-loader', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const ViewportTestRoute = ViewportTestRouteImport.update({ - id: '/viewport-test', - path: '/viewport-test', - getParentRoute: () => rootRouteImport, -} as any) -const SharedSingletonRoute = SharedSingletonRouteImport.update({ - id: '/shared-singleton', - path: '/shared-singleton', +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', getParentRoute: () => rootRouteImport, } as any) const PostsRoute = PostsRouteImport.update({ @@ -41,15 +35,25 @@ const PostsRoute = PostsRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', +const SharedSingletonRoute = SharedSingletonRouteImport.update({ + id: '/shared-singleton', + path: '/shared-singleton', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ViewportTestRoute = ViewportTestRouteImport.update({ + id: '/viewport-test', + path: '/viewport-test', getParentRoute: () => rootRouteImport, } as any) +const WithoutLoaderRoute = WithoutLoaderRouteImport.update({ + id: '/without-loader', + path: '/without-loader', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, +} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -60,20 +64,16 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRoute, } as any) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any) const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ id: '/layout-b', path: '/layout-b', getParentRoute: () => LayoutLayout2Route, } as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, -} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -158,32 +158,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/without-loader': { - id: '/without-loader' - path: '/without-loader' - fullPath: '/without-loader' - preLoaderRoute: typeof WithoutLoaderRouteImport - parentRoute: typeof rootRouteImport - } - '/viewport-test': { - id: '/viewport-test' - path: '/viewport-test' - fullPath: '/viewport-test' - preLoaderRoute: typeof ViewportTestRouteImport - parentRoute: typeof rootRouteImport - } - '/shared-singleton': { - id: '/shared-singleton' - path: '/shared-singleton' - fullPath: '/shared-singleton' - preLoaderRoute: typeof SharedSingletonRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -193,13 +172,41 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } + '/shared-singleton': { + id: '/shared-singleton' + path: '/shared-singleton' + fullPath: '/shared-singleton' + preLoaderRoute: typeof SharedSingletonRouteImport + parentRoute: typeof rootRouteImport + } + '/viewport-test': { + id: '/viewport-test' + path: '/viewport-test' + fullPath: '/viewport-test' + preLoaderRoute: typeof ViewportTestRouteImport + parentRoute: typeof rootRouteImport + } + '/without-loader': { + id: '/without-loader' + path: '/without-loader' + fullPath: '/without-loader' + preLoaderRoute: typeof WithoutLoaderRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute + } '/posts/': { id: '/posts/' path: '/' @@ -214,12 +221,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route } '/_layout/_layout-2/layout-b': { id: '/_layout/_layout-2/layout-b' @@ -228,13 +235,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport parentRoute: typeof LayoutLayout2Route } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route - } } } diff --git a/e2e/react-router/basic-file-based-code-splitting/tests/app.spec.ts b/e2e/react-router/basic-file-based-code-splitting/tests/app.spec.ts index 3e5a69ccaa..fbf093cd51 100644 --- a/e2e/react-router/basic-file-based-code-splitting/tests/app.spec.ts +++ b/e2e/react-router/basic-file-based-code-splitting/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/basic-file-based-code-splitting/tests/preload.spec.ts b/e2e/react-router/basic-file-based-code-splitting/tests/preload.spec.ts index 0bc3265760..fd17fcc47b 100644 --- a/e2e/react-router/basic-file-based-code-splitting/tests/preload.spec.ts +++ b/e2e/react-router/basic-file-based-code-splitting/tests/preload.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/basic-file-based-code-splitting/tests/setup/global.setup.ts b/e2e/react-router/basic-file-based-code-splitting/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/basic-file-based-code-splitting/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-router/basic-file-based-code-splitting/tests/setup/global.teardown.ts b/e2e/react-router/basic-file-based-code-splitting/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/basic-file-based-code-splitting/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-router/basic-file-based-code-splitting/tests/shared-bindings.spec.ts b/e2e/react-router/basic-file-based-code-splitting/tests/shared-bindings.spec.ts index 512943c10d..2ad4ec3e78 100644 --- a/e2e/react-router/basic-file-based-code-splitting/tests/shared-bindings.spec.ts +++ b/e2e/react-router/basic-file-based-code-splitting/tests/shared-bindings.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/basic-file-based/package.json b/e2e/react-router/basic-file-based/package.json index be3d8add30..0f3d243432 100644 --- a/e2e/react-router/basic-file-based/package.json +++ b/e2e/react-router/basic-file-based/package.json @@ -9,7 +9,7 @@ "preview": "vite preview", "start": "vite", "test:e2e": "pnpm run test:e2e:default", - "test:e2e:default": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e:default": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -18,7 +18,7 @@ "@tanstack/router-plugin": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, diff --git a/e2e/react-router/basic-file-based/playwright.config.ts b/e2e/react-router/basic-file-based/playwright.config.ts index 6e4e1d7703..ea3ef9ffec 100644 --- a/e2e/react-router/basic-file-based/playwright.config.ts +++ b/e2e/react-router/basic-file-based/playwright.config.ts @@ -1,14 +1,9 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` -const command = `pnpm build && pnpm preview --port ${PORT}` +const command = `pnpm build && pnpm preview --host 0.0.0.0 --port ${PORT}` console.info('Running with mode: ', process.env.MODE || 'default') @@ -21,9 +16,6 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, @@ -31,15 +23,12 @@ export default defineConfig({ webServer: { command, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', env: { MODE: process.env.MODE || '', VITE_MODE: process.env.MODE || '', - VITE_NODE_ENV: 'test', - VITE_EXTERNAL_PORT: String(EXTERNAL_PORT), - VITE_SERVER_PORT: String(PORT), PORT: String(PORT), }, }, diff --git a/e2e/react-router/basic-file-based/public/external.html b/e2e/react-router/basic-file-based/public/external.html new file mode 100644 index 0000000000..3b4062b778 --- /dev/null +++ b/e2e/react-router/basic-file-based/public/external.html @@ -0,0 +1,9 @@ + + + + External destination + + + Hello World + + diff --git a/e2e/react-router/basic-file-based/src/main.tsx b/e2e/react-router/basic-file-based/src/main.tsx index 12e202dae4..d6a5aef382 100644 --- a/e2e/react-router/basic-file-based/src/main.tsx +++ b/e2e/react-router/basic-file-based/src/main.tsx @@ -24,6 +24,14 @@ const router = createRouter({ defaultStaleTime: 5000, scrollRestoration: true, routeMasks: [mask], + rewrite: { + output: ({ url }) => { + if (url.pathname === '/document-navigation-target') { + return new URL(`http://127.0.0.1:${window.location.port}/external.html`) + } + return url + }, + }, }) // Register things for typesafety diff --git a/e2e/react-router/basic-file-based/src/posts.tsx b/e2e/react-router/basic-file-based/src/posts.tsx index ae7142c5b6..97c96d77eb 100644 --- a/e2e/react-router/basic-file-based/src/posts.tsx +++ b/e2e/react-router/basic-file-based/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-router/basic-file-based/src/routeTree.gen.ts b/e2e/react-router/basic-file-based/src/routeTree.gen.ts index 7ee0051549..83b504992f 100644 --- a/e2e/react-router/basic-file-based/src/routeTree.gen.ts +++ b/e2e/react-router/basic-file-based/src/routeTree.gen.ts @@ -9,170 +9,137 @@ // 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 RemountDepsRouteImport } from './routes/remountDeps' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as NotRemountDepsRouteImport } from './routes/notRemountDeps' -import { Route as MasksRouteImport } from './routes/masks' -import { Route as LazyErrorRouteImport } from './routes/lazy-error' -import { Route as HoverPreloadHashRouteImport } from './routes/hover-preload-hash' -import { Route as EditingBRouteImport } from './routes/editing-b' -import { Route as EditingARouteImport } from './routes/editing-a' -import { Route as ComponentTypesTestRouteImport } from './routes/component-types-test' -import { Route as AnchorRouteImport } from './routes/anchor' -import { Route as LayoutRouteImport } from './routes/_layout' -import { Route as Char45824Char54620Char48124Char44397RouteRouteImport } from './routes/대한민국/route' -import { Route as SearchParamsRouteRouteImport } from './routes/search-params/route' -import { Route as PathlessLayoutRouteRouteImport } from './routes/pathless-layout/route' -import { Route as NonNestedRouteRouteImport } from './routes/non-nested/route' -import { Route as FullpathTestRouteRouteImport } from './routes/fullpath-test/route' import { Route as IndexRouteImport } from './routes/index' -import { Route as SearchParamsIndexRouteImport } from './routes/search-params/index' -import { Route as RelativeIndexRouteImport } from './routes/relative/index' -import { Route as RedirectIndexRouteImport } from './routes/redirect/index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as ParamsPsIndexRouteImport } from './routes/params-ps/index' -import { Route as StructuralSharingEnabledRouteImport } from './routes/structural-sharing.$enabled' -import { Route as SearchParamsDefaultRouteImport } from './routes/search-params/default' -import { Route as RedirectTargetRouteImport } from './routes/redirect/$target' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as groupLazyinsideRouteImport } from './routes/(group)/lazyinside' -import { Route as groupInsideRouteImport } from './routes/(group)/inside' -import { Route as groupLayoutRouteImport } from './routes/(group)/_layout' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as AnchorRouteImport } from './routes/anchor' +import { Route as ComponentTypesTestRouteImport } from './routes/component-types-test' +import { Route as DocumentNavigationRouteImport } from './routes/document-navigation' +import { Route as DocumentNavigationTargetRouteImport } from './routes/document-navigation-target' +import { Route as EditingARouteImport } from './routes/editing-a' +import { Route as EditingBRouteImport } from './routes/editing-b' +import { Route as FullpathTestRouteRouteImport } from './routes/fullpath-test/route' +import { Route as HistoryBlockingRouteImport } from './routes/history-blocking' +import { Route as HoverPreloadHashRouteImport } from './routes/hover-preload-hash' +import { Route as LazyErrorRouteImport } from './routes/lazy-error' +import { Route as MasksRouteImport } from './routes/masks' +import { Route as NonNestedRouteRouteImport } from './routes/non-nested/route' +import { Route as NotRemountDepsRouteImport } from './routes/notRemountDeps' +import { Route as PathlessLayoutRouteRouteImport } from './routes/pathless-layout/route' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RemountDepsRouteImport } from './routes/remountDeps' +import { Route as SearchParamsRouteRouteImport } from './routes/search-params/route' +import { Route as Char45824Char54620Char48124Char44397RouteRouteImport } from './routes/대한민국/route' import { Route as anotherGroupOnlyrouteinsideRouteImport } from './routes/(another-group)/onlyrouteinside' -import { Route as RelativeUseNavigateRouteRouteImport } from './routes/relative/useNavigate/route' -import { Route as RelativeLinkRouteRouteImport } from './routes/relative/link/route' -import { Route as PathlessLayoutLayoutRouteRouteImport } from './routes/pathless-layout/_layout/route' -import { Route as ParamsPsStrictFalseRouteRouteImport } from './routes/params-ps/strict-false/route' -import { Route as ParamsPsNonNestedRouteRouteImport } from './routes/params-ps/non-nested/route' -import { Route as NonNestedSuffixRouteRouteImport } from './routes/non-nested/suffix/route' -import { Route as NonNestedPrefixRouteRouteImport } from './routes/non-nested/prefix/route' -import { Route as NonNestedPathRouteRouteImport } from './routes/non-nested/path/route' -import { Route as NonNestedNamedRouteRouteImport } from './routes/non-nested/named/route' -import { Route as NonNestedDeepRouteRouteImport } from './routes/non-nested/deep/route' +import { Route as groupLayoutRouteImport } from './routes/(group)/_layout' +import { Route as groupInsideRouteImport } from './routes/(group)/inside' +import { Route as groupLazyinsideRouteImport } from './routes/(group)/lazyinside' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' import { Route as FullpathTestLayoutRouteRouteImport } from './routes/fullpath-test/_layout/route' -import { Route as RedirectTargetIndexRouteImport } from './routes/redirect/$target/index' -import { Route as PathlessLayoutLayoutIndexRouteImport } from './routes/pathless-layout/_layout/index' -import { Route as ParamsPsWildcardIndexRouteImport } from './routes/params-ps/wildcard/index' -import { Route as ParamsPsNamedIndexRouteImport } from './routes/params-ps/named/index' -import { Route as FullpathTestLayoutIndexRouteImport } from './routes/fullpath-test/_layout/index' -import { Route as Char45824Char54620Char48124Char44397Char55357Char56960IdRouteImport } from './routes/대한민국/🚀.$id' -import { Route as Char45824Char54620Char48124Char44397WildcardSplatRouteImport } from './routes/대한민국/wildcard.$' -import { Route as RelativeUseNavigateRelativeUseNavigateBRouteImport } from './routes/relative/useNavigate/relative-useNavigate-b' -import { Route as RelativeUseNavigateRelativeUseNavigateARouteImport } from './routes/relative/useNavigate/relative-useNavigate-a' -import { Route as RelativeLinkRelativeLinkBRouteImport } from './routes/relative/link/relative-link-b' -import { Route as RelativeLinkRelativeLinkARouteImport } from './routes/relative/link/relative-link-a' -import { Route as RedirectPreloadThirdRouteImport } from './routes/redirect/preload/third' -import { Route as RedirectPreloadSecondRouteImport } from './routes/redirect/preload/second' -import { Route as RedirectPreloadFirstRouteImport } from './routes/redirect/preload/first' -import { Route as RedirectTargetViaRouteApiRedirectLoaderRouteImport } from './routes/redirect/$target/via-routeApi-redirect-loader' -import { Route as RedirectTargetViaRouteApiRedirectBeforeLoadRouteImport } from './routes/redirect/$target/via-routeApi-redirect-beforeLoad' -import { Route as RedirectTargetViaRouteRedirectLoaderRouteImport } from './routes/redirect/$target/via-route-redirect-loader' -import { Route as RedirectTargetViaRouteRedirectBeforeLoadRouteImport } from './routes/redirect/$target/via-route-redirect-beforeLoad' -import { Route as RedirectTargetViaLoaderRouteImport } from './routes/redirect/$target/via-loader' -import { Route as RedirectTargetViaBeforeLoadRouteImport } from './routes/redirect/$target/via-beforeLoad' -import { Route as RedirectTargetDestinationRouteImport } from './routes/redirect/$target/destination' -import { Route as PostsPostIdEditRouteImport } from './routes/posts_.$postId.edit' -import { Route as PathlessLayoutLayoutChildRouteImport } from './routes/pathless-layout/_layout/child' -import { Route as ParamsSingleValueRouteImport } from './routes/params.single.$value' -import { Route as ParamsPsWildcardChar123Char125suffixAtChar45824RouteImport } from './routes/params-ps/wildcard/{$}suffix@대' -import { Route as ParamsPsWildcardChar123Char125suffixRouteImport } from './routes/params-ps/wildcard/{$}suffix' -import { Route as ParamsPsWildcardPrefixChar123Char125RouteImport } from './routes/params-ps/wildcard/prefix{$}' -import { Route as ParamsPsWildcardPrefixAtChar45824Char123Char125RouteImport } from './routes/params-ps/wildcard/prefix@대{$}' -import { Route as ParamsPsWildcardSplatRouteImport } from './routes/params-ps/wildcard/$' -import { Route as ParamsPsNamedChar123fooChar125suffixRouteImport } from './routes/params-ps/named/{$foo}suffix' -import { Route as ParamsPsNamedPrefixChar123fooChar125RouteImport } from './routes/params-ps/named/prefix{$foo}' -import { Route as MasksPublicUsernameRouteImport } from './routes/masks.public.$username' -import { Route as MasksAdminUserIdRouteImport } from './routes/masks.admin.$userId' -import { Route as FullpathTestLayoutIdRouteImport } from './routes/fullpath-test/_layout/$id' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' -import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -import { Route as groupSubfolderInsideRouteImport } from './routes/(group)/subfolder/inside' +import { Route as NonNestedDeepRouteRouteImport } from './routes/non-nested/deep/route' +import { Route as NonNestedNamedRouteRouteImport } from './routes/non-nested/named/route' +import { Route as NonNestedPathRouteRouteImport } from './routes/non-nested/path/route' +import { Route as NonNestedPrefixRouteRouteImport } from './routes/non-nested/prefix/route' +import { Route as NonNestedSuffixRouteRouteImport } from './routes/non-nested/suffix/route' +import { Route as ParamsPsIndexRouteImport } from './routes/params-ps/index' +import { Route as ParamsPsNonNestedRouteRouteImport } from './routes/params-ps/non-nested/route' +import { Route as ParamsPsStrictFalseRouteRouteImport } from './routes/params-ps/strict-false/route' +import { Route as PathlessLayoutLayoutRouteRouteImport } from './routes/pathless-layout/_layout/route' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as RedirectIndexRouteImport } from './routes/redirect/index' +import { Route as RedirectTargetRouteImport } from './routes/redirect/$target' +import { Route as RelativeIndexRouteImport } from './routes/relative/index' +import { Route as RelativeLinkRouteRouteImport } from './routes/relative/link/route' +import { Route as RelativeUseNavigateRouteRouteImport } from './routes/relative/useNavigate/route' +import { Route as SearchParamsIndexRouteImport } from './routes/search-params/index' +import { Route as SearchParamsDefaultRouteImport } from './routes/search-params/default' +import { Route as StructuralSharingEnabledRouteImport } from './routes/structural-sharing.$enabled' import { Route as groupLayoutInsidelayoutRouteImport } from './routes/(group)/_layout.insidelayout' -import { Route as ParamsPsStrictFalseVersionRouteRouteImport } from './routes/params-ps/strict-false/$version.route' -import { Route as ParamsPsNonNestedFooRouteRouteImport } from './routes/params-ps/non-nested/$foo_/route' -import { Route as ParamsPsNamedFooRouteRouteImport } from './routes/params-ps/named/$foo/route' -import { Route as NonNestedSuffixChar123bazChar125suffixRouteRouteImport } from './routes/non-nested/suffix/{$baz}suffix.route' -import { Route as NonNestedPrefixPrefixChar123bazChar125RouteRouteImport } from './routes/non-nested/prefix/prefix{$baz}.route' -import { Route as NonNestedPathBazRouteRouteImport } from './routes/non-nested/path/baz.route' -import { Route as NonNestedNamedBazRouteRouteImport } from './routes/non-nested/named/$baz.route' +import { Route as groupSubfolderInsideRouteImport } from './routes/(group)/subfolder/inside' +import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as FullpathTestLayoutIndexRouteImport } from './routes/fullpath-test/_layout/index' +import { Route as FullpathTestLayoutIdRouteImport } from './routes/fullpath-test/_layout/$id' +import { Route as MasksAdminUserIdRouteImport } from './routes/masks.admin.$userId' +import { Route as MasksPublicUsernameRouteImport } from './routes/masks.public.$username' import { Route as NonNestedDeepBazRouteRouteImport } from './routes/non-nested/deep/$baz.route' -import { Route as RelativeUseNavigateWithSearchIndexRouteImport } from './routes/relative/useNavigate/with-search/index' -import { Route as RelativeUseNavigatePathIndexRouteImport } from './routes/relative/useNavigate/path/index' -import { Route as RelativeUseNavigateNestedIndexRouteImport } from './routes/relative/useNavigate/nested/index' -import { Route as RelativeLinkWithSearchIndexRouteImport } from './routes/relative/link/with-search/index' -import { Route as RelativeLinkPathIndexRouteImport } from './routes/relative/link/path/index' -import { Route as RelativeLinkNestedIndexRouteImport } from './routes/relative/link/nested/index' -import { Route as NonNestedSuffixChar123bazChar125suffixIndexRouteImport } from './routes/non-nested/suffix/{$baz}suffix.index' -import { Route as NonNestedPrefixPrefixChar123bazChar125IndexRouteImport } from './routes/non-nested/prefix/prefix{$baz}.index' -import { Route as NonNestedPathBazIndexRouteImport } from './routes/non-nested/path/baz.index' -import { Route as NonNestedNamedBazIndexRouteImport } from './routes/non-nested/named/$baz.index' +import { Route as NonNestedNamedBazRouteRouteImport } from './routes/non-nested/named/$baz.route' +import { Route as NonNestedPathBazRouteRouteImport } from './routes/non-nested/path/baz.route' +import { Route as NonNestedPrefixPrefixChar123bazChar125RouteRouteImport } from './routes/non-nested/prefix/prefix{$baz}.route' +import { Route as NonNestedSuffixChar123bazChar125suffixRouteRouteImport } from './routes/non-nested/suffix/{$baz}suffix.route' +import { Route as ParamsPsNamedIndexRouteImport } from './routes/params-ps/named/index' +import { Route as ParamsPsNamedFooRouteRouteImport } from './routes/params-ps/named/$foo/route' +import { Route as ParamsPsNamedPrefixChar123fooChar125RouteImport } from './routes/params-ps/named/prefix{$foo}' +import { Route as ParamsPsNamedChar123fooChar125suffixRouteImport } from './routes/params-ps/named/{$foo}suffix' +import { Route as ParamsPsNonNestedFooRouteRouteImport } from './routes/params-ps/non-nested/$foo_/route' +import { Route as ParamsPsStrictFalseVersionRouteRouteImport } from './routes/params-ps/strict-false/$version.route' +import { Route as ParamsPsWildcardIndexRouteImport } from './routes/params-ps/wildcard/index' +import { Route as ParamsPsWildcardSplatRouteImport } from './routes/params-ps/wildcard/$' +import { Route as ParamsPsWildcardPrefixAtChar45824Char123Char125RouteImport } from './routes/params-ps/wildcard/prefix@대{$}' +import { Route as ParamsPsWildcardPrefixChar123Char125RouteImport } from './routes/params-ps/wildcard/prefix{$}' +import { Route as ParamsPsWildcardChar123Char125suffixRouteImport } from './routes/params-ps/wildcard/{$}suffix' +import { Route as ParamsPsWildcardChar123Char125suffixAtChar45824RouteImport } from './routes/params-ps/wildcard/{$}suffix@대' +import { Route as ParamsSingleValueRouteImport } from './routes/params.single.$value' +import { Route as PathlessLayoutLayoutIndexRouteImport } from './routes/pathless-layout/_layout/index' +import { Route as PathlessLayoutLayoutChildRouteImport } from './routes/pathless-layout/_layout/child' +import { Route as PostsPostIdEditRouteImport } from './routes/posts_.$postId.edit' +import { Route as RedirectTargetIndexRouteImport } from './routes/redirect/$target/index' +import { Route as RedirectTargetDestinationRouteImport } from './routes/redirect/$target/destination' +import { Route as RedirectTargetViaBeforeLoadRouteImport } from './routes/redirect/$target/via-beforeLoad' +import { Route as RedirectTargetViaLoaderRouteImport } from './routes/redirect/$target/via-loader' +import { Route as RedirectTargetViaRouteRedirectBeforeLoadRouteImport } from './routes/redirect/$target/via-route-redirect-beforeLoad' +import { Route as RedirectTargetViaRouteRedirectLoaderRouteImport } from './routes/redirect/$target/via-route-redirect-loader' +import { Route as RedirectTargetViaRouteApiRedirectBeforeLoadRouteImport } from './routes/redirect/$target/via-routeApi-redirect-beforeLoad' +import { Route as RedirectTargetViaRouteApiRedirectLoaderRouteImport } from './routes/redirect/$target/via-routeApi-redirect-loader' +import { Route as RedirectPreloadFirstRouteImport } from './routes/redirect/preload/first' +import { Route as RedirectPreloadSecondRouteImport } from './routes/redirect/preload/second' +import { Route as RedirectPreloadThirdRouteImport } from './routes/redirect/preload/third' +import { Route as RelativeLinkRelativeLinkARouteImport } from './routes/relative/link/relative-link-a' +import { Route as RelativeLinkRelativeLinkBRouteImport } from './routes/relative/link/relative-link-b' +import { Route as RelativeUseNavigateRelativeUseNavigateARouteImport } from './routes/relative/useNavigate/relative-useNavigate-a' +import { Route as RelativeUseNavigateRelativeUseNavigateBRouteImport } from './routes/relative/useNavigate/relative-useNavigate-b' +import { Route as Char45824Char54620Char48124Char44397WildcardSplatRouteImport } from './routes/대한민국/wildcard.$' +import { Route as Char45824Char54620Char48124Char44397Char55357Char56960IdRouteImport } from './routes/대한민국/🚀.$id' import { Route as NonNestedDeepBazIndexRouteImport } from './routes/non-nested/deep/$baz.index' -import { Route as ParamsPsNonNestedFooBarRouteImport } from './routes/params-ps/non-nested/$foo_/$bar' -import { Route as NonNestedSuffixChar123bazChar125suffixBarRouteImport } from './routes/non-nested/suffix/{$baz}suffix_.bar' -import { Route as NonNestedSuffixChar123bazChar125suffixFooRouteImport } from './routes/non-nested/suffix/{$baz}suffix.foo' -import { Route as NonNestedPrefixPrefixChar123bazChar125BarRouteImport } from './routes/non-nested/prefix/prefix{$baz}_.bar' -import { Route as NonNestedPrefixPrefixChar123bazChar125FooRouteImport } from './routes/non-nested/prefix/prefix{$baz}.foo' -import { Route as NonNestedPathBazBarRouteImport } from './routes/non-nested/path/baz_.bar' -import { Route as NonNestedPathBazFooRouteImport } from './routes/non-nested/path/baz.foo' -import { Route as NonNestedNamedBazBarRouteImport } from './routes/non-nested/named/$baz_.bar' -import { Route as NonNestedNamedBazFooRouteImport } from './routes/non-nested/named/$baz.foo' -import { Route as ParamsPsNamedFooBarRouteRouteImport } from './routes/params-ps/named/$foo/$bar.route' import { Route as NonNestedDeepBazBarRouteRouteImport } from './routes/non-nested/deep/$baz_.bar.route' -import { Route as RelativeUseNavigatePathPathIndexRouteImport } from './routes/relative/useNavigate/path/$path/index' -import { Route as RelativeUseNavigateNestedDeepIndexRouteImport } from './routes/relative/useNavigate/nested/deep/index' -import { Route as RelativeLinkPathPathIndexRouteImport } from './routes/relative/link/path/$path/index' -import { Route as RelativeLinkNestedDeepIndexRouteImport } from './routes/relative/link/nested/deep/index' +import { Route as NonNestedNamedBazIndexRouteImport } from './routes/non-nested/named/$baz.index' +import { Route as NonNestedNamedBazFooRouteImport } from './routes/non-nested/named/$baz.foo' +import { Route as NonNestedNamedBazBarRouteImport } from './routes/non-nested/named/$baz_.bar' +import { Route as NonNestedPathBazIndexRouteImport } from './routes/non-nested/path/baz.index' +import { Route as NonNestedPathBazFooRouteImport } from './routes/non-nested/path/baz.foo' +import { Route as NonNestedPathBazBarRouteImport } from './routes/non-nested/path/baz_.bar' +import { Route as NonNestedPrefixPrefixChar123bazChar125IndexRouteImport } from './routes/non-nested/prefix/prefix{$baz}.index' +import { Route as NonNestedPrefixPrefixChar123bazChar125FooRouteImport } from './routes/non-nested/prefix/prefix{$baz}.foo' +import { Route as NonNestedPrefixPrefixChar123bazChar125BarRouteImport } from './routes/non-nested/prefix/prefix{$baz}_.bar' +import { Route as NonNestedSuffixChar123bazChar125suffixIndexRouteImport } from './routes/non-nested/suffix/{$baz}suffix.index' +import { Route as NonNestedSuffixChar123bazChar125suffixFooRouteImport } from './routes/non-nested/suffix/{$baz}suffix.foo' +import { Route as NonNestedSuffixChar123bazChar125suffixBarRouteImport } from './routes/non-nested/suffix/{$baz}suffix_.bar' +import { Route as ParamsPsNamedFooBarRouteRouteImport } from './routes/params-ps/named/$foo/$bar.route' +import { Route as ParamsPsNonNestedFooBarRouteImport } from './routes/params-ps/non-nested/$foo_/$bar' +import { Route as RelativeLinkNestedIndexRouteImport } from './routes/relative/link/nested/index' +import { Route as RelativeLinkPathIndexRouteImport } from './routes/relative/link/path/index' +import { Route as RelativeLinkWithSearchIndexRouteImport } from './routes/relative/link/with-search/index' +import { Route as RelativeUseNavigateNestedIndexRouteImport } from './routes/relative/useNavigate/nested/index' +import { Route as RelativeUseNavigatePathIndexRouteImport } from './routes/relative/useNavigate/path/index' +import { Route as RelativeUseNavigateWithSearchIndexRouteImport } from './routes/relative/useNavigate/with-search/index' import { Route as NonNestedDeepBazBarIndexRouteImport } from './routes/non-nested/deep/$baz_.bar.index' -import { Route as ParamsPsNamedFooBarBazRouteImport } from './routes/params-ps/named/$foo/$bar.$baz' -import { Route as NonNestedDeepBazBarQuxRouteImport } from './routes/non-nested/deep/$baz_.bar_.qux' import { Route as NonNestedDeepBazBarFooRouteRouteImport } from './routes/non-nested/deep/$baz_.bar.$foo.route' +import { Route as NonNestedDeepBazBarQuxRouteImport } from './routes/non-nested/deep/$baz_.bar_.qux' +import { Route as ParamsPsNamedFooBarBazRouteImport } from './routes/params-ps/named/$foo/$bar.$baz' +import { Route as RelativeLinkNestedDeepIndexRouteImport } from './routes/relative/link/nested/deep/index' +import { Route as RelativeLinkPathPathIndexRouteImport } from './routes/relative/link/path/$path/index' +import { Route as RelativeUseNavigateNestedDeepIndexRouteImport } from './routes/relative/useNavigate/nested/deep/index' +import { Route as RelativeUseNavigatePathPathIndexRouteImport } from './routes/relative/useNavigate/path/$path/index' import { Route as NonNestedDeepBazBarFooIndexRouteImport } from './routes/non-nested/deep/$baz_.bar.$foo.index' import { Route as NonNestedDeepBazBarFooQuxRouteImport } from './routes/non-nested/deep/$baz_.bar.$foo_.qux' -const RemountDepsRoute = RemountDepsRouteImport.update({ - id: '/remountDeps', - path: '/remountDeps', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ - id: '/notRemountDeps', - path: '/notRemountDeps', - getParentRoute: () => rootRouteImport, -} as any) -const MasksRoute = MasksRouteImport.update({ - id: '/masks', - path: '/masks', - getParentRoute: () => rootRouteImport, -} as any) -const LazyErrorRoute = LazyErrorRouteImport.update({ - id: '/lazy-error', - path: '/lazy-error', - getParentRoute: () => rootRouteImport, -} as any).lazy(() => import('./routes/lazy-error.lazy').then((d) => d.Route)) -const HoverPreloadHashRoute = HoverPreloadHashRouteImport.update({ - id: '/hover-preload-hash', - path: '/hover-preload-hash', - getParentRoute: () => rootRouteImport, -} as any) -const EditingBRoute = EditingBRouteImport.update({ - id: '/editing-b', - path: '/editing-b', - getParentRoute: () => rootRouteImport, -} as any) -const EditingARoute = EditingARouteImport.update({ - id: '/editing-a', - path: '/editing-a', - getParentRoute: () => rootRouteImport, -} as any) -const ComponentTypesTestRoute = ComponentTypesTestRouteImport.update({ - id: '/component-types-test', - path: '/component-types-test', +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', getParentRoute: () => rootRouteImport, } as any) const AnchorRoute = AnchorRouteImport.update({ @@ -180,8 +147,85 @@ const AnchorRoute = AnchorRouteImport.update({ path: '/anchor', getParentRoute: () => rootRouteImport, } as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', +const ComponentTypesTestRoute = ComponentTypesTestRouteImport.update({ + id: '/component-types-test', + path: '/component-types-test', + getParentRoute: () => rootRouteImport, +} as any) +const DocumentNavigationRoute = DocumentNavigationRouteImport.update({ + id: '/document-navigation', + path: '/document-navigation', + getParentRoute: () => rootRouteImport, +} as any) +const DocumentNavigationTargetRoute = + DocumentNavigationTargetRouteImport.update({ + id: '/document-navigation-target', + path: '/document-navigation-target', + getParentRoute: () => rootRouteImport, + } as any) +const EditingARoute = EditingARouteImport.update({ + id: '/editing-a', + path: '/editing-a', + getParentRoute: () => rootRouteImport, +} as any) +const EditingBRoute = EditingBRouteImport.update({ + id: '/editing-b', + path: '/editing-b', + getParentRoute: () => rootRouteImport, +} as any) +const FullpathTestRouteRoute = FullpathTestRouteRouteImport.update({ + id: '/fullpath-test', + path: '/fullpath-test', + getParentRoute: () => rootRouteImport, +} as any) +const HistoryBlockingRoute = HistoryBlockingRouteImport.update({ + id: '/history-blocking', + path: '/history-blocking', + getParentRoute: () => rootRouteImport, +} as any) +const HoverPreloadHashRoute = HoverPreloadHashRouteImport.update({ + id: '/hover-preload-hash', + path: '/hover-preload-hash', + getParentRoute: () => rootRouteImport, +} as any) +const LazyErrorRoute = LazyErrorRouteImport.update({ + id: '/lazy-error', + path: '/lazy-error', + getParentRoute: () => rootRouteImport, +} as any).lazy(() => import('./routes/lazy-error.lazy').then((d) => d.Route)) +const MasksRoute = MasksRouteImport.update({ + id: '/masks', + path: '/masks', + getParentRoute: () => rootRouteImport, +} as any) +const NonNestedRouteRoute = NonNestedRouteRouteImport.update({ + id: '/non-nested', + path: '/non-nested', + getParentRoute: () => rootRouteImport, +} as any) +const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ + id: '/notRemountDeps', + path: '/notRemountDeps', + getParentRoute: () => rootRouteImport, +} as any) +const PathlessLayoutRouteRoute = PathlessLayoutRouteRouteImport.update({ + id: '/pathless-layout', + path: '/pathless-layout', + getParentRoute: () => rootRouteImport, +} as any) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const RemountDepsRoute = RemountDepsRouteImport.update({ + id: '/remountDeps', + path: '/remountDeps', + getParentRoute: () => rootRouteImport, +} as any) +const SearchParamsRouteRoute = SearchParamsRouteRouteImport.update({ + id: '/search-params', + path: '/search-params', getParentRoute: () => rootRouteImport, } as any) const Char45824Char54620Char48124Char44397RouteRoute = @@ -190,80 +234,20 @@ const Char45824Char54620Char48124Char44397RouteRoute = path: '/대한민국', getParentRoute: () => rootRouteImport, } as any) -const SearchParamsRouteRoute = SearchParamsRouteRouteImport.update({ - id: '/search-params', - path: '/search-params', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRouteRoute = PathlessLayoutRouteRouteImport.update({ - id: '/pathless-layout', - path: '/pathless-layout', - getParentRoute: () => rootRouteImport, -} as any) -const NonNestedRouteRoute = NonNestedRouteRouteImport.update({ - id: '/non-nested', - path: '/non-nested', - getParentRoute: () => rootRouteImport, -} as any) -const FullpathTestRouteRoute = FullpathTestRouteRouteImport.update({ - id: '/fullpath-test', - path: '/fullpath-test', - getParentRoute: () => rootRouteImport, -} as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const SearchParamsIndexRoute = SearchParamsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SearchParamsRouteRoute, -} as any) -const RelativeIndexRoute = RelativeIndexRouteImport.update({ - id: '/relative/', - path: '/relative/', - getParentRoute: () => rootRouteImport, -} as any) -const RedirectIndexRoute = RedirectIndexRouteImport.update({ - id: '/redirect/', - path: '/redirect/', - getParentRoute: () => rootRouteImport, -} as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const ParamsPsIndexRoute = ParamsPsIndexRouteImport.update({ - id: '/params-ps/', - path: '/params-ps/', - getParentRoute: () => rootRouteImport, -} as any) -const StructuralSharingEnabledRoute = - StructuralSharingEnabledRouteImport.update({ - id: '/structural-sharing/$enabled', - path: '/structural-sharing/$enabled', +const anotherGroupOnlyrouteinsideRoute = + anotherGroupOnlyrouteinsideRouteImport.update({ + id: '/(another-group)/onlyrouteinside', + path: '/onlyrouteinside', getParentRoute: () => rootRouteImport, } as any) -const SearchParamsDefaultRoute = SearchParamsDefaultRouteImport.update({ - id: '/default', - path: '/default', - getParentRoute: () => SearchParamsRouteRoute, -} as any) -const RedirectTargetRoute = RedirectTargetRouteImport.update({ - id: '/redirect/$target', - path: '/redirect/$target', +const groupLayoutRoute = groupLayoutRouteImport.update({ + id: '/(group)/_layout', getParentRoute: () => rootRouteImport, } as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, +const groupInsideRoute = groupInsideRouteImport.update({ + id: '/(group)/inside', + path: '/inside', + getParentRoute: () => rootRouteImport, } as any) const groupLazyinsideRoute = groupLazyinsideRouteImport .update({ @@ -272,61 +256,17 @@ const groupLazyinsideRoute = groupLazyinsideRouteImport getParentRoute: () => rootRouteImport, } as any) .lazy(() => import('./routes/(group)/lazyinside.lazy').then((d) => d.Route)) -const groupInsideRoute = groupInsideRouteImport.update({ - id: '/(group)/inside', - path: '/inside', - getParentRoute: () => rootRouteImport, +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, } as any) -const groupLayoutRoute = groupLayoutRouteImport.update({ - id: '/(group)/_layout', - getParentRoute: () => rootRouteImport, +const FullpathTestLayoutRouteRoute = FullpathTestLayoutRouteRouteImport.update({ + id: '/_layout', + getParentRoute: () => FullpathTestRouteRoute, } as any) -const anotherGroupOnlyrouteinsideRoute = - anotherGroupOnlyrouteinsideRouteImport.update({ - id: '/(another-group)/onlyrouteinside', - path: '/onlyrouteinside', - getParentRoute: () => rootRouteImport, - } as any) -const RelativeUseNavigateRouteRoute = - RelativeUseNavigateRouteRouteImport.update({ - id: '/relative/useNavigate', - path: '/relative/useNavigate', - getParentRoute: () => rootRouteImport, - } as any) -const RelativeLinkRouteRoute = RelativeLinkRouteRouteImport.update({ - id: '/relative/link', - path: '/relative/link', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutLayoutRouteRoute = - PathlessLayoutLayoutRouteRouteImport.update({ - id: '/_layout', - getParentRoute: () => PathlessLayoutRouteRoute, - } as any) -const ParamsPsStrictFalseRouteRoute = - ParamsPsStrictFalseRouteRouteImport.update({ - id: '/params-ps/strict-false', - path: '/params-ps/strict-false', - getParentRoute: () => rootRouteImport, - } as any) -const ParamsPsNonNestedRouteRoute = ParamsPsNonNestedRouteRouteImport.update({ - id: '/params-ps/non-nested', - path: '/params-ps/non-nested', - getParentRoute: () => rootRouteImport, -} as any) -const NonNestedSuffixRouteRoute = NonNestedSuffixRouteRouteImport.update({ - id: '/suffix', - path: '/suffix', - getParentRoute: () => NonNestedRouteRoute, -} as any) -const NonNestedPrefixRouteRoute = NonNestedPrefixRouteRouteImport.update({ - id: '/prefix', - path: '/prefix', - getParentRoute: () => NonNestedRouteRoute, -} as any) -const NonNestedPathRouteRoute = NonNestedPathRouteRouteImport.update({ - id: '/path', - path: '/path', +const NonNestedDeepRouteRoute = NonNestedDeepRouteRouteImport.update({ + id: '/deep', + path: '/deep', getParentRoute: () => NonNestedRouteRoute, } as any) const NonNestedNamedRouteRoute = NonNestedNamedRouteRouteImport.update({ @@ -334,159 +274,209 @@ const NonNestedNamedRouteRoute = NonNestedNamedRouteRouteImport.update({ path: '/named', getParentRoute: () => NonNestedRouteRoute, } as any) -const NonNestedDeepRouteRoute = NonNestedDeepRouteRouteImport.update({ - id: '/deep', - path: '/deep', +const NonNestedPathRouteRoute = NonNestedPathRouteRouteImport.update({ + id: '/path', + path: '/path', getParentRoute: () => NonNestedRouteRoute, } as any) -const FullpathTestLayoutRouteRoute = FullpathTestLayoutRouteRouteImport.update({ - id: '/_layout', - getParentRoute: () => FullpathTestRouteRoute, +const NonNestedPrefixRouteRoute = NonNestedPrefixRouteRouteImport.update({ + id: '/prefix', + path: '/prefix', + getParentRoute: () => NonNestedRouteRoute, } as any) -const RedirectTargetIndexRoute = RedirectTargetIndexRouteImport.update({ +const NonNestedSuffixRouteRoute = NonNestedSuffixRouteRouteImport.update({ + id: '/suffix', + path: '/suffix', + getParentRoute: () => NonNestedRouteRoute, +} as any) +const ParamsPsIndexRoute = ParamsPsIndexRouteImport.update({ + id: '/params-ps/', + path: '/params-ps/', + getParentRoute: () => rootRouteImport, +} as any) +const ParamsPsNonNestedRouteRoute = ParamsPsNonNestedRouteRouteImport.update({ + id: '/params-ps/non-nested', + path: '/params-ps/non-nested', + getParentRoute: () => rootRouteImport, +} as any) +const ParamsPsStrictFalseRouteRoute = + ParamsPsStrictFalseRouteRouteImport.update({ + id: '/params-ps/strict-false', + path: '/params-ps/strict-false', + getParentRoute: () => rootRouteImport, + } as any) +const PathlessLayoutLayoutRouteRoute = + PathlessLayoutLayoutRouteRouteImport.update({ + id: '/_layout', + getParentRoute: () => PathlessLayoutRouteRoute, + } as any) +const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => RedirectTargetRoute, + getParentRoute: () => PostsRoute, } as any) -const PathlessLayoutLayoutIndexRoute = - PathlessLayoutLayoutIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PathlessLayoutLayoutRouteRoute, +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const RedirectIndexRoute = RedirectIndexRouteImport.update({ + id: '/redirect/', + path: '/redirect/', + getParentRoute: () => rootRouteImport, +} as any) +const RedirectTargetRoute = RedirectTargetRouteImport.update({ + id: '/redirect/$target', + path: '/redirect/$target', + getParentRoute: () => rootRouteImport, +} as any) +const RelativeIndexRoute = RelativeIndexRouteImport.update({ + id: '/relative/', + path: '/relative/', + getParentRoute: () => rootRouteImport, +} as any) +const RelativeLinkRouteRoute = RelativeLinkRouteRouteImport.update({ + id: '/relative/link', + path: '/relative/link', + getParentRoute: () => rootRouteImport, +} as any) +const RelativeUseNavigateRouteRoute = + RelativeUseNavigateRouteRouteImport.update({ + id: '/relative/useNavigate', + path: '/relative/useNavigate', + getParentRoute: () => rootRouteImport, } as any) -const ParamsPsWildcardIndexRoute = ParamsPsWildcardIndexRouteImport.update({ - id: '/params-ps/wildcard/', - path: '/params-ps/wildcard/', +const SearchParamsIndexRoute = SearchParamsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SearchParamsRouteRoute, +} as any) +const SearchParamsDefaultRoute = SearchParamsDefaultRouteImport.update({ + id: '/default', + path: '/default', + getParentRoute: () => SearchParamsRouteRoute, +} as any) +const StructuralSharingEnabledRoute = + StructuralSharingEnabledRouteImport.update({ + id: '/structural-sharing/$enabled', + path: '/structural-sharing/$enabled', + getParentRoute: () => rootRouteImport, + } as any) +const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport.update({ + id: '/insidelayout', + path: '/insidelayout', + getParentRoute: () => groupLayoutRoute, +} as any) +const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport.update({ + id: '/(group)/subfolder/inside', + path: '/subfolder/inside', getParentRoute: () => rootRouteImport, } as any) -const ParamsPsNamedIndexRoute = ParamsPsNamedIndexRouteImport.update({ - id: '/params-ps/named/', - path: '/params-ps/named/', - getParentRoute: () => rootRouteImport, +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, +} as any) +const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => LayoutLayout2Route, } as any) const FullpathTestLayoutIndexRoute = FullpathTestLayoutIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => FullpathTestLayoutRouteRoute, } as any) -const Char45824Char54620Char48124Char44397Char55357Char56960IdRoute = - Char45824Char54620Char48124Char44397Char55357Char56960IdRouteImport.update({ - id: '/🚀/$id', - path: '/🚀/$id', - getParentRoute: () => Char45824Char54620Char48124Char44397RouteRoute, +const FullpathTestLayoutIdRoute = FullpathTestLayoutIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => FullpathTestLayoutRouteRoute, +} as any) +const MasksAdminUserIdRoute = MasksAdminUserIdRouteImport.update({ + id: '/admin/$userId', + path: '/admin/$userId', + getParentRoute: () => MasksRoute, +} as any) +const MasksPublicUsernameRoute = MasksPublicUsernameRouteImport.update({ + id: '/public/$username', + path: '/public/$username', + getParentRoute: () => MasksRoute, +} as any) +const NonNestedDeepBazRouteRoute = NonNestedDeepBazRouteRouteImport.update({ + id: '/$baz', + path: '/$baz', + getParentRoute: () => NonNestedDeepRouteRoute, +} as any) +const NonNestedNamedBazRouteRoute = NonNestedNamedBazRouteRouteImport.update({ + id: '/$baz', + path: '/$baz', + getParentRoute: () => NonNestedNamedRouteRoute, +} as any) +const NonNestedPathBazRouteRoute = NonNestedPathBazRouteRouteImport.update({ + id: '/baz', + path: '/baz', + getParentRoute: () => NonNestedPathRouteRoute, +} as any) +const NonNestedPrefixPrefixChar123bazChar125RouteRoute = + NonNestedPrefixPrefixChar123bazChar125RouteRouteImport.update({ + id: '/prefix{$baz}', + path: '/prefix{$baz}', + getParentRoute: () => NonNestedPrefixRouteRoute, } as any) -const Char45824Char54620Char48124Char44397WildcardSplatRoute = - Char45824Char54620Char48124Char44397WildcardSplatRouteImport.update({ - id: '/wildcard/$', - path: '/wildcard/$', - getParentRoute: () => Char45824Char54620Char48124Char44397RouteRoute, +const NonNestedSuffixChar123bazChar125suffixRouteRoute = + NonNestedSuffixChar123bazChar125suffixRouteRouteImport.update({ + id: '/{$baz}suffix', + path: '/{$baz}suffix', + getParentRoute: () => NonNestedSuffixRouteRoute, } as any) -const RelativeUseNavigateRelativeUseNavigateBRoute = - RelativeUseNavigateRelativeUseNavigateBRouteImport.update({ - id: '/relative-useNavigate-b', - path: '/relative-useNavigate-b', - getParentRoute: () => RelativeUseNavigateRouteRoute, - } as any) -const RelativeUseNavigateRelativeUseNavigateARoute = - RelativeUseNavigateRelativeUseNavigateARouteImport.update({ - id: '/relative-useNavigate-a', - path: '/relative-useNavigate-a', - getParentRoute: () => RelativeUseNavigateRouteRoute, - } as any) -const RelativeLinkRelativeLinkBRoute = - RelativeLinkRelativeLinkBRouteImport.update({ - id: '/relative-link-b', - path: '/relative-link-b', - getParentRoute: () => RelativeLinkRouteRoute, - } as any) -const RelativeLinkRelativeLinkARoute = - RelativeLinkRelativeLinkARouteImport.update({ - id: '/relative-link-a', - path: '/relative-link-a', - getParentRoute: () => RelativeLinkRouteRoute, - } as any) -const RedirectPreloadThirdRoute = RedirectPreloadThirdRouteImport.update({ - id: '/redirect/preload/third', - path: '/redirect/preload/third', +const ParamsPsNamedIndexRoute = ParamsPsNamedIndexRouteImport.update({ + id: '/params-ps/named/', + path: '/params-ps/named/', getParentRoute: () => rootRouteImport, } as any) -const RedirectPreloadSecondRoute = RedirectPreloadSecondRouteImport.update({ - id: '/redirect/preload/second', - path: '/redirect/preload/second', +const ParamsPsNamedFooRouteRoute = ParamsPsNamedFooRouteRouteImport.update({ + id: '/params-ps/named/$foo', + path: '/params-ps/named/$foo', getParentRoute: () => rootRouteImport, } as any) -const RedirectPreloadFirstRoute = RedirectPreloadFirstRouteImport.update({ - id: '/redirect/preload/first', - path: '/redirect/preload/first', - getParentRoute: () => rootRouteImport, -} as any) -const RedirectTargetViaRouteApiRedirectLoaderRoute = - RedirectTargetViaRouteApiRedirectLoaderRouteImport.update({ - id: '/via-routeApi-redirect-loader', - path: '/via-routeApi-redirect-loader', - getParentRoute: () => RedirectTargetRoute, - } as any) -const RedirectTargetViaRouteApiRedirectBeforeLoadRoute = - RedirectTargetViaRouteApiRedirectBeforeLoadRouteImport.update({ - id: '/via-routeApi-redirect-beforeLoad', - path: '/via-routeApi-redirect-beforeLoad', - getParentRoute: () => RedirectTargetRoute, - } as any) -const RedirectTargetViaRouteRedirectLoaderRoute = - RedirectTargetViaRouteRedirectLoaderRouteImport.update({ - id: '/via-route-redirect-loader', - path: '/via-route-redirect-loader', - getParentRoute: () => RedirectTargetRoute, - } as any) -const RedirectTargetViaRouteRedirectBeforeLoadRoute = - RedirectTargetViaRouteRedirectBeforeLoadRouteImport.update({ - id: '/via-route-redirect-beforeLoad', - path: '/via-route-redirect-beforeLoad', - getParentRoute: () => RedirectTargetRoute, - } as any) -const RedirectTargetViaLoaderRoute = RedirectTargetViaLoaderRouteImport.update({ - id: '/via-loader', - path: '/via-loader', - getParentRoute: () => RedirectTargetRoute, -} as any) -const RedirectTargetViaBeforeLoadRoute = - RedirectTargetViaBeforeLoadRouteImport.update({ - id: '/via-beforeLoad', - path: '/via-beforeLoad', - getParentRoute: () => RedirectTargetRoute, - } as any) -const RedirectTargetDestinationRoute = - RedirectTargetDestinationRouteImport.update({ - id: '/destination', - path: '/destination', - getParentRoute: () => RedirectTargetRoute, - } as any) -const PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ - id: '/posts_/$postId/edit', - path: '/posts/$postId/edit', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutLayoutChildRoute = - PathlessLayoutLayoutChildRouteImport.update({ - id: '/child', - path: '/child', - getParentRoute: () => PathlessLayoutLayoutRouteRoute, - } as any) -const ParamsSingleValueRoute = ParamsSingleValueRouteImport.update({ - id: '/params/single/$value', - path: '/params/single/$value', - getParentRoute: () => rootRouteImport, -} as any) -const ParamsPsWildcardChar123Char125suffixAtChar45824Route = - ParamsPsWildcardChar123Char125suffixAtChar45824RouteImport.update({ - id: '/params-ps/wildcard/{$}suffix@대', - path: '/params-ps/wildcard/{$}suffix@대', +const ParamsPsNamedPrefixChar123fooChar125Route = + ParamsPsNamedPrefixChar123fooChar125RouteImport.update({ + id: '/params-ps/named/prefix{$foo}', + path: '/params-ps/named/prefix{$foo}', getParentRoute: () => rootRouteImport, } as any) -const ParamsPsWildcardChar123Char125suffixRoute = - ParamsPsWildcardChar123Char125suffixRouteImport.update({ - id: '/params-ps/wildcard/{$}suffix', - path: '/params-ps/wildcard/{$}suffix', +const ParamsPsNamedChar123fooChar125suffixRoute = + ParamsPsNamedChar123fooChar125suffixRouteImport.update({ + id: '/params-ps/named/{$foo}suffix', + path: '/params-ps/named/{$foo}suffix', + getParentRoute: () => rootRouteImport, + } as any) +const ParamsPsNonNestedFooRouteRoute = + ParamsPsNonNestedFooRouteRouteImport.update({ + id: '/$foo_', + path: '/$foo', + getParentRoute: () => ParamsPsNonNestedRouteRoute, + } as any) +const ParamsPsStrictFalseVersionRouteRoute = + ParamsPsStrictFalseVersionRouteRouteImport.update({ + id: '/$version', + path: '/$version', + getParentRoute: () => ParamsPsStrictFalseRouteRoute, + } as any) +const ParamsPsWildcardIndexRoute = ParamsPsWildcardIndexRouteImport.update({ + id: '/params-ps/wildcard/', + path: '/params-ps/wildcard/', + getParentRoute: () => rootRouteImport, +} as any) +const ParamsPsWildcardSplatRoute = ParamsPsWildcardSplatRouteImport.update({ + id: '/params-ps/wildcard/$', + path: '/params-ps/wildcard/$', + getParentRoute: () => rootRouteImport, +} as any) +const ParamsPsWildcardPrefixAtChar45824Char123Char125Route = + ParamsPsWildcardPrefixAtChar45824Char123Char125RouteImport.update({ + id: '/params-ps/wildcard/prefix@대{$}', + path: '/params-ps/wildcard/prefix@대{$}', getParentRoute: () => rootRouteImport, } as any) const ParamsPsWildcardPrefixChar123Char125Route = @@ -495,112 +485,245 @@ const ParamsPsWildcardPrefixChar123Char125Route = path: '/params-ps/wildcard/prefix{$}', getParentRoute: () => rootRouteImport, } as any) -const ParamsPsWildcardPrefixAtChar45824Char123Char125Route = - ParamsPsWildcardPrefixAtChar45824Char123Char125RouteImport.update({ - id: '/params-ps/wildcard/prefix@대{$}', - path: '/params-ps/wildcard/prefix@대{$}', +const ParamsPsWildcardChar123Char125suffixRoute = + ParamsPsWildcardChar123Char125suffixRouteImport.update({ + id: '/params-ps/wildcard/{$}suffix', + path: '/params-ps/wildcard/{$}suffix', getParentRoute: () => rootRouteImport, } as any) -const ParamsPsWildcardSplatRoute = ParamsPsWildcardSplatRouteImport.update({ - id: '/params-ps/wildcard/$', - path: '/params-ps/wildcard/$', - getParentRoute: () => rootRouteImport, -} as any) -const ParamsPsNamedChar123fooChar125suffixRoute = - ParamsPsNamedChar123fooChar125suffixRouteImport.update({ - id: '/params-ps/named/{$foo}suffix', - path: '/params-ps/named/{$foo}suffix', +const ParamsPsWildcardChar123Char125suffixAtChar45824Route = + ParamsPsWildcardChar123Char125suffixAtChar45824RouteImport.update({ + id: '/params-ps/wildcard/{$}suffix@대', + path: '/params-ps/wildcard/{$}suffix@대', getParentRoute: () => rootRouteImport, } as any) -const ParamsPsNamedPrefixChar123fooChar125Route = - ParamsPsNamedPrefixChar123fooChar125RouteImport.update({ - id: '/params-ps/named/prefix{$foo}', - path: '/params-ps/named/prefix{$foo}', - getParentRoute: () => rootRouteImport, - } as any) -const MasksPublicUsernameRoute = MasksPublicUsernameRouteImport.update({ - id: '/public/$username', - path: '/public/$username', - getParentRoute: () => MasksRoute, -} as any) -const MasksAdminUserIdRoute = MasksAdminUserIdRouteImport.update({ - id: '/admin/$userId', - path: '/admin/$userId', - getParentRoute: () => MasksRoute, -} as any) -const FullpathTestLayoutIdRoute = FullpathTestLayoutIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => FullpathTestLayoutRouteRoute, -} as any) -const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => LayoutLayout2Route, -} as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, -} as any) -const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport.update({ - id: '/(group)/subfolder/inside', - path: '/subfolder/inside', +const ParamsSingleValueRoute = ParamsSingleValueRouteImport.update({ + id: '/params/single/$value', + path: '/params/single/$value', getParentRoute: () => rootRouteImport, } as any) -const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport.update({ - id: '/insidelayout', - path: '/insidelayout', - getParentRoute: () => groupLayoutRoute, -} as any) -const ParamsPsStrictFalseVersionRouteRoute = - ParamsPsStrictFalseVersionRouteRouteImport.update({ - id: '/$version', - path: '/$version', - getParentRoute: () => ParamsPsStrictFalseRouteRoute, +const PathlessLayoutLayoutIndexRoute = + PathlessLayoutLayoutIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PathlessLayoutLayoutRouteRoute, } as any) -const ParamsPsNonNestedFooRouteRoute = - ParamsPsNonNestedFooRouteRouteImport.update({ - id: '/$foo_', - path: '/$foo', - getParentRoute: () => ParamsPsNonNestedRouteRoute, +const PathlessLayoutLayoutChildRoute = + PathlessLayoutLayoutChildRouteImport.update({ + id: '/child', + path: '/child', + getParentRoute: () => PathlessLayoutLayoutRouteRoute, } as any) -const ParamsPsNamedFooRouteRoute = ParamsPsNamedFooRouteRouteImport.update({ - id: '/params-ps/named/$foo', - path: '/params-ps/named/$foo', +const PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ + id: '/posts_/$postId/edit', + path: '/posts/$postId/edit', getParentRoute: () => rootRouteImport, } as any) -const NonNestedSuffixChar123bazChar125suffixRouteRoute = - NonNestedSuffixChar123bazChar125suffixRouteRouteImport.update({ - id: '/{$baz}suffix', - path: '/{$baz}suffix', - getParentRoute: () => NonNestedSuffixRouteRoute, - } as any) -const NonNestedPrefixPrefixChar123bazChar125RouteRoute = - NonNestedPrefixPrefixChar123bazChar125RouteRouteImport.update({ - id: '/prefix{$baz}', - path: '/prefix{$baz}', - getParentRoute: () => NonNestedPrefixRouteRoute, - } as any) -const NonNestedPathBazRouteRoute = NonNestedPathBazRouteRouteImport.update({ - id: '/baz', - path: '/baz', - getParentRoute: () => NonNestedPathRouteRoute, +const RedirectTargetIndexRoute = RedirectTargetIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => RedirectTargetRoute, } as any) -const NonNestedNamedBazRouteRoute = NonNestedNamedBazRouteRouteImport.update({ - id: '/$baz', - path: '/$baz', +const RedirectTargetDestinationRoute = + RedirectTargetDestinationRouteImport.update({ + id: '/destination', + path: '/destination', + getParentRoute: () => RedirectTargetRoute, + } as any) +const RedirectTargetViaBeforeLoadRoute = + RedirectTargetViaBeforeLoadRouteImport.update({ + id: '/via-beforeLoad', + path: '/via-beforeLoad', + getParentRoute: () => RedirectTargetRoute, + } as any) +const RedirectTargetViaLoaderRoute = RedirectTargetViaLoaderRouteImport.update({ + id: '/via-loader', + path: '/via-loader', + getParentRoute: () => RedirectTargetRoute, +} as any) +const RedirectTargetViaRouteRedirectBeforeLoadRoute = + RedirectTargetViaRouteRedirectBeforeLoadRouteImport.update({ + id: '/via-route-redirect-beforeLoad', + path: '/via-route-redirect-beforeLoad', + getParentRoute: () => RedirectTargetRoute, + } as any) +const RedirectTargetViaRouteRedirectLoaderRoute = + RedirectTargetViaRouteRedirectLoaderRouteImport.update({ + id: '/via-route-redirect-loader', + path: '/via-route-redirect-loader', + getParentRoute: () => RedirectTargetRoute, + } as any) +const RedirectTargetViaRouteApiRedirectBeforeLoadRoute = + RedirectTargetViaRouteApiRedirectBeforeLoadRouteImport.update({ + id: '/via-routeApi-redirect-beforeLoad', + path: '/via-routeApi-redirect-beforeLoad', + getParentRoute: () => RedirectTargetRoute, + } as any) +const RedirectTargetViaRouteApiRedirectLoaderRoute = + RedirectTargetViaRouteApiRedirectLoaderRouteImport.update({ + id: '/via-routeApi-redirect-loader', + path: '/via-routeApi-redirect-loader', + getParentRoute: () => RedirectTargetRoute, + } as any) +const RedirectPreloadFirstRoute = RedirectPreloadFirstRouteImport.update({ + id: '/redirect/preload/first', + path: '/redirect/preload/first', + getParentRoute: () => rootRouteImport, +} as any) +const RedirectPreloadSecondRoute = RedirectPreloadSecondRouteImport.update({ + id: '/redirect/preload/second', + path: '/redirect/preload/second', + getParentRoute: () => rootRouteImport, +} as any) +const RedirectPreloadThirdRoute = RedirectPreloadThirdRouteImport.update({ + id: '/redirect/preload/third', + path: '/redirect/preload/third', + getParentRoute: () => rootRouteImport, +} as any) +const RelativeLinkRelativeLinkARoute = + RelativeLinkRelativeLinkARouteImport.update({ + id: '/relative-link-a', + path: '/relative-link-a', + getParentRoute: () => RelativeLinkRouteRoute, + } as any) +const RelativeLinkRelativeLinkBRoute = + RelativeLinkRelativeLinkBRouteImport.update({ + id: '/relative-link-b', + path: '/relative-link-b', + getParentRoute: () => RelativeLinkRouteRoute, + } as any) +const RelativeUseNavigateRelativeUseNavigateARoute = + RelativeUseNavigateRelativeUseNavigateARouteImport.update({ + id: '/relative-useNavigate-a', + path: '/relative-useNavigate-a', + getParentRoute: () => RelativeUseNavigateRouteRoute, + } as any) +const RelativeUseNavigateRelativeUseNavigateBRoute = + RelativeUseNavigateRelativeUseNavigateBRouteImport.update({ + id: '/relative-useNavigate-b', + path: '/relative-useNavigate-b', + getParentRoute: () => RelativeUseNavigateRouteRoute, + } as any) +const Char45824Char54620Char48124Char44397WildcardSplatRoute = + Char45824Char54620Char48124Char44397WildcardSplatRouteImport.update({ + id: '/wildcard/$', + path: '/wildcard/$', + getParentRoute: () => Char45824Char54620Char48124Char44397RouteRoute, + } as any) +const Char45824Char54620Char48124Char44397Char55357Char56960IdRoute = + Char45824Char54620Char48124Char44397Char55357Char56960IdRouteImport.update({ + id: '/🚀/$id', + path: '/🚀/$id', + getParentRoute: () => Char45824Char54620Char48124Char44397RouteRoute, + } as any) +const NonNestedDeepBazIndexRoute = NonNestedDeepBazIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => NonNestedDeepBazRouteRoute, +} as any) +const NonNestedDeepBazBarRouteRoute = + NonNestedDeepBazBarRouteRouteImport.update({ + id: '/$baz_/bar', + path: '/$baz/bar', + getParentRoute: () => NonNestedDeepRouteRoute, + } as any) +const NonNestedNamedBazIndexRoute = NonNestedNamedBazIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => NonNestedNamedBazRouteRoute, +} as any) +const NonNestedNamedBazFooRoute = NonNestedNamedBazFooRouteImport.update({ + id: '/foo', + path: '/foo', + getParentRoute: () => NonNestedNamedBazRouteRoute, +} as any) +const NonNestedNamedBazBarRoute = NonNestedNamedBazBarRouteImport.update({ + id: '/$baz_/bar', + path: '/$baz/bar', getParentRoute: () => NonNestedNamedRouteRoute, } as any) -const NonNestedDeepBazRouteRoute = NonNestedDeepBazRouteRouteImport.update({ - id: '/$baz', - path: '/$baz', - getParentRoute: () => NonNestedDeepRouteRoute, +const NonNestedPathBazIndexRoute = NonNestedPathBazIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => NonNestedPathBazRouteRoute, } as any) -const RelativeUseNavigateWithSearchIndexRoute = - RelativeUseNavigateWithSearchIndexRouteImport.update({ +const NonNestedPathBazFooRoute = NonNestedPathBazFooRouteImport.update({ + id: '/foo', + path: '/foo', + getParentRoute: () => NonNestedPathBazRouteRoute, +} as any) +const NonNestedPathBazBarRoute = NonNestedPathBazBarRouteImport.update({ + id: '/baz_/bar', + path: '/baz/bar', + getParentRoute: () => NonNestedPathRouteRoute, +} as any) +const NonNestedPrefixPrefixChar123bazChar125IndexRoute = + NonNestedPrefixPrefixChar123bazChar125IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => NonNestedPrefixPrefixChar123bazChar125RouteRoute, + } as any) +const NonNestedPrefixPrefixChar123bazChar125FooRoute = + NonNestedPrefixPrefixChar123bazChar125FooRouteImport.update({ + id: '/foo', + path: '/foo', + getParentRoute: () => NonNestedPrefixPrefixChar123bazChar125RouteRoute, + } as any) +const NonNestedPrefixPrefixChar123bazChar125BarRoute = + NonNestedPrefixPrefixChar123bazChar125BarRouteImport.update({ + id: '/prefix{$baz}_/bar', + path: '/prefix{$baz}/bar', + getParentRoute: () => NonNestedPrefixRouteRoute, + } as any) +const NonNestedSuffixChar123bazChar125suffixIndexRoute = + NonNestedSuffixChar123bazChar125suffixIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => NonNestedSuffixChar123bazChar125suffixRouteRoute, + } as any) +const NonNestedSuffixChar123bazChar125suffixFooRoute = + NonNestedSuffixChar123bazChar125suffixFooRouteImport.update({ + id: '/foo', + path: '/foo', + getParentRoute: () => NonNestedSuffixChar123bazChar125suffixRouteRoute, + } as any) +const NonNestedSuffixChar123bazChar125suffixBarRoute = + NonNestedSuffixChar123bazChar125suffixBarRouteImport.update({ + id: '/{$baz}suffix_/bar', + path: '/{$baz}suffix/bar', + getParentRoute: () => NonNestedSuffixRouteRoute, + } as any) +const ParamsPsNamedFooBarRouteRoute = + ParamsPsNamedFooBarRouteRouteImport.update({ + id: '/$bar', + path: '/$bar', + getParentRoute: () => ParamsPsNamedFooRouteRoute, + } as any) +const ParamsPsNonNestedFooBarRoute = ParamsPsNonNestedFooBarRouteImport.update({ + id: '/$bar', + path: '/$bar', + getParentRoute: () => ParamsPsNonNestedFooRouteRoute, +} as any) +const RelativeLinkNestedIndexRoute = RelativeLinkNestedIndexRouteImport.update({ + id: '/nested/', + path: '/nested/', + getParentRoute: () => RelativeLinkRouteRoute, +} as any) +const RelativeLinkPathIndexRoute = RelativeLinkPathIndexRouteImport.update({ + id: '/path/', + path: '/path/', + getParentRoute: () => RelativeLinkRouteRoute, +} as any) +const RelativeLinkWithSearchIndexRoute = + RelativeLinkWithSearchIndexRouteImport.update({ id: '/with-search/', path: '/with-search/', + getParentRoute: () => RelativeLinkRouteRoute, + } as any) +const RelativeUseNavigateNestedIndexRoute = + RelativeUseNavigateNestedIndexRouteImport.update({ + id: '/nested/', + path: '/nested/', getParentRoute: () => RelativeUseNavigateRouteRoute, } as any) const RelativeUseNavigatePathIndexRoute = @@ -609,162 +732,58 @@ const RelativeUseNavigatePathIndexRoute = path: '/path/', getParentRoute: () => RelativeUseNavigateRouteRoute, } as any) -const RelativeUseNavigateNestedIndexRoute = - RelativeUseNavigateNestedIndexRouteImport.update({ - id: '/nested/', - path: '/nested/', - getParentRoute: () => RelativeUseNavigateRouteRoute, - } as any) -const RelativeLinkWithSearchIndexRoute = - RelativeLinkWithSearchIndexRouteImport.update({ +const RelativeUseNavigateWithSearchIndexRoute = + RelativeUseNavigateWithSearchIndexRouteImport.update({ id: '/with-search/', path: '/with-search/', - getParentRoute: () => RelativeLinkRouteRoute, - } as any) -const RelativeLinkPathIndexRoute = RelativeLinkPathIndexRouteImport.update({ - id: '/path/', - path: '/path/', - getParentRoute: () => RelativeLinkRouteRoute, -} as any) -const RelativeLinkNestedIndexRoute = RelativeLinkNestedIndexRouteImport.update({ - id: '/nested/', - path: '/nested/', - getParentRoute: () => RelativeLinkRouteRoute, -} as any) -const NonNestedSuffixChar123bazChar125suffixIndexRoute = - NonNestedSuffixChar123bazChar125suffixIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => NonNestedSuffixChar123bazChar125suffixRouteRoute, - } as any) -const NonNestedPrefixPrefixChar123bazChar125IndexRoute = - NonNestedPrefixPrefixChar123bazChar125IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => NonNestedPrefixPrefixChar123bazChar125RouteRoute, - } as any) -const NonNestedPathBazIndexRoute = NonNestedPathBazIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => NonNestedPathBazRouteRoute, -} as any) -const NonNestedNamedBazIndexRoute = NonNestedNamedBazIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => NonNestedNamedBazRouteRoute, -} as any) -const NonNestedDeepBazIndexRoute = NonNestedDeepBazIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => NonNestedDeepBazRouteRoute, -} as any) -const ParamsPsNonNestedFooBarRoute = ParamsPsNonNestedFooBarRouteImport.update({ - id: '/$bar', - path: '/$bar', - getParentRoute: () => ParamsPsNonNestedFooRouteRoute, -} as any) -const NonNestedSuffixChar123bazChar125suffixBarRoute = - NonNestedSuffixChar123bazChar125suffixBarRouteImport.update({ - id: '/{$baz}suffix_/bar', - path: '/{$baz}suffix/bar', - getParentRoute: () => NonNestedSuffixRouteRoute, - } as any) -const NonNestedSuffixChar123bazChar125suffixFooRoute = - NonNestedSuffixChar123bazChar125suffixFooRouteImport.update({ - id: '/foo', - path: '/foo', - getParentRoute: () => NonNestedSuffixChar123bazChar125suffixRouteRoute, - } as any) -const NonNestedPrefixPrefixChar123bazChar125BarRoute = - NonNestedPrefixPrefixChar123bazChar125BarRouteImport.update({ - id: '/prefix{$baz}_/bar', - path: '/prefix{$baz}/bar', - getParentRoute: () => NonNestedPrefixRouteRoute, - } as any) -const NonNestedPrefixPrefixChar123bazChar125FooRoute = - NonNestedPrefixPrefixChar123bazChar125FooRouteImport.update({ - id: '/foo', - path: '/foo', - getParentRoute: () => NonNestedPrefixPrefixChar123bazChar125RouteRoute, - } as any) -const NonNestedPathBazBarRoute = NonNestedPathBazBarRouteImport.update({ - id: '/baz_/bar', - path: '/baz/bar', - getParentRoute: () => NonNestedPathRouteRoute, -} as any) -const NonNestedPathBazFooRoute = NonNestedPathBazFooRouteImport.update({ - id: '/foo', - path: '/foo', - getParentRoute: () => NonNestedPathBazRouteRoute, -} as any) -const NonNestedNamedBazBarRoute = NonNestedNamedBazBarRouteImport.update({ - id: '/$baz_/bar', - path: '/$baz/bar', - getParentRoute: () => NonNestedNamedRouteRoute, -} as any) -const NonNestedNamedBazFooRoute = NonNestedNamedBazFooRouteImport.update({ - id: '/foo', - path: '/foo', - getParentRoute: () => NonNestedNamedBazRouteRoute, -} as any) -const ParamsPsNamedFooBarRouteRoute = - ParamsPsNamedFooBarRouteRouteImport.update({ - id: '/$bar', - path: '/$bar', - getParentRoute: () => ParamsPsNamedFooRouteRoute, - } as any) -const NonNestedDeepBazBarRouteRoute = - NonNestedDeepBazBarRouteRouteImport.update({ - id: '/$baz_/bar', - path: '/$baz/bar', - getParentRoute: () => NonNestedDeepRouteRoute, - } as any) -const RelativeUseNavigatePathPathIndexRoute = - RelativeUseNavigatePathPathIndexRouteImport.update({ - id: '/path/$path/', - path: '/path/$path/', getParentRoute: () => RelativeUseNavigateRouteRoute, } as any) -const RelativeUseNavigateNestedDeepIndexRoute = - RelativeUseNavigateNestedDeepIndexRouteImport.update({ - id: '/nested/deep/', - path: '/nested/deep/', - getParentRoute: () => RelativeUseNavigateRouteRoute, - } as any) -const RelativeLinkPathPathIndexRoute = - RelativeLinkPathPathIndexRouteImport.update({ - id: '/path/$path/', - path: '/path/$path/', - getParentRoute: () => RelativeLinkRouteRoute, - } as any) -const RelativeLinkNestedDeepIndexRoute = - RelativeLinkNestedDeepIndexRouteImport.update({ - id: '/nested/deep/', - path: '/nested/deep/', - getParentRoute: () => RelativeLinkRouteRoute, - } as any) const NonNestedDeepBazBarIndexRoute = NonNestedDeepBazBarIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => NonNestedDeepBazBarRouteRoute, } as any) -const ParamsPsNamedFooBarBazRoute = ParamsPsNamedFooBarBazRouteImport.update({ - id: '/$baz', - path: '/$baz', - getParentRoute: () => ParamsPsNamedFooBarRouteRoute, -} as any) -const NonNestedDeepBazBarQuxRoute = NonNestedDeepBazBarQuxRouteImport.update({ - id: '/$baz_/bar_/qux', - path: '/$baz/bar/qux', - getParentRoute: () => NonNestedDeepRouteRoute, -} as any) const NonNestedDeepBazBarFooRouteRoute = NonNestedDeepBazBarFooRouteRouteImport.update({ id: '/$foo', path: '/$foo', getParentRoute: () => NonNestedDeepBazBarRouteRoute, } as any) +const NonNestedDeepBazBarQuxRoute = NonNestedDeepBazBarQuxRouteImport.update({ + id: '/$baz_/bar_/qux', + path: '/$baz/bar/qux', + getParentRoute: () => NonNestedDeepRouteRoute, +} as any) +const ParamsPsNamedFooBarBazRoute = ParamsPsNamedFooBarBazRouteImport.update({ + id: '/$baz', + path: '/$baz', + getParentRoute: () => ParamsPsNamedFooBarRouteRoute, +} as any) +const RelativeLinkNestedDeepIndexRoute = + RelativeLinkNestedDeepIndexRouteImport.update({ + id: '/nested/deep/', + path: '/nested/deep/', + getParentRoute: () => RelativeLinkRouteRoute, + } as any) +const RelativeLinkPathPathIndexRoute = + RelativeLinkPathPathIndexRouteImport.update({ + id: '/path/$path/', + path: '/path/$path/', + getParentRoute: () => RelativeLinkRouteRoute, + } as any) +const RelativeUseNavigateNestedDeepIndexRoute = + RelativeUseNavigateNestedDeepIndexRouteImport.update({ + id: '/nested/deep/', + path: '/nested/deep/', + getParentRoute: () => RelativeUseNavigateRouteRoute, + } as any) +const RelativeUseNavigatePathPathIndexRoute = + RelativeUseNavigatePathPathIndexRouteImport.update({ + id: '/path/$path/', + path: '/path/$path/', + getParentRoute: () => RelativeUseNavigateRouteRoute, + } as any) const NonNestedDeepBazBarFooIndexRoute = NonNestedDeepBazBarFooIndexRouteImport.update({ id: '/', @@ -787,8 +806,11 @@ export interface FileRoutesByFullPath { '/대한민국': typeof Char45824Char54620Char48124Char44397RouteRouteWithChildren '/anchor': typeof AnchorRoute '/component-types-test': typeof ComponentTypesTestRoute + '/document-navigation': typeof DocumentNavigationRoute + '/document-navigation-target': typeof DocumentNavigationTargetRoute '/editing-a': typeof EditingARoute '/editing-b': typeof EditingBRoute + '/history-blocking': typeof HistoryBlockingRoute '/hover-preload-hash': typeof HoverPreloadHashRoute '/lazy-error': typeof LazyErrorRoute '/masks': typeof MasksRouteWithChildren @@ -903,8 +925,11 @@ export interface FileRoutesByTo { '/대한민국': typeof Char45824Char54620Char48124Char44397RouteRouteWithChildren '/anchor': typeof AnchorRoute '/component-types-test': typeof ComponentTypesTestRoute + '/document-navigation': typeof DocumentNavigationRoute + '/document-navigation-target': typeof DocumentNavigationTargetRoute '/editing-a': typeof EditingARoute '/editing-b': typeof EditingBRoute + '/history-blocking': typeof HistoryBlockingRoute '/hover-preload-hash': typeof HoverPreloadHashRoute '/lazy-error': typeof LazyErrorRoute '/masks': typeof MasksRouteWithChildren @@ -1011,8 +1036,11 @@ export interface FileRoutesById { '/_layout': typeof LayoutRouteWithChildren '/anchor': typeof AnchorRoute '/component-types-test': typeof ComponentTypesTestRoute + '/document-navigation': typeof DocumentNavigationRoute + '/document-navigation-target': typeof DocumentNavigationTargetRoute '/editing-a': typeof EditingARoute '/editing-b': typeof EditingBRoute + '/history-blocking': typeof HistoryBlockingRoute '/hover-preload-hash': typeof HoverPreloadHashRoute '/lazy-error': typeof LazyErrorRoute '/masks': typeof MasksRouteWithChildren @@ -1134,8 +1162,11 @@ export interface FileRouteTypes { | '/대한민국' | '/anchor' | '/component-types-test' + | '/document-navigation' + | '/document-navigation-target' | '/editing-a' | '/editing-b' + | '/history-blocking' | '/hover-preload-hash' | '/lazy-error' | '/masks' @@ -1250,8 +1281,11 @@ export interface FileRouteTypes { | '/대한민국' | '/anchor' | '/component-types-test' + | '/document-navigation' + | '/document-navigation-target' | '/editing-a' | '/editing-b' + | '/history-blocking' | '/hover-preload-hash' | '/lazy-error' | '/masks' @@ -1357,8 +1391,11 @@ export interface FileRouteTypes { | '/_layout' | '/anchor' | '/component-types-test' + | '/document-navigation' + | '/document-navigation-target' | '/editing-a' | '/editing-b' + | '/history-blocking' | '/hover-preload-hash' | '/lazy-error' | '/masks' @@ -1480,8 +1517,11 @@ export interface RootRouteChildren { LayoutRoute: typeof LayoutRouteWithChildren AnchorRoute: typeof AnchorRoute ComponentTypesTestRoute: typeof ComponentTypesTestRoute + DocumentNavigationRoute: typeof DocumentNavigationRoute + DocumentNavigationTargetRoute: typeof DocumentNavigationTargetRoute EditingARoute: typeof EditingARoute EditingBRoute: typeof EditingBRoute + HistoryBlockingRoute: typeof HistoryBlockingRoute HoverPreloadHashRoute: typeof HoverPreloadHashRoute LazyErrorRoute: typeof LazyErrorRoute MasksRoute: typeof MasksRouteWithChildren @@ -1521,74 +1561,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/remountDeps': { - id: '/remountDeps' - path: '/remountDeps' - fullPath: '/remountDeps' - preLoaderRoute: typeof RemountDepsRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/notRemountDeps': { - id: '/notRemountDeps' - path: '/notRemountDeps' - fullPath: '/notRemountDeps' - preLoaderRoute: typeof NotRemountDepsRouteImport - parentRoute: typeof rootRouteImport - } - '/masks': { - id: '/masks' - path: '/masks' - fullPath: '/masks' - preLoaderRoute: typeof MasksRouteImport - parentRoute: typeof rootRouteImport - } - '/lazy-error': { - id: '/lazy-error' - path: '/lazy-error' - fullPath: '/lazy-error' - preLoaderRoute: typeof LazyErrorRouteImport - parentRoute: typeof rootRouteImport - } - '/hover-preload-hash': { - id: '/hover-preload-hash' - path: '/hover-preload-hash' - fullPath: '/hover-preload-hash' - preLoaderRoute: typeof HoverPreloadHashRouteImport - parentRoute: typeof rootRouteImport - } - '/editing-b': { - id: '/editing-b' - path: '/editing-b' - fullPath: '/editing-b' - preLoaderRoute: typeof EditingBRouteImport - parentRoute: typeof rootRouteImport - } - '/editing-a': { - id: '/editing-a' - path: '/editing-a' - fullPath: '/editing-a' - preLoaderRoute: typeof EditingARouteImport - parentRoute: typeof rootRouteImport - } - '/component-types-test': { - id: '/component-types-test' - path: '/component-types-test' - fullPath: '/component-types-test' - preLoaderRoute: typeof ComponentTypesTestRouteImport - parentRoute: typeof rootRouteImport - } - '/anchor': { - id: '/anchor' - path: '/anchor' - fullPath: '/anchor' - preLoaderRoute: typeof AnchorRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -1598,32 +1575,46 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/대한민국': { - id: '/대한민국' - path: '/대한민국' - fullPath: '/대한민국' - preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteRouteImport + '/anchor': { + id: '/anchor' + path: '/anchor' + fullPath: '/anchor' + preLoaderRoute: typeof AnchorRouteImport parentRoute: typeof rootRouteImport } - '/search-params': { - id: '/search-params' - path: '/search-params' - fullPath: '/search-params' - preLoaderRoute: typeof SearchParamsRouteRouteImport + '/component-types-test': { + id: '/component-types-test' + path: '/component-types-test' + fullPath: '/component-types-test' + preLoaderRoute: typeof ComponentTypesTestRouteImport parentRoute: typeof rootRouteImport } - '/pathless-layout': { - id: '/pathless-layout' - path: '/pathless-layout' - fullPath: '/pathless-layout' - preLoaderRoute: typeof PathlessLayoutRouteRouteImport + '/document-navigation': { + id: '/document-navigation' + path: '/document-navigation' + fullPath: '/document-navigation' + preLoaderRoute: typeof DocumentNavigationRouteImport parentRoute: typeof rootRouteImport } - '/non-nested': { - id: '/non-nested' - path: '/non-nested' - fullPath: '/non-nested' - preLoaderRoute: typeof NonNestedRouteRouteImport + '/document-navigation-target': { + id: '/document-navigation-target' + path: '/document-navigation-target' + fullPath: '/document-navigation-target' + preLoaderRoute: typeof DocumentNavigationTargetRouteImport + parentRoute: typeof rootRouteImport + } + '/editing-a': { + id: '/editing-a' + path: '/editing-a' + fullPath: '/editing-a' + preLoaderRoute: typeof EditingARouteImport + parentRoute: typeof rootRouteImport + } + '/editing-b': { + id: '/editing-b' + path: '/editing-b' + fullPath: '/editing-b' + preLoaderRoute: typeof EditingBRouteImport parentRoute: typeof rootRouteImport } '/fullpath-test': { @@ -1633,102 +1624,81 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof FullpathTestRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/history-blocking': { + id: '/history-blocking' + path: '/history-blocking' + fullPath: '/history-blocking' + preLoaderRoute: typeof HistoryBlockingRouteImport parentRoute: typeof rootRouteImport } - '/search-params/': { - id: '/search-params/' - path: '/' - fullPath: '/search-params/' - preLoaderRoute: typeof SearchParamsIndexRouteImport - parentRoute: typeof SearchParamsRouteRoute - } - '/relative/': { - id: '/relative/' - path: '/relative' - fullPath: '/relative/' - preLoaderRoute: typeof RelativeIndexRouteImport + '/hover-preload-hash': { + id: '/hover-preload-hash' + path: '/hover-preload-hash' + fullPath: '/hover-preload-hash' + preLoaderRoute: typeof HoverPreloadHashRouteImport parentRoute: typeof rootRouteImport } - '/redirect/': { - id: '/redirect/' - path: '/redirect' - fullPath: '/redirect/' - preLoaderRoute: typeof RedirectIndexRouteImport + '/lazy-error': { + id: '/lazy-error' + path: '/lazy-error' + fullPath: '/lazy-error' + preLoaderRoute: typeof LazyErrorRouteImport parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/params-ps/': { - id: '/params-ps/' - path: '/params-ps' - fullPath: '/params-ps/' - preLoaderRoute: typeof ParamsPsIndexRouteImport + '/masks': { + id: '/masks' + path: '/masks' + fullPath: '/masks' + preLoaderRoute: typeof MasksRouteImport parentRoute: typeof rootRouteImport } - '/structural-sharing/$enabled': { - id: '/structural-sharing/$enabled' - path: '/structural-sharing/$enabled' - fullPath: '/structural-sharing/$enabled' - preLoaderRoute: typeof StructuralSharingEnabledRouteImport + '/non-nested': { + id: '/non-nested' + path: '/non-nested' + fullPath: '/non-nested' + preLoaderRoute: typeof NonNestedRouteRouteImport parentRoute: typeof rootRouteImport } - '/search-params/default': { - id: '/search-params/default' - path: '/default' - fullPath: '/search-params/default' - preLoaderRoute: typeof SearchParamsDefaultRouteImport - parentRoute: typeof SearchParamsRouteRoute - } - '/redirect/$target': { - id: '/redirect/$target' - path: '/redirect/$target' - fullPath: '/redirect/$target' - preLoaderRoute: typeof RedirectTargetRouteImport + '/notRemountDeps': { + id: '/notRemountDeps' + path: '/notRemountDeps' + fullPath: '/notRemountDeps' + preLoaderRoute: typeof NotRemountDepsRouteImport parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute - } - '/(group)/lazyinside': { - id: '/(group)/lazyinside' - path: '/lazyinside' - fullPath: '/lazyinside' - preLoaderRoute: typeof groupLazyinsideRouteImport + '/pathless-layout': { + id: '/pathless-layout' + path: '/pathless-layout' + fullPath: '/pathless-layout' + preLoaderRoute: typeof PathlessLayoutRouteRouteImport parentRoute: typeof rootRouteImport } - '/(group)/inside': { - id: '/(group)/inside' - path: '/inside' - fullPath: '/inside' - preLoaderRoute: typeof groupInsideRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/(group)/_layout': { - id: '/(group)/_layout' - path: '' - fullPath: '' - preLoaderRoute: typeof groupLayoutRouteImport + '/remountDeps': { + id: '/remountDeps' + path: '/remountDeps' + fullPath: '/remountDeps' + preLoaderRoute: typeof RemountDepsRouteImport + parentRoute: typeof rootRouteImport + } + '/search-params': { + id: '/search-params' + path: '/search-params' + fullPath: '/search-params' + preLoaderRoute: typeof SearchParamsRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/대한민국': { + id: '/대한민국' + path: '/대한민국' + fullPath: '/대한민국' + preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteRouteImport parentRoute: typeof rootRouteImport } '/(another-group)/onlyrouteinside': { @@ -1738,60 +1708,46 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport parentRoute: typeof rootRouteImport } - '/relative/useNavigate': { - id: '/relative/useNavigate' - path: '/relative/useNavigate' - fullPath: '/relative/useNavigate' - preLoaderRoute: typeof RelativeUseNavigateRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/relative/link': { - id: '/relative/link' - path: '/relative/link' - fullPath: '/relative/link' - preLoaderRoute: typeof RelativeLinkRouteRouteImport - parentRoute: typeof rootRouteImport - } - '/pathless-layout/_layout': { - id: '/pathless-layout/_layout' + '/(group)/_layout': { + id: '/(group)/_layout' path: '' - fullPath: '/pathless-layout' - preLoaderRoute: typeof PathlessLayoutLayoutRouteRouteImport - parentRoute: typeof PathlessLayoutRouteRoute - } - '/params-ps/strict-false': { - id: '/params-ps/strict-false' - path: '/params-ps/strict-false' - fullPath: '/params-ps/strict-false' - preLoaderRoute: typeof ParamsPsStrictFalseRouteRouteImport + fullPath: '/' + preLoaderRoute: typeof groupLayoutRouteImport parentRoute: typeof rootRouteImport } - '/params-ps/non-nested': { - id: '/params-ps/non-nested' - path: '/params-ps/non-nested' - fullPath: '/params-ps/non-nested' - preLoaderRoute: typeof ParamsPsNonNestedRouteRouteImport + '/(group)/inside': { + id: '/(group)/inside' + path: '/inside' + fullPath: '/inside' + preLoaderRoute: typeof groupInsideRouteImport parentRoute: typeof rootRouteImport } - '/non-nested/suffix': { - id: '/non-nested/suffix' - path: '/suffix' - fullPath: '/non-nested/suffix' - preLoaderRoute: typeof NonNestedSuffixRouteRouteImport - parentRoute: typeof NonNestedRouteRoute + '/(group)/lazyinside': { + id: '/(group)/lazyinside' + path: '/lazyinside' + fullPath: '/lazyinside' + preLoaderRoute: typeof groupLazyinsideRouteImport + parentRoute: typeof rootRouteImport } - '/non-nested/prefix': { - id: '/non-nested/prefix' - path: '/prefix' - fullPath: '/non-nested/prefix' - preLoaderRoute: typeof NonNestedPrefixRouteRouteImport - parentRoute: typeof NonNestedRouteRoute + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute } - '/non-nested/path': { - id: '/non-nested/path' - path: '/path' - fullPath: '/non-nested/path' - preLoaderRoute: typeof NonNestedPathRouteRouteImport + '/fullpath-test/_layout': { + id: '/fullpath-test/_layout' + path: '' + fullPath: '/fullpath-test' + preLoaderRoute: typeof FullpathTestLayoutRouteRouteImport + parentRoute: typeof FullpathTestRouteRoute + } + '/non-nested/deep': { + id: '/non-nested/deep' + path: '/deep' + fullPath: '/non-nested/deep' + preLoaderRoute: typeof NonNestedDeepRouteRouteImport parentRoute: typeof NonNestedRouteRoute } '/non-nested/named': { @@ -1801,277 +1757,123 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof NonNestedNamedRouteRouteImport parentRoute: typeof NonNestedRouteRoute } - '/non-nested/deep': { - id: '/non-nested/deep' - path: '/deep' - fullPath: '/non-nested/deep' - preLoaderRoute: typeof NonNestedDeepRouteRouteImport + '/non-nested/path': { + id: '/non-nested/path' + path: '/path' + fullPath: '/non-nested/path' + preLoaderRoute: typeof NonNestedPathRouteRouteImport parentRoute: typeof NonNestedRouteRoute } - '/fullpath-test/_layout': { - id: '/fullpath-test/_layout' + '/non-nested/prefix': { + id: '/non-nested/prefix' + path: '/prefix' + fullPath: '/non-nested/prefix' + preLoaderRoute: typeof NonNestedPrefixRouteRouteImport + parentRoute: typeof NonNestedRouteRoute + } + '/non-nested/suffix': { + id: '/non-nested/suffix' + path: '/suffix' + fullPath: '/non-nested/suffix' + preLoaderRoute: typeof NonNestedSuffixRouteRouteImport + parentRoute: typeof NonNestedRouteRoute + } + '/params-ps/': { + id: '/params-ps/' + path: '/params-ps' + fullPath: '/params-ps/' + preLoaderRoute: typeof ParamsPsIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/params-ps/non-nested': { + id: '/params-ps/non-nested' + path: '/params-ps/non-nested' + fullPath: '/params-ps/non-nested' + preLoaderRoute: typeof ParamsPsNonNestedRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/params-ps/strict-false': { + id: '/params-ps/strict-false' + path: '/params-ps/strict-false' + fullPath: '/params-ps/strict-false' + preLoaderRoute: typeof ParamsPsStrictFalseRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/pathless-layout/_layout': { + id: '/pathless-layout/_layout' path: '' - fullPath: '/fullpath-test' - preLoaderRoute: typeof FullpathTestLayoutRouteRouteImport - parentRoute: typeof FullpathTestRouteRoute + fullPath: '/pathless-layout' + preLoaderRoute: typeof PathlessLayoutLayoutRouteRouteImport + parentRoute: typeof PathlessLayoutRouteRoute } - '/redirect/$target/': { - id: '/redirect/$target/' + '/posts/': { + id: '/posts/' path: '/' - fullPath: '/redirect/$target/' - preLoaderRoute: typeof RedirectTargetIndexRouteImport - parentRoute: typeof RedirectTargetRoute + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute } - '/pathless-layout/_layout/': { - id: '/pathless-layout/_layout/' + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/redirect/': { + id: '/redirect/' + path: '/redirect' + fullPath: '/redirect/' + preLoaderRoute: typeof RedirectIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect/$target': { + id: '/redirect/$target' + path: '/redirect/$target' + fullPath: '/redirect/$target' + preLoaderRoute: typeof RedirectTargetRouteImport + parentRoute: typeof rootRouteImport + } + '/relative/': { + id: '/relative/' + path: '/relative' + fullPath: '/relative/' + preLoaderRoute: typeof RelativeIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/relative/link': { + id: '/relative/link' + path: '/relative/link' + fullPath: '/relative/link' + preLoaderRoute: typeof RelativeLinkRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/relative/useNavigate': { + id: '/relative/useNavigate' + path: '/relative/useNavigate' + fullPath: '/relative/useNavigate' + preLoaderRoute: typeof RelativeUseNavigateRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/search-params/': { + id: '/search-params/' path: '/' - fullPath: '/pathless-layout/' - preLoaderRoute: typeof PathlessLayoutLayoutIndexRouteImport - parentRoute: typeof PathlessLayoutLayoutRouteRoute + fullPath: '/search-params/' + preLoaderRoute: typeof SearchParamsIndexRouteImport + parentRoute: typeof SearchParamsRouteRoute } - '/params-ps/wildcard/': { - id: '/params-ps/wildcard/' - path: '/params-ps/wildcard' - fullPath: '/params-ps/wildcard/' - preLoaderRoute: typeof ParamsPsWildcardIndexRouteImport - parentRoute: typeof rootRouteImport + '/search-params/default': { + id: '/search-params/default' + path: '/default' + fullPath: '/search-params/default' + preLoaderRoute: typeof SearchParamsDefaultRouteImport + parentRoute: typeof SearchParamsRouteRoute } - '/params-ps/named/': { - id: '/params-ps/named/' - path: '/params-ps/named' - fullPath: '/params-ps/named/' - preLoaderRoute: typeof ParamsPsNamedIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/fullpath-test/_layout/': { - id: '/fullpath-test/_layout/' - path: '/' - fullPath: '/fullpath-test/' - preLoaderRoute: typeof FullpathTestLayoutIndexRouteImport - parentRoute: typeof FullpathTestLayoutRouteRoute - } - '/대한민국/🚀/$id': { - id: '/대한민국/🚀/$id' - path: '/🚀/$id' - fullPath: '/대한민국/🚀/$id' - preLoaderRoute: typeof Char45824Char54620Char48124Char44397Char55357Char56960IdRouteImport - parentRoute: typeof Char45824Char54620Char48124Char44397RouteRoute - } - '/대한민국/wildcard/$': { - id: '/대한민국/wildcard/$' - path: '/wildcard/$' - fullPath: '/대한민국/wildcard/$' - preLoaderRoute: typeof Char45824Char54620Char48124Char44397WildcardSplatRouteImport - parentRoute: typeof Char45824Char54620Char48124Char44397RouteRoute - } - '/relative/useNavigate/relative-useNavigate-b': { - id: '/relative/useNavigate/relative-useNavigate-b' - path: '/relative-useNavigate-b' - fullPath: '/relative/useNavigate/relative-useNavigate-b' - preLoaderRoute: typeof RelativeUseNavigateRelativeUseNavigateBRouteImport - parentRoute: typeof RelativeUseNavigateRouteRoute - } - '/relative/useNavigate/relative-useNavigate-a': { - id: '/relative/useNavigate/relative-useNavigate-a' - path: '/relative-useNavigate-a' - fullPath: '/relative/useNavigate/relative-useNavigate-a' - preLoaderRoute: typeof RelativeUseNavigateRelativeUseNavigateARouteImport - parentRoute: typeof RelativeUseNavigateRouteRoute - } - '/relative/link/relative-link-b': { - id: '/relative/link/relative-link-b' - path: '/relative-link-b' - fullPath: '/relative/link/relative-link-b' - preLoaderRoute: typeof RelativeLinkRelativeLinkBRouteImport - parentRoute: typeof RelativeLinkRouteRoute - } - '/relative/link/relative-link-a': { - id: '/relative/link/relative-link-a' - path: '/relative-link-a' - fullPath: '/relative/link/relative-link-a' - preLoaderRoute: typeof RelativeLinkRelativeLinkARouteImport - parentRoute: typeof RelativeLinkRouteRoute - } - '/redirect/preload/third': { - id: '/redirect/preload/third' - path: '/redirect/preload/third' - fullPath: '/redirect/preload/third' - preLoaderRoute: typeof RedirectPreloadThirdRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect/preload/second': { - id: '/redirect/preload/second' - path: '/redirect/preload/second' - fullPath: '/redirect/preload/second' - preLoaderRoute: typeof RedirectPreloadSecondRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect/preload/first': { - id: '/redirect/preload/first' - path: '/redirect/preload/first' - fullPath: '/redirect/preload/first' - preLoaderRoute: typeof RedirectPreloadFirstRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect/$target/via-routeApi-redirect-loader': { - id: '/redirect/$target/via-routeApi-redirect-loader' - path: '/via-routeApi-redirect-loader' - fullPath: '/redirect/$target/via-routeApi-redirect-loader' - preLoaderRoute: typeof RedirectTargetViaRouteApiRedirectLoaderRouteImport - parentRoute: typeof RedirectTargetRoute - } - '/redirect/$target/via-routeApi-redirect-beforeLoad': { - id: '/redirect/$target/via-routeApi-redirect-beforeLoad' - path: '/via-routeApi-redirect-beforeLoad' - fullPath: '/redirect/$target/via-routeApi-redirect-beforeLoad' - preLoaderRoute: typeof RedirectTargetViaRouteApiRedirectBeforeLoadRouteImport - parentRoute: typeof RedirectTargetRoute - } - '/redirect/$target/via-route-redirect-loader': { - id: '/redirect/$target/via-route-redirect-loader' - path: '/via-route-redirect-loader' - fullPath: '/redirect/$target/via-route-redirect-loader' - preLoaderRoute: typeof RedirectTargetViaRouteRedirectLoaderRouteImport - parentRoute: typeof RedirectTargetRoute - } - '/redirect/$target/via-route-redirect-beforeLoad': { - id: '/redirect/$target/via-route-redirect-beforeLoad' - path: '/via-route-redirect-beforeLoad' - fullPath: '/redirect/$target/via-route-redirect-beforeLoad' - preLoaderRoute: typeof RedirectTargetViaRouteRedirectBeforeLoadRouteImport - parentRoute: typeof RedirectTargetRoute - } - '/redirect/$target/via-loader': { - id: '/redirect/$target/via-loader' - path: '/via-loader' - fullPath: '/redirect/$target/via-loader' - preLoaderRoute: typeof RedirectTargetViaLoaderRouteImport - parentRoute: typeof RedirectTargetRoute - } - '/redirect/$target/via-beforeLoad': { - id: '/redirect/$target/via-beforeLoad' - path: '/via-beforeLoad' - fullPath: '/redirect/$target/via-beforeLoad' - preLoaderRoute: typeof RedirectTargetViaBeforeLoadRouteImport - parentRoute: typeof RedirectTargetRoute - } - '/redirect/$target/destination': { - id: '/redirect/$target/destination' - path: '/destination' - fullPath: '/redirect/$target/destination' - preLoaderRoute: typeof RedirectTargetDestinationRouteImport - parentRoute: typeof RedirectTargetRoute - } - '/posts_/$postId/edit': { - id: '/posts_/$postId/edit' - path: '/posts/$postId/edit' - fullPath: '/posts/$postId/edit' - preLoaderRoute: typeof PostsPostIdEditRouteImport - parentRoute: typeof rootRouteImport - } - '/pathless-layout/_layout/child': { - id: '/pathless-layout/_layout/child' - path: '/child' - fullPath: '/pathless-layout/child' - preLoaderRoute: typeof PathlessLayoutLayoutChildRouteImport - parentRoute: typeof PathlessLayoutLayoutRouteRoute - } - '/params/single/$value': { - id: '/params/single/$value' - path: '/params/single/$value' - fullPath: '/params/single/$value' - preLoaderRoute: typeof ParamsSingleValueRouteImport - parentRoute: typeof rootRouteImport - } - '/params-ps/wildcard/{$}suffix@대': { - id: '/params-ps/wildcard/{$}suffix@대' - path: '/params-ps/wildcard/{$}suffix@대' - fullPath: '/params-ps/wildcard/{$}suffix@대' - preLoaderRoute: typeof ParamsPsWildcardChar123Char125suffixAtChar45824RouteImport - parentRoute: typeof rootRouteImport - } - '/params-ps/wildcard/{$}suffix': { - id: '/params-ps/wildcard/{$}suffix' - path: '/params-ps/wildcard/{$}suffix' - fullPath: '/params-ps/wildcard/{$}suffix' - preLoaderRoute: typeof ParamsPsWildcardChar123Char125suffixRouteImport - parentRoute: typeof rootRouteImport - } - '/params-ps/wildcard/prefix{$}': { - id: '/params-ps/wildcard/prefix{$}' - path: '/params-ps/wildcard/prefix{$}' - fullPath: '/params-ps/wildcard/prefix{$}' - preLoaderRoute: typeof ParamsPsWildcardPrefixChar123Char125RouteImport - parentRoute: typeof rootRouteImport - } - '/params-ps/wildcard/prefix@대{$}': { - id: '/params-ps/wildcard/prefix@대{$}' - path: '/params-ps/wildcard/prefix@대{$}' - fullPath: '/params-ps/wildcard/prefix@대{$}' - preLoaderRoute: typeof ParamsPsWildcardPrefixAtChar45824Char123Char125RouteImport - parentRoute: typeof rootRouteImport - } - '/params-ps/wildcard/$': { - id: '/params-ps/wildcard/$' - path: '/params-ps/wildcard/$' - fullPath: '/params-ps/wildcard/$' - preLoaderRoute: typeof ParamsPsWildcardSplatRouteImport - parentRoute: typeof rootRouteImport - } - '/params-ps/named/{$foo}suffix': { - id: '/params-ps/named/{$foo}suffix' - path: '/params-ps/named/{$foo}suffix' - fullPath: '/params-ps/named/{$foo}suffix' - preLoaderRoute: typeof ParamsPsNamedChar123fooChar125suffixRouteImport - parentRoute: typeof rootRouteImport - } - '/params-ps/named/prefix{$foo}': { - id: '/params-ps/named/prefix{$foo}' - path: '/params-ps/named/prefix{$foo}' - fullPath: '/params-ps/named/prefix{$foo}' - preLoaderRoute: typeof ParamsPsNamedPrefixChar123fooChar125RouteImport - parentRoute: typeof rootRouteImport - } - '/masks/public/$username': { - id: '/masks/public/$username' - path: '/public/$username' - fullPath: '/masks/public/$username' - preLoaderRoute: typeof MasksPublicUsernameRouteImport - parentRoute: typeof MasksRoute - } - '/masks/admin/$userId': { - id: '/masks/admin/$userId' - path: '/admin/$userId' - fullPath: '/masks/admin/$userId' - preLoaderRoute: typeof MasksAdminUserIdRouteImport - parentRoute: typeof MasksRoute - } - '/fullpath-test/_layout/$id': { - id: '/fullpath-test/_layout/$id' - path: '/$id' - fullPath: '/fullpath-test/$id' - preLoaderRoute: typeof FullpathTestLayoutIdRouteImport - parentRoute: typeof FullpathTestLayoutRouteRoute - } - '/_layout/_layout-2/layout-b': { - id: '/_layout/_layout-2/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport - parentRoute: typeof LayoutLayout2Route - } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route - } - '/(group)/subfolder/inside': { - id: '/(group)/subfolder/inside' - path: '/subfolder/inside' - fullPath: '/subfolder/inside' - preLoaderRoute: typeof groupSubfolderInsideRouteImport + '/structural-sharing/$enabled': { + id: '/structural-sharing/$enabled' + path: '/structural-sharing/$enabled' + fullPath: '/structural-sharing/$enabled' + preLoaderRoute: typeof StructuralSharingEnabledRouteImport parentRoute: typeof rootRouteImport } '/(group)/_layout/insidelayout': { @@ -2081,54 +1883,54 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport parentRoute: typeof groupLayoutRoute } - '/params-ps/strict-false/$version': { - id: '/params-ps/strict-false/$version' - path: '/$version' - fullPath: '/params-ps/strict-false/$version' - preLoaderRoute: typeof ParamsPsStrictFalseVersionRouteRouteImport - parentRoute: typeof ParamsPsStrictFalseRouteRoute - } - '/params-ps/non-nested/$foo_': { - id: '/params-ps/non-nested/$foo_' - path: '/$foo' - fullPath: '/params-ps/non-nested/$foo' - preLoaderRoute: typeof ParamsPsNonNestedFooRouteRouteImport - parentRoute: typeof ParamsPsNonNestedRouteRoute - } - '/params-ps/named/$foo': { - id: '/params-ps/named/$foo' - path: '/params-ps/named/$foo' - fullPath: '/params-ps/named/$foo' - preLoaderRoute: typeof ParamsPsNamedFooRouteRouteImport + '/(group)/subfolder/inside': { + id: '/(group)/subfolder/inside' + path: '/subfolder/inside' + fullPath: '/subfolder/inside' + preLoaderRoute: typeof groupSubfolderInsideRouteImport parentRoute: typeof rootRouteImport } - '/non-nested/suffix/{$baz}suffix': { - id: '/non-nested/suffix/{$baz}suffix' - path: '/{$baz}suffix' - fullPath: '/non-nested/suffix/{$baz}suffix' - preLoaderRoute: typeof NonNestedSuffixChar123bazChar125suffixRouteRouteImport - parentRoute: typeof NonNestedSuffixRouteRoute + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route } - '/non-nested/prefix/prefix{$baz}': { - id: '/non-nested/prefix/prefix{$baz}' - path: '/prefix{$baz}' - fullPath: '/non-nested/prefix/prefix{$baz}' - preLoaderRoute: typeof NonNestedPrefixPrefixChar123bazChar125RouteRouteImport - parentRoute: typeof NonNestedPrefixRouteRoute + '/_layout/_layout-2/layout-b': { + id: '/_layout/_layout-2/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport + parentRoute: typeof LayoutLayout2Route } - '/non-nested/path/baz': { - id: '/non-nested/path/baz' - path: '/baz' - fullPath: '/non-nested/path/baz' - preLoaderRoute: typeof NonNestedPathBazRouteRouteImport - parentRoute: typeof NonNestedPathRouteRoute + '/fullpath-test/_layout/': { + id: '/fullpath-test/_layout/' + path: '/' + fullPath: '/fullpath-test/' + preLoaderRoute: typeof FullpathTestLayoutIndexRouteImport + parentRoute: typeof FullpathTestLayoutRouteRoute } - '/non-nested/named/$baz': { - id: '/non-nested/named/$baz' - path: '/$baz' - fullPath: '/non-nested/named/$baz' - preLoaderRoute: typeof NonNestedNamedBazRouteRouteImport - parentRoute: typeof NonNestedNamedRouteRoute + '/fullpath-test/_layout/$id': { + id: '/fullpath-test/_layout/$id' + path: '/$id' + fullPath: '/fullpath-test/$id' + preLoaderRoute: typeof FullpathTestLayoutIdRouteImport + parentRoute: typeof FullpathTestLayoutRouteRoute + } + '/masks/admin/$userId': { + id: '/masks/admin/$userId' + path: '/admin/$userId' + fullPath: '/masks/admin/$userId' + preLoaderRoute: typeof MasksAdminUserIdRouteImport + parentRoute: typeof MasksRoute + } + '/masks/public/$username': { + id: '/masks/public/$username' + path: '/public/$username' + fullPath: '/masks/public/$username' + preLoaderRoute: typeof MasksPublicUsernameRouteImport + parentRoute: typeof MasksRoute } '/non-nested/deep/$baz': { id: '/non-nested/deep/$baz' @@ -2137,32 +1939,382 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof NonNestedDeepBazRouteRouteImport parentRoute: typeof NonNestedDeepRouteRoute } - '/relative/useNavigate/with-search/': { - id: '/relative/useNavigate/with-search/' - path: '/with-search' - fullPath: '/relative/useNavigate/with-search/' - preLoaderRoute: typeof RelativeUseNavigateWithSearchIndexRouteImport + '/non-nested/named/$baz': { + id: '/non-nested/named/$baz' + path: '/$baz' + fullPath: '/non-nested/named/$baz' + preLoaderRoute: typeof NonNestedNamedBazRouteRouteImport + parentRoute: typeof NonNestedNamedRouteRoute + } + '/non-nested/path/baz': { + id: '/non-nested/path/baz' + path: '/baz' + fullPath: '/non-nested/path/baz' + preLoaderRoute: typeof NonNestedPathBazRouteRouteImport + parentRoute: typeof NonNestedPathRouteRoute + } + '/non-nested/prefix/prefix{$baz}': { + id: '/non-nested/prefix/prefix{$baz}' + path: '/prefix{$baz}' + fullPath: '/non-nested/prefix/prefix{$baz}' + preLoaderRoute: typeof NonNestedPrefixPrefixChar123bazChar125RouteRouteImport + parentRoute: typeof NonNestedPrefixRouteRoute + } + '/non-nested/suffix/{$baz}suffix': { + id: '/non-nested/suffix/{$baz}suffix' + path: '/{$baz}suffix' + fullPath: '/non-nested/suffix/{$baz}suffix' + preLoaderRoute: typeof NonNestedSuffixChar123bazChar125suffixRouteRouteImport + parentRoute: typeof NonNestedSuffixRouteRoute + } + '/params-ps/named/': { + id: '/params-ps/named/' + path: '/params-ps/named' + fullPath: '/params-ps/named/' + preLoaderRoute: typeof ParamsPsNamedIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/params-ps/named/$foo': { + id: '/params-ps/named/$foo' + path: '/params-ps/named/$foo' + fullPath: '/params-ps/named/$foo' + preLoaderRoute: typeof ParamsPsNamedFooRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/params-ps/named/prefix{$foo}': { + id: '/params-ps/named/prefix{$foo}' + path: '/params-ps/named/prefix{$foo}' + fullPath: '/params-ps/named/prefix{$foo}' + preLoaderRoute: typeof ParamsPsNamedPrefixChar123fooChar125RouteImport + parentRoute: typeof rootRouteImport + } + '/params-ps/named/{$foo}suffix': { + id: '/params-ps/named/{$foo}suffix' + path: '/params-ps/named/{$foo}suffix' + fullPath: '/params-ps/named/{$foo}suffix' + preLoaderRoute: typeof ParamsPsNamedChar123fooChar125suffixRouteImport + parentRoute: typeof rootRouteImport + } + '/params-ps/non-nested/$foo_': { + id: '/params-ps/non-nested/$foo_' + path: '/$foo' + fullPath: '/params-ps/non-nested/$foo' + preLoaderRoute: typeof ParamsPsNonNestedFooRouteRouteImport + parentRoute: typeof ParamsPsNonNestedRouteRoute + } + '/params-ps/strict-false/$version': { + id: '/params-ps/strict-false/$version' + path: '/$version' + fullPath: '/params-ps/strict-false/$version' + preLoaderRoute: typeof ParamsPsStrictFalseVersionRouteRouteImport + parentRoute: typeof ParamsPsStrictFalseRouteRoute + } + '/params-ps/wildcard/': { + id: '/params-ps/wildcard/' + path: '/params-ps/wildcard' + fullPath: '/params-ps/wildcard/' + preLoaderRoute: typeof ParamsPsWildcardIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/params-ps/wildcard/$': { + id: '/params-ps/wildcard/$' + path: '/params-ps/wildcard/$' + fullPath: '/params-ps/wildcard/$' + preLoaderRoute: typeof ParamsPsWildcardSplatRouteImport + parentRoute: typeof rootRouteImport + } + '/params-ps/wildcard/prefix@대{$}': { + id: '/params-ps/wildcard/prefix@대{$}' + path: '/params-ps/wildcard/prefix@대{$}' + fullPath: '/params-ps/wildcard/prefix@대{$}' + preLoaderRoute: typeof ParamsPsWildcardPrefixAtChar45824Char123Char125RouteImport + parentRoute: typeof rootRouteImport + } + '/params-ps/wildcard/prefix{$}': { + id: '/params-ps/wildcard/prefix{$}' + path: '/params-ps/wildcard/prefix{$}' + fullPath: '/params-ps/wildcard/prefix{$}' + preLoaderRoute: typeof ParamsPsWildcardPrefixChar123Char125RouteImport + parentRoute: typeof rootRouteImport + } + '/params-ps/wildcard/{$}suffix': { + id: '/params-ps/wildcard/{$}suffix' + path: '/params-ps/wildcard/{$}suffix' + fullPath: '/params-ps/wildcard/{$}suffix' + preLoaderRoute: typeof ParamsPsWildcardChar123Char125suffixRouteImport + parentRoute: typeof rootRouteImport + } + '/params-ps/wildcard/{$}suffix@대': { + id: '/params-ps/wildcard/{$}suffix@대' + path: '/params-ps/wildcard/{$}suffix@대' + fullPath: '/params-ps/wildcard/{$}suffix@대' + preLoaderRoute: typeof ParamsPsWildcardChar123Char125suffixAtChar45824RouteImport + parentRoute: typeof rootRouteImport + } + '/params/single/$value': { + id: '/params/single/$value' + path: '/params/single/$value' + fullPath: '/params/single/$value' + preLoaderRoute: typeof ParamsSingleValueRouteImport + parentRoute: typeof rootRouteImport + } + '/pathless-layout/_layout/': { + id: '/pathless-layout/_layout/' + path: '/' + fullPath: '/pathless-layout/' + preLoaderRoute: typeof PathlessLayoutLayoutIndexRouteImport + parentRoute: typeof PathlessLayoutLayoutRouteRoute + } + '/pathless-layout/_layout/child': { + id: '/pathless-layout/_layout/child' + path: '/child' + fullPath: '/pathless-layout/child' + preLoaderRoute: typeof PathlessLayoutLayoutChildRouteImport + parentRoute: typeof PathlessLayoutLayoutRouteRoute + } + '/posts_/$postId/edit': { + id: '/posts_/$postId/edit' + path: '/posts/$postId/edit' + fullPath: '/posts/$postId/edit' + preLoaderRoute: typeof PostsPostIdEditRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect/$target/': { + id: '/redirect/$target/' + path: '/' + fullPath: '/redirect/$target/' + preLoaderRoute: typeof RedirectTargetIndexRouteImport + parentRoute: typeof RedirectTargetRoute + } + '/redirect/$target/destination': { + id: '/redirect/$target/destination' + path: '/destination' + fullPath: '/redirect/$target/destination' + preLoaderRoute: typeof RedirectTargetDestinationRouteImport + parentRoute: typeof RedirectTargetRoute + } + '/redirect/$target/via-beforeLoad': { + id: '/redirect/$target/via-beforeLoad' + path: '/via-beforeLoad' + fullPath: '/redirect/$target/via-beforeLoad' + preLoaderRoute: typeof RedirectTargetViaBeforeLoadRouteImport + parentRoute: typeof RedirectTargetRoute + } + '/redirect/$target/via-loader': { + id: '/redirect/$target/via-loader' + path: '/via-loader' + fullPath: '/redirect/$target/via-loader' + preLoaderRoute: typeof RedirectTargetViaLoaderRouteImport + parentRoute: typeof RedirectTargetRoute + } + '/redirect/$target/via-route-redirect-beforeLoad': { + id: '/redirect/$target/via-route-redirect-beforeLoad' + path: '/via-route-redirect-beforeLoad' + fullPath: '/redirect/$target/via-route-redirect-beforeLoad' + preLoaderRoute: typeof RedirectTargetViaRouteRedirectBeforeLoadRouteImport + parentRoute: typeof RedirectTargetRoute + } + '/redirect/$target/via-route-redirect-loader': { + id: '/redirect/$target/via-route-redirect-loader' + path: '/via-route-redirect-loader' + fullPath: '/redirect/$target/via-route-redirect-loader' + preLoaderRoute: typeof RedirectTargetViaRouteRedirectLoaderRouteImport + parentRoute: typeof RedirectTargetRoute + } + '/redirect/$target/via-routeApi-redirect-beforeLoad': { + id: '/redirect/$target/via-routeApi-redirect-beforeLoad' + path: '/via-routeApi-redirect-beforeLoad' + fullPath: '/redirect/$target/via-routeApi-redirect-beforeLoad' + preLoaderRoute: typeof RedirectTargetViaRouteApiRedirectBeforeLoadRouteImport + parentRoute: typeof RedirectTargetRoute + } + '/redirect/$target/via-routeApi-redirect-loader': { + id: '/redirect/$target/via-routeApi-redirect-loader' + path: '/via-routeApi-redirect-loader' + fullPath: '/redirect/$target/via-routeApi-redirect-loader' + preLoaderRoute: typeof RedirectTargetViaRouteApiRedirectLoaderRouteImport + parentRoute: typeof RedirectTargetRoute + } + '/redirect/preload/first': { + id: '/redirect/preload/first' + path: '/redirect/preload/first' + fullPath: '/redirect/preload/first' + preLoaderRoute: typeof RedirectPreloadFirstRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect/preload/second': { + id: '/redirect/preload/second' + path: '/redirect/preload/second' + fullPath: '/redirect/preload/second' + preLoaderRoute: typeof RedirectPreloadSecondRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect/preload/third': { + id: '/redirect/preload/third' + path: '/redirect/preload/third' + fullPath: '/redirect/preload/third' + preLoaderRoute: typeof RedirectPreloadThirdRouteImport + parentRoute: typeof rootRouteImport + } + '/relative/link/relative-link-a': { + id: '/relative/link/relative-link-a' + path: '/relative-link-a' + fullPath: '/relative/link/relative-link-a' + preLoaderRoute: typeof RelativeLinkRelativeLinkARouteImport + parentRoute: typeof RelativeLinkRouteRoute + } + '/relative/link/relative-link-b': { + id: '/relative/link/relative-link-b' + path: '/relative-link-b' + fullPath: '/relative/link/relative-link-b' + preLoaderRoute: typeof RelativeLinkRelativeLinkBRouteImport + parentRoute: typeof RelativeLinkRouteRoute + } + '/relative/useNavigate/relative-useNavigate-a': { + id: '/relative/useNavigate/relative-useNavigate-a' + path: '/relative-useNavigate-a' + fullPath: '/relative/useNavigate/relative-useNavigate-a' + preLoaderRoute: typeof RelativeUseNavigateRelativeUseNavigateARouteImport parentRoute: typeof RelativeUseNavigateRouteRoute } - '/relative/useNavigate/path/': { - id: '/relative/useNavigate/path/' - path: '/path' - fullPath: '/relative/useNavigate/path/' - preLoaderRoute: typeof RelativeUseNavigatePathIndexRouteImport + '/relative/useNavigate/relative-useNavigate-b': { + id: '/relative/useNavigate/relative-useNavigate-b' + path: '/relative-useNavigate-b' + fullPath: '/relative/useNavigate/relative-useNavigate-b' + preLoaderRoute: typeof RelativeUseNavigateRelativeUseNavigateBRouteImport parentRoute: typeof RelativeUseNavigateRouteRoute } - '/relative/useNavigate/nested/': { - id: '/relative/useNavigate/nested/' + '/대한민국/wildcard/$': { + id: '/대한민국/wildcard/$' + path: '/wildcard/$' + fullPath: '/대한민국/wildcard/$' + preLoaderRoute: typeof Char45824Char54620Char48124Char44397WildcardSplatRouteImport + parentRoute: typeof Char45824Char54620Char48124Char44397RouteRoute + } + '/대한민국/🚀/$id': { + id: '/대한민국/🚀/$id' + path: '/🚀/$id' + fullPath: '/대한민국/🚀/$id' + preLoaderRoute: typeof Char45824Char54620Char48124Char44397Char55357Char56960IdRouteImport + parentRoute: typeof Char45824Char54620Char48124Char44397RouteRoute + } + '/non-nested/deep/$baz/': { + id: '/non-nested/deep/$baz/' + path: '/' + fullPath: '/non-nested/deep/$baz/' + preLoaderRoute: typeof NonNestedDeepBazIndexRouteImport + parentRoute: typeof NonNestedDeepBazRouteRoute + } + '/non-nested/deep/$baz_/bar': { + id: '/non-nested/deep/$baz_/bar' + path: '/$baz/bar' + fullPath: '/non-nested/deep/$baz/bar' + preLoaderRoute: typeof NonNestedDeepBazBarRouteRouteImport + parentRoute: typeof NonNestedDeepRouteRoute + } + '/non-nested/named/$baz/': { + id: '/non-nested/named/$baz/' + path: '/' + fullPath: '/non-nested/named/$baz/' + preLoaderRoute: typeof NonNestedNamedBazIndexRouteImport + parentRoute: typeof NonNestedNamedBazRouteRoute + } + '/non-nested/named/$baz/foo': { + id: '/non-nested/named/$baz/foo' + path: '/foo' + fullPath: '/non-nested/named/$baz/foo' + preLoaderRoute: typeof NonNestedNamedBazFooRouteImport + parentRoute: typeof NonNestedNamedBazRouteRoute + } + '/non-nested/named/$baz_/bar': { + id: '/non-nested/named/$baz_/bar' + path: '/$baz/bar' + fullPath: '/non-nested/named/$baz/bar' + preLoaderRoute: typeof NonNestedNamedBazBarRouteImport + parentRoute: typeof NonNestedNamedRouteRoute + } + '/non-nested/path/baz/': { + id: '/non-nested/path/baz/' + path: '/' + fullPath: '/non-nested/path/baz/' + preLoaderRoute: typeof NonNestedPathBazIndexRouteImport + parentRoute: typeof NonNestedPathBazRouteRoute + } + '/non-nested/path/baz/foo': { + id: '/non-nested/path/baz/foo' + path: '/foo' + fullPath: '/non-nested/path/baz/foo' + preLoaderRoute: typeof NonNestedPathBazFooRouteImport + parentRoute: typeof NonNestedPathBazRouteRoute + } + '/non-nested/path/baz_/bar': { + id: '/non-nested/path/baz_/bar' + path: '/baz/bar' + fullPath: '/non-nested/path/baz/bar' + preLoaderRoute: typeof NonNestedPathBazBarRouteImport + parentRoute: typeof NonNestedPathRouteRoute + } + '/non-nested/prefix/prefix{$baz}/': { + id: '/non-nested/prefix/prefix{$baz}/' + path: '/' + fullPath: '/non-nested/prefix/prefix{$baz}/' + preLoaderRoute: typeof NonNestedPrefixPrefixChar123bazChar125IndexRouteImport + parentRoute: typeof NonNestedPrefixPrefixChar123bazChar125RouteRoute + } + '/non-nested/prefix/prefix{$baz}/foo': { + id: '/non-nested/prefix/prefix{$baz}/foo' + path: '/foo' + fullPath: '/non-nested/prefix/prefix{$baz}/foo' + preLoaderRoute: typeof NonNestedPrefixPrefixChar123bazChar125FooRouteImport + parentRoute: typeof NonNestedPrefixPrefixChar123bazChar125RouteRoute + } + '/non-nested/prefix/prefix{$baz}_/bar': { + id: '/non-nested/prefix/prefix{$baz}_/bar' + path: '/prefix{$baz}/bar' + fullPath: '/non-nested/prefix/prefix{$baz}/bar' + preLoaderRoute: typeof NonNestedPrefixPrefixChar123bazChar125BarRouteImport + parentRoute: typeof NonNestedPrefixRouteRoute + } + '/non-nested/suffix/{$baz}suffix/': { + id: '/non-nested/suffix/{$baz}suffix/' + path: '/' + fullPath: '/non-nested/suffix/{$baz}suffix/' + preLoaderRoute: typeof NonNestedSuffixChar123bazChar125suffixIndexRouteImport + parentRoute: typeof NonNestedSuffixChar123bazChar125suffixRouteRoute + } + '/non-nested/suffix/{$baz}suffix/foo': { + id: '/non-nested/suffix/{$baz}suffix/foo' + path: '/foo' + fullPath: '/non-nested/suffix/{$baz}suffix/foo' + preLoaderRoute: typeof NonNestedSuffixChar123bazChar125suffixFooRouteImport + parentRoute: typeof NonNestedSuffixChar123bazChar125suffixRouteRoute + } + '/non-nested/suffix/{$baz}suffix_/bar': { + id: '/non-nested/suffix/{$baz}suffix_/bar' + path: '/{$baz}suffix/bar' + fullPath: '/non-nested/suffix/{$baz}suffix/bar' + preLoaderRoute: typeof NonNestedSuffixChar123bazChar125suffixBarRouteImport + parentRoute: typeof NonNestedSuffixRouteRoute + } + '/params-ps/named/$foo/$bar': { + id: '/params-ps/named/$foo/$bar' + path: '/$bar' + fullPath: '/params-ps/named/$foo/$bar' + preLoaderRoute: typeof ParamsPsNamedFooBarRouteRouteImport + parentRoute: typeof ParamsPsNamedFooRouteRoute + } + '/params-ps/non-nested/$foo_/$bar': { + id: '/params-ps/non-nested/$foo_/$bar' + path: '/$bar' + fullPath: '/params-ps/non-nested/$foo/$bar' + preLoaderRoute: typeof ParamsPsNonNestedFooBarRouteImport + parentRoute: typeof ParamsPsNonNestedFooRouteRoute + } + '/relative/link/nested/': { + id: '/relative/link/nested/' path: '/nested' - fullPath: '/relative/useNavigate/nested/' - preLoaderRoute: typeof RelativeUseNavigateNestedIndexRouteImport - parentRoute: typeof RelativeUseNavigateRouteRoute - } - '/relative/link/with-search/': { - id: '/relative/link/with-search/' - path: '/with-search' - fullPath: '/relative/link/with-search/' - preLoaderRoute: typeof RelativeLinkWithSearchIndexRouteImport + fullPath: '/relative/link/nested/' + preLoaderRoute: typeof RelativeLinkNestedIndexRouteImport parentRoute: typeof RelativeLinkRouteRoute } '/relative/link/path/': { @@ -2172,152 +2324,33 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof RelativeLinkPathIndexRouteImport parentRoute: typeof RelativeLinkRouteRoute } - '/relative/link/nested/': { - id: '/relative/link/nested/' + '/relative/link/with-search/': { + id: '/relative/link/with-search/' + path: '/with-search' + fullPath: '/relative/link/with-search/' + preLoaderRoute: typeof RelativeLinkWithSearchIndexRouteImport + parentRoute: typeof RelativeLinkRouteRoute + } + '/relative/useNavigate/nested/': { + id: '/relative/useNavigate/nested/' path: '/nested' - fullPath: '/relative/link/nested/' - preLoaderRoute: typeof RelativeLinkNestedIndexRouteImport - parentRoute: typeof RelativeLinkRouteRoute - } - '/non-nested/suffix/{$baz}suffix/': { - id: '/non-nested/suffix/{$baz}suffix/' - path: '/' - fullPath: '/non-nested/suffix/{$baz}suffix/' - preLoaderRoute: typeof NonNestedSuffixChar123bazChar125suffixIndexRouteImport - parentRoute: typeof NonNestedSuffixChar123bazChar125suffixRouteRoute - } - '/non-nested/prefix/prefix{$baz}/': { - id: '/non-nested/prefix/prefix{$baz}/' - path: '/' - fullPath: '/non-nested/prefix/prefix{$baz}/' - preLoaderRoute: typeof NonNestedPrefixPrefixChar123bazChar125IndexRouteImport - parentRoute: typeof NonNestedPrefixPrefixChar123bazChar125RouteRoute - } - '/non-nested/path/baz/': { - id: '/non-nested/path/baz/' - path: '/' - fullPath: '/non-nested/path/baz/' - preLoaderRoute: typeof NonNestedPathBazIndexRouteImport - parentRoute: typeof NonNestedPathBazRouteRoute - } - '/non-nested/named/$baz/': { - id: '/non-nested/named/$baz/' - path: '/' - fullPath: '/non-nested/named/$baz/' - preLoaderRoute: typeof NonNestedNamedBazIndexRouteImport - parentRoute: typeof NonNestedNamedBazRouteRoute - } - '/non-nested/deep/$baz/': { - id: '/non-nested/deep/$baz/' - path: '/' - fullPath: '/non-nested/deep/$baz/' - preLoaderRoute: typeof NonNestedDeepBazIndexRouteImport - parentRoute: typeof NonNestedDeepBazRouteRoute - } - '/params-ps/non-nested/$foo_/$bar': { - id: '/params-ps/non-nested/$foo_/$bar' - path: '/$bar' - fullPath: '/params-ps/non-nested/$foo/$bar' - preLoaderRoute: typeof ParamsPsNonNestedFooBarRouteImport - parentRoute: typeof ParamsPsNonNestedFooRouteRoute - } - '/non-nested/suffix/{$baz}suffix_/bar': { - id: '/non-nested/suffix/{$baz}suffix_/bar' - path: '/{$baz}suffix/bar' - fullPath: '/non-nested/suffix/{$baz}suffix/bar' - preLoaderRoute: typeof NonNestedSuffixChar123bazChar125suffixBarRouteImport - parentRoute: typeof NonNestedSuffixRouteRoute - } - '/non-nested/suffix/{$baz}suffix/foo': { - id: '/non-nested/suffix/{$baz}suffix/foo' - path: '/foo' - fullPath: '/non-nested/suffix/{$baz}suffix/foo' - preLoaderRoute: typeof NonNestedSuffixChar123bazChar125suffixFooRouteImport - parentRoute: typeof NonNestedSuffixChar123bazChar125suffixRouteRoute - } - '/non-nested/prefix/prefix{$baz}_/bar': { - id: '/non-nested/prefix/prefix{$baz}_/bar' - path: '/prefix{$baz}/bar' - fullPath: '/non-nested/prefix/prefix{$baz}/bar' - preLoaderRoute: typeof NonNestedPrefixPrefixChar123bazChar125BarRouteImport - parentRoute: typeof NonNestedPrefixRouteRoute - } - '/non-nested/prefix/prefix{$baz}/foo': { - id: '/non-nested/prefix/prefix{$baz}/foo' - path: '/foo' - fullPath: '/non-nested/prefix/prefix{$baz}/foo' - preLoaderRoute: typeof NonNestedPrefixPrefixChar123bazChar125FooRouteImport - parentRoute: typeof NonNestedPrefixPrefixChar123bazChar125RouteRoute - } - '/non-nested/path/baz_/bar': { - id: '/non-nested/path/baz_/bar' - path: '/baz/bar' - fullPath: '/non-nested/path/baz/bar' - preLoaderRoute: typeof NonNestedPathBazBarRouteImport - parentRoute: typeof NonNestedPathRouteRoute - } - '/non-nested/path/baz/foo': { - id: '/non-nested/path/baz/foo' - path: '/foo' - fullPath: '/non-nested/path/baz/foo' - preLoaderRoute: typeof NonNestedPathBazFooRouteImport - parentRoute: typeof NonNestedPathBazRouteRoute - } - '/non-nested/named/$baz_/bar': { - id: '/non-nested/named/$baz_/bar' - path: '/$baz/bar' - fullPath: '/non-nested/named/$baz/bar' - preLoaderRoute: typeof NonNestedNamedBazBarRouteImport - parentRoute: typeof NonNestedNamedRouteRoute - } - '/non-nested/named/$baz/foo': { - id: '/non-nested/named/$baz/foo' - path: '/foo' - fullPath: '/non-nested/named/$baz/foo' - preLoaderRoute: typeof NonNestedNamedBazFooRouteImport - parentRoute: typeof NonNestedNamedBazRouteRoute - } - '/params-ps/named/$foo/$bar': { - id: '/params-ps/named/$foo/$bar' - path: '/$bar' - fullPath: '/params-ps/named/$foo/$bar' - preLoaderRoute: typeof ParamsPsNamedFooBarRouteRouteImport - parentRoute: typeof ParamsPsNamedFooRouteRoute - } - '/non-nested/deep/$baz_/bar': { - id: '/non-nested/deep/$baz_/bar' - path: '/$baz/bar' - fullPath: '/non-nested/deep/$baz/bar' - preLoaderRoute: typeof NonNestedDeepBazBarRouteRouteImport - parentRoute: typeof NonNestedDeepRouteRoute - } - '/relative/useNavigate/path/$path/': { - id: '/relative/useNavigate/path/$path/' - path: '/path/$path' - fullPath: '/relative/useNavigate/path/$path/' - preLoaderRoute: typeof RelativeUseNavigatePathPathIndexRouteImport + fullPath: '/relative/useNavigate/nested/' + preLoaderRoute: typeof RelativeUseNavigateNestedIndexRouteImport parentRoute: typeof RelativeUseNavigateRouteRoute } - '/relative/useNavigate/nested/deep/': { - id: '/relative/useNavigate/nested/deep/' - path: '/nested/deep' - fullPath: '/relative/useNavigate/nested/deep/' - preLoaderRoute: typeof RelativeUseNavigateNestedDeepIndexRouteImport + '/relative/useNavigate/path/': { + id: '/relative/useNavigate/path/' + path: '/path' + fullPath: '/relative/useNavigate/path/' + preLoaderRoute: typeof RelativeUseNavigatePathIndexRouteImport parentRoute: typeof RelativeUseNavigateRouteRoute } - '/relative/link/path/$path/': { - id: '/relative/link/path/$path/' - path: '/path/$path' - fullPath: '/relative/link/path/$path/' - preLoaderRoute: typeof RelativeLinkPathPathIndexRouteImport - parentRoute: typeof RelativeLinkRouteRoute - } - '/relative/link/nested/deep/': { - id: '/relative/link/nested/deep/' - path: '/nested/deep' - fullPath: '/relative/link/nested/deep/' - preLoaderRoute: typeof RelativeLinkNestedDeepIndexRouteImport - parentRoute: typeof RelativeLinkRouteRoute + '/relative/useNavigate/with-search/': { + id: '/relative/useNavigate/with-search/' + path: '/with-search' + fullPath: '/relative/useNavigate/with-search/' + preLoaderRoute: typeof RelativeUseNavigateWithSearchIndexRouteImport + parentRoute: typeof RelativeUseNavigateRouteRoute } '/non-nested/deep/$baz_/bar/': { id: '/non-nested/deep/$baz_/bar/' @@ -2326,12 +2359,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof NonNestedDeepBazBarIndexRouteImport parentRoute: typeof NonNestedDeepBazBarRouteRoute } - '/params-ps/named/$foo/$bar/$baz': { - id: '/params-ps/named/$foo/$bar/$baz' - path: '/$baz' - fullPath: '/params-ps/named/$foo/$bar/$baz' - preLoaderRoute: typeof ParamsPsNamedFooBarBazRouteImport - parentRoute: typeof ParamsPsNamedFooBarRouteRoute + '/non-nested/deep/$baz_/bar/$foo': { + id: '/non-nested/deep/$baz_/bar/$foo' + path: '/$foo' + fullPath: '/non-nested/deep/$baz/bar/$foo' + preLoaderRoute: typeof NonNestedDeepBazBarFooRouteRouteImport + parentRoute: typeof NonNestedDeepBazBarRouteRoute } '/non-nested/deep/$baz_/bar_/qux': { id: '/non-nested/deep/$baz_/bar_/qux' @@ -2340,12 +2373,40 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof NonNestedDeepBazBarQuxRouteImport parentRoute: typeof NonNestedDeepRouteRoute } - '/non-nested/deep/$baz_/bar/$foo': { - id: '/non-nested/deep/$baz_/bar/$foo' - path: '/$foo' - fullPath: '/non-nested/deep/$baz/bar/$foo' - preLoaderRoute: typeof NonNestedDeepBazBarFooRouteRouteImport - parentRoute: typeof NonNestedDeepBazBarRouteRoute + '/params-ps/named/$foo/$bar/$baz': { + id: '/params-ps/named/$foo/$bar/$baz' + path: '/$baz' + fullPath: '/params-ps/named/$foo/$bar/$baz' + preLoaderRoute: typeof ParamsPsNamedFooBarBazRouteImport + parentRoute: typeof ParamsPsNamedFooBarRouteRoute + } + '/relative/link/nested/deep/': { + id: '/relative/link/nested/deep/' + path: '/nested/deep' + fullPath: '/relative/link/nested/deep/' + preLoaderRoute: typeof RelativeLinkNestedDeepIndexRouteImport + parentRoute: typeof RelativeLinkRouteRoute + } + '/relative/link/path/$path/': { + id: '/relative/link/path/$path/' + path: '/path/$path' + fullPath: '/relative/link/path/$path/' + preLoaderRoute: typeof RelativeLinkPathPathIndexRouteImport + parentRoute: typeof RelativeLinkRouteRoute + } + '/relative/useNavigate/nested/deep/': { + id: '/relative/useNavigate/nested/deep/' + path: '/nested/deep' + fullPath: '/relative/useNavigate/nested/deep/' + preLoaderRoute: typeof RelativeUseNavigateNestedDeepIndexRouteImport + parentRoute: typeof RelativeUseNavigateRouteRoute + } + '/relative/useNavigate/path/$path/': { + id: '/relative/useNavigate/path/$path/' + path: '/path/$path' + fullPath: '/relative/useNavigate/path/$path/' + preLoaderRoute: typeof RelativeUseNavigatePathPathIndexRouteImport + parentRoute: typeof RelativeUseNavigateRouteRoute } '/non-nested/deep/$baz_/bar/$foo/': { id: '/non-nested/deep/$baz_/bar/$foo/' @@ -2878,8 +2939,11 @@ const rootRouteChildren: RootRouteChildren = { LayoutRoute: LayoutRouteWithChildren, AnchorRoute: AnchorRoute, ComponentTypesTestRoute: ComponentTypesTestRoute, + DocumentNavigationRoute: DocumentNavigationRoute, + DocumentNavigationTargetRoute: DocumentNavigationTargetRoute, EditingARoute: EditingARoute, EditingBRoute: EditingBRoute, + HistoryBlockingRoute: HistoryBlockingRoute, HoverPreloadHashRoute: HoverPreloadHashRoute, LazyErrorRoute: LazyErrorRoute, MasksRoute: MasksRouteWithChildren, diff --git a/e2e/react-router/basic-file-based/src/routes/anchor.tsx b/e2e/react-router/basic-file-based/src/routes/anchor.tsx index aafad6cb6f..cae0a3e583 100644 --- a/e2e/react-router/basic-file-based/src/routes/anchor.tsx +++ b/e2e/react-router/basic-file-based/src/routes/anchor.tsx @@ -25,6 +25,10 @@ const anchors: Array<{ title: 'Smooth Scroll', hashScrollIntoView: { behavior: 'smooth' }, }, + { + id: '/\\section', + title: 'Fragment with slashes', + }, ] as const function AnchorSection({ id, title }: { id: string; title: string }) { diff --git a/e2e/react-router/basic-file-based/src/routes/document-navigation-target.tsx b/e2e/react-router/basic-file-based/src/routes/document-navigation-target.tsx new file mode 100644 index 0000000000..905b0c31b9 --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/document-navigation-target.tsx @@ -0,0 +1,3 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/document-navigation-target')({}) diff --git a/e2e/react-router/basic-file-based/src/routes/document-navigation.tsx b/e2e/react-router/basic-file-based/src/routes/document-navigation.tsx new file mode 100644 index 0000000000..66c2b704d1 --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/document-navigation.tsx @@ -0,0 +1,97 @@ +import { Link, createFileRoute } from '@tanstack/react-router' +import type { AnyRouter } from '@tanstack/react-router' + +export const Route = createFileRoute('/document-navigation')({ + component: DocumentNavigation, +}) + +const adminHref = `http://127.0.0.1:${window.location.port}/external.html` + +function DocumentNavigation() { + const navigate = Route.useNavigate() + + return ( +
+ + + + + + + + Navigate to admin + + Replace with admin + + + Reload admin + + + Navigate with external mask + + + Replace with external mask + + to={`${adminHref}?value=a+b&value=a%20b#raw%2f`}> + Navigate to absolute href + + + Reload relative href + +
+ ) +} diff --git a/e2e/react-router/basic-file-based/src/routes/history-blocking.tsx b/e2e/react-router/basic-file-based/src/routes/history-blocking.tsx new file mode 100644 index 0000000000..019893a628 --- /dev/null +++ b/e2e/react-router/basic-file-based/src/routes/history-blocking.tsx @@ -0,0 +1,119 @@ +import * as React from 'react' +import { + Link, + createFileRoute, + useBlocker, + useRouter, +} from '@tanstack/react-router' + +export const Route = createFileRoute('/history-blocking')({ + validateSearch: (search: Record) => ({ + step: Number(search.step) || 0, + }), + component: HistoryBlocking, +}) + +function HistoryBlocking() { + const router = useRouter() + const { step } = Route.useSearch() + const [draft, setDraft] = React.useState('') + const [ignoreBlocker, setIgnoreBlocker] = React.useState(false) + const [documentHref, setDocumentHref] = React.useState('/') + const [navigationError, setNavigationError] = React.useState('') + const { status, reset, proceed } = useBlocker({ + shouldBlockFn: () => draft.length > 0, + enableBeforeUnload: draft.length > 0, + withResolver: true, + }) + + return ( +
+

History blocking

+

Step {step}

+ + +

{draft ? 'Unsaved changes' : 'No changes'}

+

Blocker status: {status}

+ {status === 'blocked' && ( + <> + + + + )} + + {[false, true].map((replace) => ( + + ))} + {navigationError &&

{navigationError}

} + + Add history entry + + + + {[-2, -1, 0, 1, 2].map((delta) => ( + + ))} + Leave document +
+ ) +} diff --git a/e2e/react-router/basic-file-based/tests/app.spec.ts b/e2e/react-router/basic-file-based/tests/app.spec.ts index ae87d350ce..bd9c365484 100644 --- a/e2e/react-router/basic-file-based/tests/app.spec.ts +++ b/e2e/react-router/basic-file-based/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' import type { Page } from '@playwright/test' test.beforeEach(async ({ page }) => { diff --git a/e2e/react-router/basic-file-based/tests/document-navigation.spec.ts b/e2e/react-router/basic-file-based/tests/document-navigation.spec.ts new file mode 100644 index 0000000000..bd81eaa44b --- /dev/null +++ b/e2e/react-router/basic-file-based/tests/document-navigation.spec.ts @@ -0,0 +1,68 @@ +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' + +const appPort = Number(process.env.E2E_APP_PORT ?? 0) +const adminHref = `http://127.0.0.1:${appPort}/external.html` + +for (const role of ['button', 'link'] as const) { + for (const { name, href, replace } of [ + { name: 'Navigate to admin', href: adminHref, replace: false }, + { name: 'Replace with admin', href: adminHref, replace: true }, + { name: 'Reload admin', href: adminHref, replace: false }, + { name: 'Navigate with external mask', href: adminHref, replace: false }, + { name: 'Replace with external mask', href: adminHref, replace: true }, + { + name: 'Navigate to absolute href', + href: `${adminHref}?value=a+b&value=a%20b#raw%2f`, + replace: false, + }, + ]) { + test(`${role}: ${name}`, async ({ page }) => { + const errors: Array = [] + page.on('pageerror', (error) => errors.push(error)) + await page.goto('/') + await page.goto('/document-navigation') + const historyLength = await page.evaluate(() => window.history.length) + const response = page.waitForResponse(href.split('#')[0]) + + const control = page.getByRole(role, { name, exact: true }) + if (role === 'link') { + await expect(control).toHaveAttribute('href', href) + } + await control.click() + + expect((await response).request().isNavigationRequest()).toBe(true) + await expect(page).toHaveURL(href) + await expect(page.locator('body')).toHaveText('Hello World') + // Cross-origin Links use native anchors, which push even with replace=true. + const replacesHistory = role === 'button' && replace + expect(await page.evaluate(() => window.history.length)).toBe( + historyLength + (replacesHistory ? 0 : 1), + ) + expect(errors).toEqual([]) + + await page.goBack() + + await expect(page).toHaveURL( + replacesHistory ? '/' : '/document-navigation', + ) + }) + } + + test(`${role}: explicit reload resolves a raw relative href in the browser`, async ({ + page, + }) => { + await page.goto('/document-navigation') + const response = page.waitForResponse((candidate) => + candidate.request().isNavigationRequest(), + ) + + await page + .getByRole(role, { name: 'Reload relative href', exact: true }) + .click() + + expect((await response).request().resourceType()).toBe('document') + await expect(page).toHaveURL('/?value=a+b&value=a%20b#raw%2f') + await expect(page.getByRole('heading')).toContainText('Welcome Home!') + }) +} diff --git a/e2e/react-router/basic-file-based/tests/fullpath-types.spec.ts b/e2e/react-router/basic-file-based/tests/fullpath-types.spec.ts index d1bd9c1c41..8f4df9f966 100644 --- a/e2e/react-router/basic-file-based/tests/fullpath-types.spec.ts +++ b/e2e/react-router/basic-file-based/tests/fullpath-types.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.describe('FullPath type/runtime match (Issues #4892, #2675, #6403)', () => { test.describe('Pathless layout routes should have parent fullPath, not empty string', () => { diff --git a/e2e/react-router/basic-file-based/tests/history-blocking.spec.ts b/e2e/react-router/basic-file-based/tests/history-blocking.spec.ts new file mode 100644 index 0000000000..df1f863a03 --- /dev/null +++ b/e2e/react-router/basic-file-based/tests/history-blocking.spec.ts @@ -0,0 +1,254 @@ +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' +import type { Page } from '@playwright/test' + +async function prepareDocumentTraversal(page: Page, delta: number) { + if (delta < 0) { + for (let i = 0; i < Math.abs(delta); i++) { + await page.goto(`/?entry=${i}`) + } + await page.goto('/history-blocking') + } else { + await page.goto('/history-blocking') + for (let i = 0; i < delta; i++) { + await page.goto(`/?entry=${i}`) + } + for (let i = 0; i < delta; i++) { + await page.goBack() + } + } + await expect( + page.getByRole('heading', { name: 'History blocking' }), + ).toBeVisible() + await page.getByLabel('Draft', { exact: true }).fill('Unsaved draft') + await expect(page.getByText('Unsaved changes', { exact: true })).toBeVisible() +} + +async function prepareSameDocumentTraversal(page: Page, delta: number) { + await page.goto('/history-blocking') + for (let step = 1; step <= Math.abs(delta); step++) { + await page.getByRole('link', { name: 'Add history entry' }).click() + await expect(page.getByText(`Step ${step}`, { exact: true })).toBeVisible() + } + if (delta > 0) { + for (let step = delta - 1; step >= 0; step--) { + await page + .getByRole('button', { name: 'History back', exact: true }) + .click() + await expect( + page.getByText(`Step ${step}`, { exact: true }), + ).toBeVisible() + } + } + await page.getByLabel('Draft', { exact: true }).fill('Unsaved draft') + await expect(page.getByText('Unsaved changes', { exact: true })).toBeVisible() +} + +function dismissUnloadDialogs(page: Page) { + const dialogs: Array = [] + page.on('dialog', async (dialog) => { + dialogs.push(dialog.type()) + await dialog.dismiss() + }) + return dialogs +} + +for (const [direction, delta] of [ + ['back', -1], + ['forward', 1], + ['go(-1)', -1], + ['go(1)', 1], + ['go(-2)', -2], + ['go(2)', 2], +] as const) { + test(`history ${direction} to another document warns before losing edits`, async ({ + page, + }) => { + await prepareDocumentTraversal(page, delta) + const dialogs = dismissUnloadDialogs(page) + const originalUrl = page.url() + + await page + .getByRole('button', { name: `History ${direction}`, exact: true }) + .click() + + await expect.poll(() => dialogs).toEqual(['beforeunload']) + await expect(page).toHaveURL(originalUrl) + await expect(page.getByLabel('Draft', { exact: true })).toHaveValue( + 'Unsaved draft', + ) + }) + + test(`history ${direction} can explicitly bypass a document unload warning`, async ({ + page, + }) => { + await prepareDocumentTraversal(page, delta) + await page.getByLabel('Ignore blockers').check() + const dialogs = dismissUnloadDialogs(page) + + await page + .getByRole('button', { name: `History ${direction}`, exact: true }) + .click() + + await expect(page).toHaveURL(/\/\?entry=\d$/) + expect(dialogs).toEqual([]) + }) + + test(`ignored same-document ${direction} preserves the next document unload warning`, async ({ + page, + }) => { + await prepareSameDocumentTraversal(page, delta) + await page.getByLabel('Ignore blockers').check() + const dialogs = dismissUnloadDialogs(page) + + await page + .getByRole('button', { name: `History ${direction}`, exact: true }) + .click() + + await expect( + page.getByText(`Step ${delta < 0 ? 0 : delta}`, { + exact: true, + }), + ).toBeVisible() + await expect(page.getByLabel('Draft', { exact: true })).toHaveValue( + 'Unsaved draft', + ) + await expect( + page.getByText('Blocker status: idle', { exact: true }), + ).toBeVisible() + expect(dialogs).toEqual([]) + + await page.getByRole('link', { name: 'Leave document' }).click() + + await expect.poll(() => dialogs).toEqual(['beforeunload']) + await expect(page.getByLabel('Draft', { exact: true })).toHaveValue( + 'Unsaved draft', + ) + }) + + test(`same-document ${direction} still checks blockers by default`, async ({ + page, + }) => { + await prepareSameDocumentTraversal(page, delta) + const originalUrl = page.url() + + await page + .getByRole('button', { name: `History ${direction}`, exact: true }) + .click() + + await expect( + page.getByText('Blocker status: blocked', { exact: true }), + ).toBeVisible() + await expect( + page.getByText(`Step ${delta < 0 ? -delta : 0}`, { exact: true }), + ).toBeVisible() + await expect(page.getByLabel('Draft', { exact: true })).toHaveValue( + 'Unsaved draft', + ) + await page.getByRole('button', { name: 'Stay here' }).click() + await expect( + page.getByText('Blocker status: idle', { exact: true }), + ).toBeVisible() + await expect(page).toHaveURL(originalUrl) + await expect( + page.getByText(`Step ${delta < 0 ? -delta : 0}`, { exact: true }), + ).toBeVisible() + }) +} + +for (const ignoreBlocker of [false, true]) { + test(`history go(0) ${ignoreBlocker ? 'can bypass' : 'preserves'} the reload warning`, async ({ + page, + }) => { + await page.goto('/history-blocking') + await page.getByLabel('Draft', { exact: true }).fill('Unsaved draft') + await expect( + page.getByText('Unsaved changes', { exact: true }), + ).toBeVisible() + if (ignoreBlocker) { + await page.getByLabel('Ignore blockers').check() + } + const dialogs = dismissUnloadDialogs(page) + + await page + .getByRole('button', { name: 'History go(0)', exact: true }) + .click() + + if (ignoreBlocker) { + await expect(page.getByLabel('Draft', { exact: true })).toHaveValue('') + expect(dialogs).toEqual([]) + } else { + await expect.poll(() => dialogs).toEqual(['beforeunload']) + await expect(page.getByLabel('Draft', { exact: true })).toHaveValue( + 'Unsaved draft', + ) + } + }) +} + +for (const action of ['Navigate document', 'Replace document']) { + test(`${action}: invalid URLs preserve the next unload warning`, async ({ + page, + }) => { + await page.goto('/history-blocking') + await page.getByLabel('Draft', { exact: true }).fill('Unsaved draft') + await page.getByLabel('Ignore blockers').check() + await page.getByLabel('Document destination').fill('https://[') + const dialogs = dismissUnloadDialogs(page) + + await page.getByRole('button', { name: action, exact: true }).click() + + await expect(page.getByRole('status')).toBeVisible() + expect(dialogs).toEqual([]) + await page.getByRole('link', { name: 'Leave document' }).click() + + await expect.poll(() => dialogs).toEqual(['beforeunload']) + await expect(page.getByLabel('Draft', { exact: true })).toHaveValue( + 'Unsaved draft', + ) + }) + + test(`${action}: the current fragment preserves the next unload warning`, async ({ + page, + }) => { + await page.goto('/history-blocking?step=0#same') + await page.getByLabel('Draft', { exact: true }).fill('Unsaved draft') + await page.getByLabel('Ignore blockers').check() + await page.getByLabel('Document destination').fill('#same') + const dialogs = dismissUnloadDialogs(page) + + await page.getByRole('button', { name: action, exact: true }).click() + + await expect(page).toHaveURL('/history-blocking?step=0#same') + expect(dialogs).toEqual([]) + await page.getByRole('link', { name: 'Leave document' }).click() + + await expect.poll(() => dialogs).toEqual(['beforeunload']) + await expect(page.getByLabel('Draft', { exact: true })).toHaveValue( + 'Unsaved draft', + ) + }) + + for (const ignoreBlocker of [false, true]) { + test(`${action}: ${ignoreBlocker ? 'skipped' : 'accepted'} blockers need no native confirmation`, async ({ + page, + }) => { + await page.goto('/history-blocking') + await page.getByLabel('Draft', { exact: true }).fill('Unsaved draft') + if (ignoreBlocker) { + await page.getByLabel('Ignore blockers').check() + } + const dialogs = dismissUnloadDialogs(page) + + await page.getByRole('button', { name: action, exact: true }).click() + if (!ignoreBlocker) { + await page + .getByRole('button', { name: 'Continue navigation', exact: true }) + .click() + } + + await expect(page).toHaveURL('/') + expect(dialogs).toEqual([]) + }) + } +} diff --git a/e2e/react-router/basic-file-based/tests/hover-preload-hash.spec.ts b/e2e/react-router/basic-file-based/tests/hover-preload-hash.spec.ts index b090c2a6b7..1263faf391 100644 --- a/e2e/react-router/basic-file-based/tests/hover-preload-hash.spec.ts +++ b/e2e/react-router/basic-file-based/tests/hover-preload-hash.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' import { toRuntimePath } from '@tanstack/router-e2e-utils' test('clicking hash link then hovering another link does not scroll back to hash', async ({ diff --git a/e2e/react-router/basic-file-based/tests/mask.spec.ts b/e2e/react-router/basic-file-based/tests/mask.spec.ts index 1b77760de6..d5076a5854 100644 --- a/e2e/react-router/basic-file-based/tests/mask.spec.ts +++ b/e2e/react-router/basic-file-based/tests/mask.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test('route masks transform params and expose masked pathname in the browser (react)', async ({ page, diff --git a/e2e/react-router/basic-file-based/tests/non-nested-paths.spec.ts b/e2e/react-router/basic-file-based/tests/non-nested-paths.spec.ts index dccdfd4acf..ea0e585c75 100644 --- a/e2e/react-router/basic-file-based/tests/non-nested-paths.spec.ts +++ b/e2e/react-router/basic-file-based/tests/non-nested-paths.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' const testCases: Array<{ name: string diff --git a/e2e/react-router/basic-file-based/tests/open-redirect-prevention.spec.ts b/e2e/react-router/basic-file-based/tests/open-redirect-prevention.spec.ts index 2f0fe256cd..bbb2dac7a1 100644 --- a/e2e/react-router/basic-file-based/tests/open-redirect-prevention.spec.ts +++ b/e2e/react-router/basic-file-based/tests/open-redirect-prevention.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.describe('Open redirect prevention', () => { test.describe('CRLF injection attacks', () => { diff --git a/e2e/react-router/basic-file-based/tests/params.spec.ts b/e2e/react-router/basic-file-based/tests/params.spec.ts index a867696ff8..fa0377f3ca 100644 --- a/e2e/react-router/basic-file-based/tests/params.spec.ts +++ b/e2e/react-router/basic-file-based/tests/params.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' import type { Page } from '@playwright/test' test.beforeEach(async ({ page }) => { diff --git a/e2e/react-router/basic-file-based/tests/redirect.spec.ts b/e2e/react-router/basic-file-based/tests/redirect.spec.ts index 1845cc16a4..aaa9c1a6b6 100644 --- a/e2e/react-router/basic-file-based/tests/redirect.spec.ts +++ b/e2e/react-router/basic-file-based/tests/redirect.spec.ts @@ -1,17 +1,13 @@ import queryString from 'node:querystring' -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' import combinateImport from 'combinate' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from '../package.json' with { type: 'json' } // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_HOST_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const EXTERNAL_ORIGIN = `http://127.0.0.1:${PORT}` test.describe('redirects', () => { const internalNavigationTestMatrix = combinate({ @@ -39,7 +35,7 @@ test.describe('redirects', () => { const requestPromise = new Promise((resolve) => { page.on('request', (request) => { if ( - request.url() === `http://localhost:${EXTERNAL_HOST_PORT}/posts` + request.url() === 'https://jsonplaceholder.typicode.com/posts' ) { requestHappened = true resolve() @@ -108,7 +104,7 @@ test.describe('redirects', () => { await page.waitForLoadState('networkidle') const q = queryString.stringify({ - externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, + externalHost: `${EXTERNAL_ORIGIN}/`, }) if (scenario === 'navigate') { @@ -118,7 +114,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/external/via-${thrower}?${q}`) } - const url = `http://localhost:${EXTERNAL_HOST_PORT}/` + const url = `${EXTERNAL_ORIGIN}/` await page.waitForURL(url) expect(page.url()).toBe(url) @@ -184,7 +180,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, + externalHost: `${EXTERNAL_ORIGIN}/`, }) if (scenario === 'navigate') { @@ -197,7 +193,7 @@ test.describe('redirects', () => { ) } - const url = `http://localhost:${EXTERNAL_HOST_PORT}/` + const url = `${EXTERNAL_ORIGIN}/` await page.waitForURL(url) expect(page.url()).toBe(url) }) @@ -254,7 +250,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, + externalHost: `${EXTERNAL_ORIGIN}/`, }) if (scenario === 'navigate') { @@ -267,7 +263,7 @@ test.describe('redirects', () => { ) } - const url = `http://localhost:${EXTERNAL_HOST_PORT}/` + const url = `${EXTERNAL_ORIGIN}/` await page.waitForURL(url) expect(page.url()).toBe(url) }) diff --git a/e2e/react-router/basic-file-based/tests/relative.spec.ts b/e2e/react-router/basic-file-based/tests/relative.spec.ts index 4850d3630d..f62c248680 100644 --- a/e2e/react-router/basic-file-based/tests/relative.spec.ts +++ b/e2e/react-router/basic-file-based/tests/relative.spec.ts @@ -1,12 +1,11 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' import combinateImport from 'combinate' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from '../package.json' with { type: 'json' } // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) test.describe('relative_routing', () => { const internalNavigationTestMatrix = combinate({ diff --git a/e2e/react-router/basic-file-based/tests/scroll-into-view.spec.ts b/e2e/react-router/basic-file-based/tests/scroll-into-view.spec.ts index d1af86adfb..68dfededc2 100644 --- a/e2e/react-router/basic-file-based/tests/scroll-into-view.spec.ts +++ b/e2e/react-router/basic-file-based/tests/scroll-into-view.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' import type { Page } from '@playwright/test' const anchors = { @@ -32,6 +33,21 @@ test.beforeEach(async ({ page }) => { await page.goto('/anchor') }) +test('slash and backslash fragment data selects the matching anchor', async ({ + page, +}) => { + const link = page.getByRole('link', { name: 'Fragment with slashes' }) + const heading = page.getByRole('heading', { name: 'Fragment with slashes' }) + await link.click() + await expect(page).toHaveURL(/#\/\\section$/) + await expect(link).toHaveClass(activeClass) + await expect(heading).toBeInViewport() + + await page.reload() + await expect(link).toHaveClass(activeClass) + await expect(heading).toBeInViewport() +}) + // Testing the `Link` component with the `hashScrollIntoView` prop test('Navigating via anchor `Link` with default hash scrolling behavior', async ({ page, diff --git a/e2e/react-router/basic-file-based/tests/search-params.spec.ts b/e2e/react-router/basic-file-based/tests/search-params.spec.ts index d6307cbcf8..a99488a47a 100644 --- a/e2e/react-router/basic-file-based/tests/search-params.spec.ts +++ b/e2e/react-router/basic-file-based/tests/search-params.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.describe('/search-params/default', () => { test('Directly visiting the route without search param set', async ({ diff --git a/e2e/react-router/basic-file-based/tests/setup/global.setup.ts b/e2e/react-router/basic-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/basic-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-router/basic-file-based/tests/setup/global.teardown.ts b/e2e/react-router/basic-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/basic-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-router/basic-react-query-file-based/package.json b/e2e/react-router/basic-react-query-file-based/package.json index 6548381772..3a90a3cd6d 100644 --- a/e2e/react-router/basic-react-query-file-based/package.json +++ b/e2e/react-router/basic-react-query-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -19,7 +19,7 @@ "@tanstack/router-plugin": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, diff --git a/e2e/react-router/basic-react-query-file-based/playwright.config.ts b/e2e/react-router/basic-react-query-file-based/playwright.config.ts index f3083ff8b6..fbda9bd451 100644 --- a/e2e/react-router/basic-react-query-file-based/playwright.config.ts +++ b/e2e/react-router/basic-react-query-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -17,17 +12,15 @@ export default defineConfig({ workers: 1, reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/basic-react-query-file-based/src/posts.tsx b/e2e/react-router/basic-react-query-file-based/src/posts.tsx index 1becc2c242..1f6cb8e308 100644 --- a/e2e/react-router/basic-react-query-file-based/src/posts.tsx +++ b/e2e/react-router/basic-react-query-file-based/src/posts.tsx @@ -8,11 +8,7 @@ export type PostType = { export class PostNotFoundError extends Error {} -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-router/basic-react-query-file-based/src/routeTree.gen.ts b/e2e/react-router/basic-react-query-file-based/src/routeTree.gen.ts index 62ce94f2c8..115e4bce47 100644 --- a/e2e/react-router/basic-react-query-file-based/src/routeTree.gen.ts +++ b/e2e/react-router/basic-react-query-file-based/src/routeTree.gen.ts @@ -9,29 +9,33 @@ // 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 PostsRouteImport } from './routes/posts' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as IndexRouteImport } from './routes/index' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const LayoutRoute = LayoutRouteImport.update({ id: '/_layout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, +} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -42,20 +46,16 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRoute, } as any) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any) const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ id: '/layout-b', path: '/layout-b', getParentRoute: () => LayoutLayout2Route, } as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, -} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -114,11 +114,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -128,13 +128,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute + } '/posts/': { id: '/posts/' path: '/' @@ -149,12 +156,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route } '/_layout/_layout-2/layout-b': { id: '/_layout/_layout-2/layout-b' @@ -163,13 +170,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport parentRoute: typeof LayoutLayout2Route } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route - } } } diff --git a/e2e/react-router/basic-react-query-file-based/tests/app.spec.ts b/e2e/react-router/basic-react-query-file-based/tests/app.spec.ts index d80e8dada5..2b42d6d589 100644 --- a/e2e/react-router/basic-react-query-file-based/tests/app.spec.ts +++ b/e2e/react-router/basic-react-query-file-based/tests/app.spec.ts @@ -1,24 +1,23 @@ -import { expect, test } from '@playwright/test' -import { getDummyServerPort } from '@tanstack/router-e2e-utils' -import packageJson from '../package.json' with { type: 'json' } +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') }) -test('GetPosts', async () => { - const port = await getDummyServerPort(packageJson.name) - const res = await fetch(`http://localhost:${port}/posts`) - - expect(res.status).toBe(200) - - const posts = await res.json() - +test('GetPosts with networking disabled', async ({ page, context }) => { + await page.goto('about:blank') + await context.setOffline(true) + const { status, posts, post } = await page.evaluate(async () => { + const response = await fetch('https://jsonplaceholder.typicode.com/posts') + const posts = await response.json() + const post = await fetch( + 'https://jsonplaceholder.typicode.com/posts/1', + ).then((r) => r.json()) + return { status: response.status, posts, post } + }) + expect(status).toBe(200) expect(posts.length).toBeGreaterThan(0) - - const postRes = await fetch(`http://localhost:${port}/posts/1`) - expect(postRes.status).toBe(200) - const post = await postRes.json() expect(post).toEqual(posts[0]) }) diff --git a/e2e/react-router/basic-react-query-file-based/tests/setup/global.setup.ts b/e2e/react-router/basic-react-query-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/basic-react-query-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-router/basic-react-query-file-based/tests/setup/global.teardown.ts b/e2e/react-router/basic-react-query-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/basic-react-query-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-router/basic-react-query/package.json b/e2e/react-router/basic-react-query/package.json index 81eb9eb67b..8f28340f56 100644 --- a/e2e/react-router/basic-react-query/package.json +++ b/e2e/react-router/basic-react-query/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -18,7 +18,7 @@ "@tanstack/router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2" }, "devDependencies": { diff --git a/e2e/react-router/basic-react-query/playwright.config.ts b/e2e/react-router/basic-react-query/playwright.config.ts index ab42c7c607..4eead86444 100644 --- a/e2e/react-router/basic-react-query/playwright.config.ts +++ b/e2e/react-router/basic-react-query/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/basic-react-query/src/posts.ts b/e2e/react-router/basic-react-query/src/posts.ts index 5e2a2d3aa3..ffc5a274b7 100644 --- a/e2e/react-router/basic-react-query/src/posts.ts +++ b/e2e/react-router/basic-react-query/src/posts.ts @@ -9,11 +9,7 @@ type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/react-router/basic-react-query/tests/app.spec.ts b/e2e/react-router/basic-react-query/tests/app.spec.ts index 3e5a69ccaa..fbf093cd51 100644 --- a/e2e/react-router/basic-react-query/tests/app.spec.ts +++ b/e2e/react-router/basic-react-query/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/basic-react-query/tests/setup/global.setup.ts b/e2e/react-router/basic-react-query/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/basic-react-query/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-router/basic-react-query/tests/setup/global.teardown.ts b/e2e/react-router/basic-react-query/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/basic-react-query/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-router/basic-scroll-restoration/package.json b/e2e/react-router/basic-scroll-restoration/package.json index d8ebcb414b..c13e92cec8 100644 --- a/e2e/react-router/basic-scroll-restoration/package.json +++ b/e2e/react-router/basic-scroll-restoration/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -17,7 +17,7 @@ "@tanstack/react-virtual": "^3.13.0", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2" }, "devDependencies": { diff --git a/e2e/react-router/basic-scroll-restoration/playwright.config.ts b/e2e/react-router/basic-scroll-restoration/playwright.config.ts index 0c5cee43e4..6a684ac89e 100644 --- a/e2e/react-router/basic-scroll-restoration/playwright.config.ts +++ b/e2e/react-router/basic-scroll-restoration/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/basic-virtual-file-based/package.json b/e2e/react-router/basic-virtual-file-based/package.json index 891f1d6328..0343de0846 100644 --- a/e2e/react-router/basic-virtual-file-based/package.json +++ b/e2e/react-router/basic-virtual-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -18,7 +18,7 @@ "@tanstack/virtual-file-routes": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, diff --git a/e2e/react-router/basic-virtual-file-based/playwright.config.ts b/e2e/react-router/basic-virtual-file-based/playwright.config.ts index c5de6b5611..4eead86444 100644 --- a/e2e/react-router/basic-virtual-file-based/playwright.config.ts +++ b/e2e/react-router/basic-virtual-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -22,13 +17,10 @@ export default defineConfig({ baseURL, }, - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - webServer: { - command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/basic-virtual-file-based/src/posts.tsx b/e2e/react-router/basic-virtual-file-based/src/posts.tsx index 01831e335c..cc3cb0f9c8 100644 --- a/e2e/react-router/basic-virtual-file-based/src/posts.tsx +++ b/e2e/react-router/basic-virtual-file-based/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-router/basic-virtual-file-based/src/routeTree.gen.ts b/e2e/react-router/basic-virtual-file-based/src/routeTree.gen.ts index 72e6928d43..eb98ba28c5 100644 --- a/e2e/react-router/basic-virtual-file-based/src/routeTree.gen.ts +++ b/e2e/react-router/basic-virtual-file-based/src/routeTree.gen.ts @@ -9,76 +9,76 @@ // 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 postsPostsRouteImport } from './routes/posts/posts' -import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' import { Route as homeRouteImport } from './routes/home' -import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' +import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' +import { Route as postsPostsRouteImport } from './routes/posts/posts' import { Route as layoutSecondLayoutRouteImport } from './routes/layout/second-layout' -import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' import { Route as ClassicHelloRouteRouteImport } from './routes/file-based-subtree/hello/route' -import { Route as ClassicHelloIndexRouteImport } from './routes/file-based-subtree/hello/index' -import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' -import { Route as ClassicHelloUniverseRouteImport } from './routes/file-based-subtree/hello/universe' -import { Route as bRouteImport } from './routes/b' +import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' +import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' import { Route as aRouteImport } from './routes/a' +import { Route as bRouteImport } from './routes/b' +import { Route as ClassicHelloIndexRouteImport } from './routes/file-based-subtree/hello/index' +import { Route as ClassicHelloUniverseRouteImport } from './routes/file-based-subtree/hello/universe' +import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' -const postsPostsRoute = postsPostsRouteImport.update({ - id: '/posts', - path: '/posts', +const homeRoute = homeRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const layoutFirstLayoutRoute = layoutFirstLayoutRouteImport.update({ id: '/_first', getParentRoute: () => rootRouteImport, } as any) -const homeRoute = homeRouteImport.update({ - id: '/', - path: '/', +const postsPostsRoute = postsPostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const postsPostsDetailRoute = postsPostsDetailRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => postsPostsRoute, -} as any) const layoutSecondLayoutRoute = layoutSecondLayoutRouteImport.update({ id: '/_second', getParentRoute: () => layoutFirstLayoutRoute, } as any) -const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => postsPostsRoute, -} as any) const ClassicHelloRouteRoute = ClassicHelloRouteRouteImport.update({ id: '/classic/hello', path: '/classic/hello', getParentRoute: () => rootRouteImport, } as any) +const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => postsPostsRoute, +} as any) +const postsPostsDetailRoute = postsPostsDetailRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => postsPostsRoute, +} as any) +const aRoute = aRouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => layoutSecondLayoutRoute, +} as any) +const bRoute = bRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => layoutSecondLayoutRoute, +} as any) const ClassicHelloIndexRoute = ClassicHelloIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ - id: '/world', - path: '/world', - getParentRoute: () => ClassicHelloRouteRoute, -} as any) const ClassicHelloUniverseRoute = ClassicHelloUniverseRouteImport.update({ id: '/universe', path: '/universe', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const bRoute = bRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => layoutSecondLayoutRoute, -} as any) -const aRoute = aRouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => layoutSecondLayoutRoute, +const ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ + id: '/world', + path: '/world', + getParentRoute: () => ClassicHelloRouteRoute, } as any) export interface FileRoutesByFullPath { @@ -166,11 +166,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof postsPostsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof homeRouteImport parentRoute: typeof rootRouteImport } '/_first': { @@ -180,20 +180,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof layoutFirstLayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof homeRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof postsPostsRouteImport parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof postsPostsDetailRouteImport - parentRoute: typeof postsPostsRoute - } '/_first/_second': { id: '/_first/_second' path: '' @@ -201,13 +194,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof layoutSecondLayoutRouteImport parentRoute: typeof layoutFirstLayoutRoute } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof postsPostsHomeRouteImport - parentRoute: typeof postsPostsRoute - } '/classic/hello': { id: '/classic/hello' path: '/classic/hello' @@ -215,6 +201,34 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ClassicHelloRouteRouteImport parentRoute: typeof rootRouteImport } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof postsPostsHomeRouteImport + parentRoute: typeof postsPostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof postsPostsDetailRouteImport + parentRoute: typeof postsPostsRoute + } + '/_first/_second/layout-a': { + id: '/_first/_second/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof aRouteImport + parentRoute: typeof layoutSecondLayoutRoute + } + '/_first/_second/layout-b': { + id: '/_first/_second/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof bRouteImport + parentRoute: typeof layoutSecondLayoutRoute + } '/classic/hello/': { id: '/classic/hello/' path: '/' @@ -222,13 +236,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ClassicHelloIndexRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/classic/hello/world': { - id: '/classic/hello/world' - path: '/world' - fullPath: '/classic/hello/world' - preLoaderRoute: typeof ClassicHelloWorldRouteImport - parentRoute: typeof ClassicHelloRouteRoute - } '/classic/hello/universe': { id: '/classic/hello/universe' path: '/universe' @@ -236,19 +243,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ClassicHelloUniverseRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/_first/_second/layout-b': { - id: '/_first/_second/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof bRouteImport - parentRoute: typeof layoutSecondLayoutRoute - } - '/_first/_second/layout-a': { - id: '/_first/_second/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof aRouteImport - parentRoute: typeof layoutSecondLayoutRoute + '/classic/hello/world': { + id: '/classic/hello/world' + path: '/world' + fullPath: '/classic/hello/world' + preLoaderRoute: typeof ClassicHelloWorldRouteImport + parentRoute: typeof ClassicHelloRouteRoute } } } diff --git a/e2e/react-router/basic-virtual-file-based/tests/app.spec.ts b/e2e/react-router/basic-virtual-file-based/tests/app.spec.ts index 3e5a69ccaa..fbf093cd51 100644 --- a/e2e/react-router/basic-virtual-file-based/tests/app.spec.ts +++ b/e2e/react-router/basic-virtual-file-based/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/basic-virtual-file-based/tests/setup/global.setup.ts b/e2e/react-router/basic-virtual-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/basic-virtual-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-router/basic-virtual-file-based/tests/setup/global.teardown.ts b/e2e/react-router/basic-virtual-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/basic-virtual-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-router/basic-virtual-named-export-config-file-based/package.json b/e2e/react-router/basic-virtual-named-export-config-file-based/package.json index d3872b01e6..6bdb1248f6 100644 --- a/e2e/react-router/basic-virtual-named-export-config-file-based/package.json +++ b/e2e/react-router/basic-virtual-named-export-config-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -18,7 +18,7 @@ "@tanstack/virtual-file-routes": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, diff --git a/e2e/react-router/basic-virtual-named-export-config-file-based/playwright.config.ts b/e2e/react-router/basic-virtual-named-export-config-file-based/playwright.config.ts index ab42c7c607..4eead86444 100644 --- a/e2e/react-router/basic-virtual-named-export-config-file-based/playwright.config.ts +++ b/e2e/react-router/basic-virtual-named-export-config-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/basic-virtual-named-export-config-file-based/src/posts.tsx b/e2e/react-router/basic-virtual-named-export-config-file-based/src/posts.tsx index ae7142c5b6..97c96d77eb 100644 --- a/e2e/react-router/basic-virtual-named-export-config-file-based/src/posts.tsx +++ b/e2e/react-router/basic-virtual-named-export-config-file-based/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts b/e2e/react-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts index 0aedada786..7d2074182f 100644 --- a/e2e/react-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts +++ b/e2e/react-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts b/e2e/react-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts b/e2e/react-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-router/basic/package.json b/e2e/react-router/basic/package.json index a8de9acc3f..4ff68f5cda 100644 --- a/e2e/react-router/basic/package.json +++ b/e2e/react-router/basic/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -16,8 +16,9 @@ "@tanstack/react-router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", - "tailwindcss": "^4.2.2" + "redaxios": "catalog:", + "tailwindcss": "^4.2.2", + "zod": "catalog:" }, "devDependencies": { "@playwright/test": "^1.61.0", diff --git a/e2e/react-router/basic/playwright.config.ts b/e2e/react-router/basic/playwright.config.ts index 22c9bdcd7e..4eead86444 100644 --- a/e2e/react-router/basic/playwright.config.ts +++ b/e2e/react-router/basic/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/basic/src/main.tsx b/e2e/react-router/basic/src/main.tsx index 36e5106654..49fa054776 100644 --- a/e2e/react-router/basic/src/main.tsx +++ b/e2e/react-router/basic/src/main.tsx @@ -1,3 +1,5 @@ +import { useState } from 'react' +import { createPortal } from 'react-dom' import ReactDOM from 'react-dom/client' import { ErrorComponent, @@ -9,12 +11,19 @@ import { createRouter, redirect, } from '@tanstack/react-router' -import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' +import { + TanStackRouterDevtoolsInProd as TanStackRouterDevtools, + TanStackRouterDevtoolsPanelInProd as TanStackRouterDevtoolsPanel, +} from '@tanstack/react-router-devtools' +import { z } from 'zod' import { NotFoundError, fetchPost, fetchPosts } from './posts' import './styles.css' import type { ErrorComponentProps } from '@tanstack/react-router' const rootRoute = createRootRoute({ + validateSearch: z.object({ + devtools: z.enum(['panel', 'shadow']).optional().catch(undefined), + }), component: RootComponent, notFoundComponent: () => { return ( @@ -27,6 +36,8 @@ const rootRoute = createRootRoute({ }) function RootComponent() { + const { devtools } = rootRoute.useSearch() + return ( <>
@@ -86,12 +97,57 @@ function RootComponent() {
+
+ Devtools: + {(['floating', 'panel', 'shadow'] as const).map((mode) => ( + ({ + ...prev, + devtools: mode === 'floating' ? undefined : mode, + })} + className={ + (devtools ?? 'floating') === mode ? 'font-bold' : undefined + } + > + {mode} + + ))} +
- TanStack Logo -

- Next.js TanStack Start -

-
- Docs - -
- + {devtools === 'panel' ? ( + + ) : devtools === 'shadow' ? ( + + ) : ( + + )} ) } + +function ShadowDevtoolsPanel() { + const [shadowRoot, setShadowRoot] = useState() + + return ( +
{ + if (host) { + setShadowRoot(host.shadowRoot ?? host.attachShadow({ mode: 'open' })) + } + }} + > + {shadowRoot + ? createPortal( + , + shadowRoot, + ) + : null} +
+ ) +} const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', diff --git a/e2e/react-router/basic/src/posts.ts b/e2e/react-router/basic/src/posts.ts index e859645746..f72d16fee3 100644 --- a/e2e/react-router/basic/src/posts.ts +++ b/e2e/react-router/basic/src/posts.ts @@ -8,11 +8,7 @@ type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/react-router/basic/tests/app.spec.ts b/e2e/react-router/basic/tests/app.spec.ts index ec0e24d8a4..9c0a6b6901 100644 --- a/e2e/react-router/basic/tests/app.spec.ts +++ b/e2e/react-router/basic/tests/app.spec.ts @@ -1,8 +1,7 @@ -import { expect, test } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from '../package.json' with { type: 'json' } +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/basic/tests/devtools.spec.ts b/e2e/react-router/basic/tests/devtools.spec.ts new file mode 100644 index 0000000000..b8a7e803e6 --- /dev/null +++ b/e2e/react-router/basic/tests/devtools.spec.ts @@ -0,0 +1,42 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' + +for (const mode of ['panel', 'shadow', 'floating']) { + test(`devtools preserve typography and explorer indentation in ${mode} mode`, async ({ + page, + }) => { + await page.goto(mode === 'floating' ? '/' : `/?devtools=${mode}`) + if (mode === 'floating') { + await page + .getByRole('button', { name: 'Open TanStack Router Devtools' }) + .click() + } + + const panel = page.locator('.TanStackRouterDevtoolsPanel') + const router = panel.getByRole('button', { name: /^Router\s*\d+ items/ }) + const state = panel.getByRole('button', { name: /^state\s*\d+ items/ }) + await expect(router).toBeVisible() + await expect(state).toBeVisible() + await expect(router).toHaveCSS('font-size', '12px') + await expect(router).toHaveCSS('gap', '4px') + await expect( + panel.getByText('Pathname', { exact: true }).locator('..'), + ).toHaveCSS('padding-left', '8px') + + const routerBox = await router.boundingBox() + const stateBox = await state.boundingBox() + expect(stateBox!.x - routerBox!.x).toBe(18) + + if (mode !== 'floating') { + await page.addStyleTag({ content: ':root { font-size: 20px; }' }) + await expect(router).toHaveCSS('font-size', '15px') + await expect(router).toHaveCSS('gap', '5px') + + await page.addStyleTag({ + content: ':root { --tsrd-font-size: 24px; }', + }) + await expect(router).toHaveCSS('font-size', '18px') + await expect(router).toHaveCSS('gap', '6px') + } + }) +} diff --git a/e2e/react-router/basic/tests/params.spec.ts b/e2e/react-router/basic/tests/params.spec.ts index ac18f39864..f673138047 100644 --- a/e2e/react-router/basic/tests/params.spec.ts +++ b/e2e/react-router/basic/tests/params.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.describe('params operations + prefix/suffix', () => { test.beforeEach(async ({ page }) => { diff --git a/e2e/react-router/basic/tests/setup/global.setup.ts b/e2e/react-router/basic/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/basic/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-router/basic/tests/setup/global.teardown.ts b/e2e/react-router/basic/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/basic/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-router/escaped-special-strings/package.json b/e2e/react-router/escaped-special-strings/package.json index 71a3cb08ca..af401c49d3 100644 --- a/e2e/react-router/escaped-special-strings/package.json +++ b/e2e/react-router/escaped-special-strings/package.json @@ -9,7 +9,7 @@ "preview": "vite preview", "start": "vite", "test:e2e": "pnpm run test:e2e:default", - "test:e2e:default": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e:default": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", diff --git a/e2e/react-router/escaped-special-strings/playwright.config.ts b/e2e/react-router/escaped-special-strings/playwright.config.ts index 6e4e1d7703..629ddefccf 100644 --- a/e2e/react-router/escaped-special-strings/playwright.config.ts +++ b/e2e/react-router/escaped-special-strings/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` const command = `pnpm build && pnpm preview --port ${PORT}` @@ -21,9 +16,6 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, @@ -31,15 +23,12 @@ export default defineConfig({ webServer: { command, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', env: { MODE: process.env.MODE || '', VITE_MODE: process.env.MODE || '', - VITE_NODE_ENV: 'test', - VITE_EXTERNAL_PORT: String(EXTERNAL_PORT), - VITE_SERVER_PORT: String(PORT), PORT: String(PORT), }, }, diff --git a/e2e/react-router/escaped-special-strings/src/routeTree.gen.ts b/e2e/react-router/escaped-special-strings/src/routeTree.gen.ts index b0e04cd8e8..50a5f8b305 100644 --- a/e2e/react-router/escaped-special-strings/src/routeTree.gen.ts +++ b/e2e/react-router/escaped-special-strings/src/routeTree.gen.ts @@ -10,30 +10,20 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as Char91indexChar93RouteImport } from './routes/[index]' -import { Route as Char91routeChar93RouteImport } from './routes/[route]' -import { Route as Char91lazyChar93RouteImport } from './routes/[lazy]' -import { Route as BlogRouteImport } from './routes/blog[_]' -import { Route as LayoutRouteImport } from './routes/[_]layout' import { Route as IndexRouteImport } from './routes/index' +import { Route as LayoutRouteImport } from './routes/[_]layout' +import { Route as BlogRouteImport } from './routes/blog[_]' +import { Route as Char91lazyChar93RouteImport } from './routes/[lazy]' +import { Route as Char91routeChar93RouteImport } from './routes/[route]' const Char91indexChar93Route = Char91indexChar93RouteImport.update({ id: '/index', path: '/index', getParentRoute: () => rootRouteImport, } as any) -const Char91routeChar93Route = Char91routeChar93RouteImport.update({ - id: '/route', - path: '/route', - getParentRoute: () => rootRouteImport, -} as any) -const Char91lazyChar93Route = Char91lazyChar93RouteImport.update({ - id: '/lazy', - path: '/lazy', - getParentRoute: () => rootRouteImport, -} as any) -const BlogRoute = BlogRouteImport.update({ - id: '/blog_', - path: '/blog_', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const LayoutRoute = LayoutRouteImport.update({ @@ -41,9 +31,19 @@ const LayoutRoute = LayoutRouteImport.update({ path: '/_layout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const BlogRoute = BlogRouteImport.update({ + id: '/blog_', + path: '/blog_', + getParentRoute: () => rootRouteImport, +} as any) +const Char91lazyChar93Route = Char91lazyChar93RouteImport.update({ + id: '/lazy', + path: '/lazy', + getParentRoute: () => rootRouteImport, +} as any) +const Char91routeChar93Route = Char91routeChar93RouteImport.update({ + id: '/route', + path: '/route', getParentRoute: () => rootRouteImport, } as any) @@ -98,25 +98,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof Char91indexChar93RouteImport parentRoute: typeof rootRouteImport } - '/route': { - id: '/route' - path: '/route' - fullPath: '/route' - preLoaderRoute: typeof Char91routeChar93RouteImport - parentRoute: typeof rootRouteImport - } - '/lazy': { - id: '/lazy' - path: '/lazy' - fullPath: '/lazy' - preLoaderRoute: typeof Char91lazyChar93RouteImport - parentRoute: typeof rootRouteImport - } - '/blog_': { - id: '/blog_' - path: '/blog_' - fullPath: '/blog_' - preLoaderRoute: typeof BlogRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -126,11 +112,25 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/blog_': { + id: '/blog_' + path: '/blog_' + fullPath: '/blog_' + preLoaderRoute: typeof BlogRouteImport + parentRoute: typeof rootRouteImport + } + '/lazy': { + id: '/lazy' + path: '/lazy' + fullPath: '/lazy' + preLoaderRoute: typeof Char91lazyChar93RouteImport + parentRoute: typeof rootRouteImport + } + '/route': { + id: '/route' + path: '/route' + fullPath: '/route' + preLoaderRoute: typeof Char91routeChar93RouteImport parentRoute: typeof rootRouteImport } } diff --git a/e2e/react-router/escaped-special-strings/tests/setup/global.setup.ts b/e2e/react-router/escaped-special-strings/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/escaped-special-strings/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-router/escaped-special-strings/tests/setup/global.teardown.ts b/e2e/react-router/escaped-special-strings/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/escaped-special-strings/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-router/generator-cli-only/package.json b/e2e/react-router/generator-cli-only/package.json index 6bbcccf4bd..159ba05500 100644 --- a/e2e/react-router/generator-cli-only/package.json +++ b/e2e/react-router/generator-cli-only/package.json @@ -8,7 +8,7 @@ "build": "tsr generate && vite build && tsc --noEmit", "preview": "vite preview", "start": "tsr generate && vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -17,7 +17,7 @@ "@tanstack/router-cli": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2" }, "devDependencies": { diff --git a/e2e/react-router/generator-cli-only/playwright.config.ts b/e2e/react-router/generator-cli-only/playwright.config.ts index c9d9a76ae7..4eead86444 100644 --- a/e2e/react-router/generator-cli-only/playwright.config.ts +++ b/e2e/react-router/generator-cli-only/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/generator-cli-only/src/posts.ts b/e2e/react-router/generator-cli-only/src/posts.ts index e859645746..f72d16fee3 100644 --- a/e2e/react-router/generator-cli-only/src/posts.ts +++ b/e2e/react-router/generator-cli-only/src/posts.ts @@ -8,11 +8,7 @@ type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/react-router/generator-cli-only/src/routeTree.gen.ts b/e2e/react-router/generator-cli-only/src/routeTree.gen.ts index 28cfbec8ed..9676858c7c 100644 --- a/e2e/react-router/generator-cli-only/src/routeTree.gen.ts +++ b/e2e/react-router/generator-cli-only/src/routeTree.gen.ts @@ -9,15 +9,20 @@ // 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 PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as PostsRouteRouteImport } from './routes/posts.route' -import { Route as IndexRouteImport } from './routes/index' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, @@ -27,11 +32,11 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, + } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -42,10 +47,11 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRouteRoute, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -53,12 +59,6 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -117,6 +117,13 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/_pathlessLayout': { id: '/_pathlessLayout' path: '' @@ -131,12 +138,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' + path: '' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/posts/': { id: '/posts/' @@ -152,12 +159,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRouteRoute } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -166,13 +173,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } } } diff --git a/e2e/react-router/generator-cli-only/tests/app.spec.ts b/e2e/react-router/generator-cli-only/tests/app.spec.ts index 5a83a314f2..ced5ac9310 100644 --- a/e2e/react-router/generator-cli-only/tests/app.spec.ts +++ b/e2e/react-router/generator-cli-only/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/generator-cli-only/tests/setup/global.setup.ts b/e2e/react-router/generator-cli-only/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/generator-cli-only/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-router/generator-cli-only/tests/setup/global.teardown.ts b/e2e/react-router/generator-cli-only/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/generator-cli-only/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-router/i18n-paraglide/package.json b/e2e/react-router/i18n-paraglide/package.json index 31a22eb66b..d1af160f10 100644 --- a/e2e/react-router/i18n-paraglide/package.json +++ b/e2e/react-router/i18n-paraglide/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -26,7 +26,26 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" + }, + "nx": { + "targets": { + "build": { + "outputs": [ + "...", + "{projectRoot}/src/paraglide", + "{projectRoot}/project.inlang/cache" + ] + }, + "test:e2e": { + "outputs": [ + "...", + "{projectRoot}/src/paraglide", + "{projectRoot}/project.inlang/cache" + ] + } + } } } diff --git a/e2e/react-router/i18n-paraglide/playwright.config.ts b/e2e/react-router/i18n-paraglide/playwright.config.ts index 91ef8fbd9f..8e94d5f9a1 100644 --- a/e2e/react-router/i18n-paraglide/playwright.config.ts +++ b/e2e/react-router/i18n-paraglide/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/issue-4759/index.html b/e2e/react-router/issue-4759/index.html new file mode 100644 index 0000000000..9609ea710b --- /dev/null +++ b/e2e/react-router/issue-4759/index.html @@ -0,0 +1,62 @@ + + + + + + Issue 4759 + + + +
+
HTML fallback
+
+ + + + diff --git a/e2e/react-router/issue-4759/package.json b/e2e/react-router/issue-4759/package.json new file mode 100644 index 0000000000..ee6a105ad5 --- /dev/null +++ b/e2e/react-router/issue-4759/package.json @@ -0,0 +1,26 @@ +{ + "name": "tanstack-router-e2e-react-issue-4759", + "private": true, + "type": "module", + "scripts": { + "build": "vite build && tsc --noEmit", + "dev": "vite --port 3000", + "dev:e2e": "vite", + "preview": "vite preview", + "start": "vite", + "test:e2e": "playwright test --project=chromium" + }, + "dependencies": { + "@tanstack/react-router": "workspace:^", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@playwright/test": "^1.61.0", + "@tanstack/router-e2e-utils": "workspace:^", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^6.0.1", + "vite": "^8.0.14" + } +} diff --git a/e2e/react-router/issue-4759/playwright.config.ts b/e2e/react-router/issue-4759/playwright.config.ts new file mode 100644 index 0000000000..a301f62881 --- /dev/null +++ b/e2e/react-router/issue-4759/playwright.config.ts @@ -0,0 +1,24 @@ +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}` + +export default defineConfig({ + testDir: './tests', + workers: 1, + reporter: [['line']], + use: { baseURL }, + webServer: { + command: `VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/react-router/issue-4759/src/main.tsx b/e2e/react-router/issue-4759/src/main.tsx new file mode 100644 index 0000000000..e251178045 --- /dev/null +++ b/e2e/react-router/issue-4759/src/main.tsx @@ -0,0 +1,74 @@ +import { StrictMode } from 'react' +import { createRoot } from 'react-dom/client' +import { + Outlet, + RouterProvider, + createRootRoute, + createRoute, + createRouter, +} from '@tanstack/react-router' + +const rootRoute = createRootRoute({ + context: () => ({ locale: 'en' }), + component: RootComponent, +}) +function RootComponent() { + const { locale } = rootRoute.useRouteContext() + return ( +
+ +
+ ) +} +const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + loader: () => new Promise((resolve) => setTimeout(resolve, 1_000)), + component: () =>
loaded
, +}) +const routePendingRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/route-pending', + pendingMs: 0, + pendingMinMs: 0, + pendingComponent: RoutePending, + loader: () => new Promise((resolve) => setTimeout(resolve, 1_000)), + component: () =>
loaded
, +}) +function RoutePending() { + const { locale } = routePendingRoute.useRouteContext() + return ( +
+ route pending +
+ ) +} +const router = createRouter({ + routeTree: rootRoute.addChildren([indexRoute, routePendingRoute]), +}) +const usesRoutePending = window.location.pathname === '/route-pending' +function DefaultPending() { + const { locale } = indexRoute.useRouteContext() + return ( +
+ default pending +
+ ) +} + +createRoot(document.getElementById('app')!).render( + +
+ +
+
, +) diff --git a/e2e/react-router/issue-4759/tests/issue-4759.spec.ts b/e2e/react-router/issue-4759/tests/issue-4759.spec.ts new file mode 100644 index 0000000000..95689010c8 --- /dev/null +++ b/e2e/react-router/issue-4759/tests/issue-4759.spec.ts @@ -0,0 +1,39 @@ +import { expect, test } from '@playwright/test' +import type { Page } from '@playwright/test' + +async function expectNoBlankFrame( + page: Page, + pendingSource: 'default' | 'route', +) { + const pending = page.locator( + `[data-state="pending"][data-pending-source="${pendingSource}"]`, + ) + await expect(pending).toBeVisible() + await expect(pending).toHaveAttribute('data-locale', 'en') + await expect(page.locator('[data-root-locale="en"]')).toBeVisible() + + const paintStates = await page.evaluate( + () => + (globalThis as typeof globalThis & { __paintStates: Array }) + .__paintStates, + ) + + expect(paintStates).toContain('pending') + expect(paintStates).not.toContain('shell') + expect(paintStates).not.toContain('empty') + await expect(page.locator('[data-state="loaded"]')).toBeVisible() +} + +test('#4759: the initial default pending component has no blank frame before it', async ({ + page, +}) => { + await page.goto('/') + await expectNoBlankFrame(page, 'default') +}) + +test('an initial route pending component has no blank frame before it', async ({ + page, +}) => { + await page.goto('/route-pending') + await expectNoBlankFrame(page, 'route') +}) diff --git a/e2e/react-router/issue-4759/tsconfig.json b/e2e/react-router/issue-4759/tsconfig.json new file mode 100644 index 0000000000..e4ba4788a3 --- /dev/null +++ b/e2e/react-router/issue-4759/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "strict": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "resolveJsonModule": true, + "skipLibCheck": true, + "types": ["vite/client"] + }, + "exclude": ["node_modules", "dist"] +} diff --git a/e2e/react-router/issue-4759/vite.config.ts b/e2e/react-router/issue-4759/vite.config.ts new file mode 100644 index 0000000000..9ffcc67574 --- /dev/null +++ b/e2e/react-router/issue-4759/vite.config.ts @@ -0,0 +1,6 @@ +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' + +export default defineConfig({ + plugins: [react()], +}) diff --git a/e2e/react-router/issue-7120/package.json b/e2e/react-router/issue-7120/package.json index a16155eb61..979b32556c 100644 --- a/e2e/react-router/issue-7120/package.json +++ b/e2e/react-router/issue-7120/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", diff --git a/e2e/react-router/issue-7120/playwright.config.ts b/e2e/react-router/issue-7120/playwright.config.ts index 61a995a815..a8ba116fb4 100644 --- a/e2e/react-router/issue-7120/playwright.config.ts +++ b/e2e/react-router/issue-7120/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -12,8 +11,8 @@ export default defineConfig({ use: { baseURL }, webServer: { command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, projects: [ diff --git a/e2e/react-router/issue-7120/src/routeTree.gen.ts b/e2e/react-router/issue-7120/src/routeTree.gen.ts index fc671589c7..e8c6d92110 100644 --- a/e2e/react-router/issue-7120/src/routeTree.gen.ts +++ b/e2e/react-router/issue-7120/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 PostsRouteImport } from './routes/posts' import { Route as IndexRouteImport } from './routes/index' +import { Route as PostsRouteImport } from './routes/posts' -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any).lazy(() => import('./routes/posts.lazy').then((d) => d.Route)) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any).lazy(() => import('./routes/posts.lazy').then((d) => d.Route)) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/e2e/react-router/issue-7457/package.json b/e2e/react-router/issue-7457/package.json index 3220a4dbb4..838f5173e2 100644 --- a/e2e/react-router/issue-7457/package.json +++ b/e2e/react-router/issue-7457/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-query": "^5.99.0", diff --git a/e2e/react-router/issue-7457/playwright.config.ts b/e2e/react-router/issue-7457/playwright.config.ts index 61a995a815..a8ba116fb4 100644 --- a/e2e/react-router/issue-7457/playwright.config.ts +++ b/e2e/react-router/issue-7457/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -12,8 +11,8 @@ export default defineConfig({ use: { baseURL }, webServer: { command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, projects: [ diff --git a/e2e/react-router/issue-7457/src/routeTree.gen.ts b/e2e/react-router/issue-7457/src/routeTree.gen.ts index 72a8f23384..04a2c94ce8 100644 --- a/e2e/react-router/issue-7457/src/routeTree.gen.ts +++ b/e2e/react-router/issue-7457/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 AnotherRouteImport } from './routes/another' import { Route as IndexRouteImport } from './routes/index' +import { Route as AnotherRouteImport } from './routes/another' -const AnotherRoute = AnotherRouteImport.update({ - id: '/another', - path: '/another', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AnotherRoute = AnotherRouteImport.update({ + id: '/another', + path: '/another', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/another': { - id: '/another' - path: '/another' - fullPath: '/another' - preLoaderRoute: typeof AnotherRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/another': { + id: '/another' + path: '/another' + fullPath: '/another' + preLoaderRoute: typeof AnotherRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/e2e/react-router/js-only-file-based/package.json b/e2e/react-router/js-only-file-based/package.json index d18d4da143..39742d9c84 100644 --- a/e2e/react-router/js-only-file-based/package.json +++ b/e2e/react-router/js-only-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -16,7 +16,7 @@ "@tanstack/react-router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2" }, "devDependencies": { diff --git a/e2e/react-router/js-only-file-based/playwright.config.ts b/e2e/react-router/js-only-file-based/playwright.config.ts index 4f93bc1413..0925936d55 100644 --- a/e2e/react-router/js-only-file-based/playwright.config.ts +++ b/e2e/react-router/js-only-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -18,18 +13,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/js-only-file-based/src/posts.js b/e2e/react-router/js-only-file-based/src/posts.js index 979e5e381c..36c1c281f6 100644 --- a/e2e/react-router/js-only-file-based/src/posts.js +++ b/e2e/react-router/js-only-file-based/src/posts.js @@ -2,11 +2,7 @@ import axios from 'redaxios' export class NotFoundError extends Error {} -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/react-router/js-only-file-based/src/routeTree.gen.js b/e2e/react-router/js-only-file-based/src/routeTree.gen.js index f2d42e5a6c..80683abb30 100644 --- a/e2e/react-router/js-only-file-based/src/routeTree.gen.js +++ b/e2e/react-router/js-only-file-based/src/routeTree.gen.js @@ -9,15 +9,20 @@ // 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 PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as PostsRouteRouteImport } from './routes/posts.route' -import { Route as IndexRouteImport } from './routes/index' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +}) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, @@ -27,11 +32,11 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, }) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -}) +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, + }) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -42,10 +47,11 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRouteRoute, }) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, }) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -53,12 +59,6 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, }) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - }) const PostsRouteRouteChildren = { PostsPostIdRoute: PostsPostIdRoute, diff --git a/e2e/react-router/js-only-file-based/tests/app.spec.ts b/e2e/react-router/js-only-file-based/tests/app.spec.ts index 5a83a314f2..ced5ac9310 100644 --- a/e2e/react-router/js-only-file-based/tests/app.spec.ts +++ b/e2e/react-router/js-only-file-based/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/js-only-file-based/tests/setup/global.setup.ts b/e2e/react-router/js-only-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/js-only-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-router/js-only-file-based/tests/setup/global.teardown.ts b/e2e/react-router/js-only-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/js-only-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-router/match-params/package.json b/e2e/react-router/match-params/package.json index 3282e5e5c2..908be67a9d 100644 --- a/e2e/react-router/match-params/package.json +++ b/e2e/react-router/match-params/package.json @@ -6,7 +6,7 @@ "dev": "vite --port 3000", "build": "vite build && tsc --noEmit", "preview": "vite preview", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", diff --git a/e2e/react-router/match-params/playwright.config.ts b/e2e/react-router/match-params/playwright.config.ts index 246cf40060..9e8c1fab2b 100644 --- a/e2e/react-router/match-params/playwright.config.ts +++ b/e2e/react-router/match-params/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -14,8 +13,8 @@ export default defineConfig({ }, webServer: { command: `pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, projects: [ diff --git a/e2e/react-router/react-compiler/index.html b/e2e/react-router/react-compiler/index.html new file mode 100644 index 0000000000..0c5b6b471c --- /dev/null +++ b/e2e/react-router/react-compiler/index.html @@ -0,0 +1,12 @@ + + + + + + React Compiler useMatchRoute test + + +
+ + + diff --git a/e2e/react-router/react-compiler/package.json b/e2e/react-router/react-compiler/package.json new file mode 100644 index 0000000000..82e6fbf86b --- /dev/null +++ b/e2e/react-router/react-compiler/package.json @@ -0,0 +1,29 @@ +{ + "name": "tanstack-router-e2e-react-compiler", + "private": true, + "type": "module", + "scripts": { + "dev": "vite --port 3000", + "dev:e2e": "vite", + "build": "vite build && tsc --noEmit", + "preview": "vite preview", + "start": "vite", + "test:e2e": "playwright test --project=chromium" + }, + "dependencies": { + "@tanstack/react-router": "workspace:^", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@babel/core": "^7.29.0", + "@playwright/test": "^1.61.0", + "@rolldown/plugin-babel": "^0.2.0", + "@tanstack/router-e2e-utils": "workspace:^", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^6.0.1", + "babel-plugin-react-compiler": "^1.0.0", + "vite": "^8.0.14" + } +} diff --git a/e2e/react-router/react-compiler/playwright.config.ts b/e2e/react-router/react-compiler/playwright.config.ts new file mode 100644 index 0000000000..a8ba116fb4 --- /dev/null +++ b/e2e/react-router/react-compiler/playwright.config.ts @@ -0,0 +1,24 @@ +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}` + +export default defineConfig({ + testDir: './tests', + workers: 1, + reporter: [['line']], + use: { baseURL }, + webServer: { + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/react-router/react-compiler/src/main.tsx b/e2e/react-router/react-compiler/src/main.tsx new file mode 100644 index 0000000000..e6e549da83 --- /dev/null +++ b/e2e/react-router/react-compiler/src/main.tsx @@ -0,0 +1,73 @@ +import { StrictMode } from 'react' +import { createRoot } from 'react-dom/client' +import { + Link, + Outlet, + RouterProvider, + createRootRoute, + createRoute, + createRouter, + linkOptions, + useMatchRoute, +} from '@tanstack/react-router' + +const links = linkOptions([ + { to: '/home', label: 'Home' }, + { to: '/about', label: 'About' }, +]) + +function useRouteName() { + const matchRoute = useMatchRoute() + + return links.find((link) => matchRoute(link))?.label ?? 'Unknown' +} + +function RootComponent() { + const matchedRoute = useRouteName() + + return ( + <> + +

+ Matched route: {matchedRoute} +

+ + + ) +} + +const rootRoute = createRootRoute({ component: RootComponent }) +const homeRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/home', +}) +const aboutRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/about', +}) +const router = createRouter({ + routeTree: rootRoute.addChildren([homeRoute, aboutRoute]), +}) + +declare module '@tanstack/react-router' { + interface Register { + router: typeof router + } +} + +const rootElement = document.getElementById('app') +if (!rootElement) { + throw new Error('Root element not found') +} + +createRoot(rootElement).render( + + + , +) diff --git a/e2e/react-router/react-compiler/tests/use-match-route.spec.ts b/e2e/react-router/react-compiler/tests/use-match-route.spec.ts new file mode 100644 index 0000000000..b800e3c908 --- /dev/null +++ b/e2e/react-router/react-compiler/tests/use-match-route.spec.ts @@ -0,0 +1,16 @@ +import { expect, test } from '@playwright/test' + +test('useMatchRoute updates after navigation with React Compiler', async ({ + page, +}) => { + await page.goto('/home') + await expect(page.getByTestId('matched-route')).toHaveText('Home') + + await page.getByRole('link', { name: 'About' }).click() + await expect(page).toHaveURL(/\/about$/) + await expect(page.getByTestId('matched-route')).toHaveText('About') + + await page.getByRole('link', { name: 'Home' }).click() + await expect(page).toHaveURL(/\/home$/) + await expect(page.getByTestId('matched-route')).toHaveText('Home') +}) diff --git a/e2e/react-router/react-compiler/tsconfig.json b/e2e/react-router/react-compiler/tsconfig.json new file mode 100644 index 0000000000..4f6089bc08 --- /dev/null +++ b/e2e/react-router/react-compiler/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "resolveJsonModule": true, + "allowJs": true, + "skipLibCheck": true, + "types": ["vite/client"] + }, + "exclude": ["node_modules", "dist"] +} diff --git a/e2e/react-router/react-compiler/vite.config.js b/e2e/react-router/react-compiler/vite.config.js new file mode 100644 index 0000000000..b4478aced4 --- /dev/null +++ b/e2e/react-router/react-compiler/vite.config.js @@ -0,0 +1,7 @@ +import { defineConfig } from 'vite' +import react, { reactCompilerPreset } from '@vitejs/plugin-react' +import babel from '@rolldown/plugin-babel' + +export default defineConfig({ + plugins: [react(), babel({ presets: [reactCompilerPreset()] })], +}) diff --git a/e2e/react-router/rspack-basic-file-based/package.json b/e2e/react-router/rspack-basic-file-based/package.json index f54f8f83ca..5ec9ed9862 100644 --- a/e2e/react-router/rspack-basic-file-based/package.json +++ b/e2e/react-router/rspack-basic-file-based/package.json @@ -7,18 +7,18 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1" + "redaxios": "catalog:" }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.0.11", + "@rsbuild/core": "^2.3.1", "@rsbuild/plugin-react": "^2.0.0", "@tailwindcss/postcss": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", @@ -27,6 +27,7 @@ "@types/react-dom": "^19.0.3", "postcss": "^8.5.1", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2" } } diff --git a/e2e/react-router/rspack-basic-file-based/playwright.config.ts b/e2e/react-router/rspack-basic-file-based/playwright.config.ts index decceaef2f..4eead86444 100644 --- a/e2e/react-router/rspack-basic-file-based/playwright.config.ts +++ b/e2e/react-router/rspack-basic-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `PUBLIC_NODE_ENV="test" PUBLIC_EXTERNAL_PORT=${EXTERNAL_PORT} PUBLIC_SERVER_PORT=${PORT} pnpm build && PUBLIC_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/rspack-basic-file-based/src/posts.tsx b/e2e/react-router/rspack-basic-file-based/src/posts.tsx index a1225b7fe7..97c96d77eb 100644 --- a/e2e/react-router/rspack-basic-file-based/src/posts.tsx +++ b/e2e/react-router/rspack-basic-file-based/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.PUBLIC_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-router/rspack-basic-file-based/tests/app.spec.ts b/e2e/react-router/rspack-basic-file-based/tests/app.spec.ts index 10beff655f..d230263bfe 100644 --- a/e2e/react-router/rspack-basic-file-based/tests/app.spec.ts +++ b/e2e/react-router/rspack-basic-file-based/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/rspack-basic-file-based/tests/setup/global.setup.ts b/e2e/react-router/rspack-basic-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/rspack-basic-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-router/rspack-basic-file-based/tests/setup/global.teardown.ts b/e2e/react-router/rspack-basic-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/rspack-basic-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/package.json b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/package.json index 18e7851ac9..30c62d0af1 100644 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/package.json +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/package.json @@ -7,18 +7,18 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1" + "redaxios": "catalog:" }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.0.11", + "@rsbuild/core": "^2.3.1", "@rsbuild/plugin-react": "^2.0.0", "@tailwindcss/postcss": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", @@ -28,6 +28,7 @@ "@types/react-dom": "^19.0.3", "postcss": "^8.5.1", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2" } } diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts index bf3adc082c..1c1d021f2f 100644 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `PUBLIC_NODE_ENV="test" PUBLIC_EXTERNAL_PORT=${EXTERNAL_PORT} PUBLIC_SERVER_PORT=${PORT} pnpm build && PUBLIC_SERVER_PORT=${PORT} pnpm start --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm start --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx index b196982420..cc3cb0f9c8 100644 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.PUBLIC_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts index a689f459e3..8b808782f6 100644 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/package.json b/e2e/react-router/scroll-restoration-sandbox-vite/package.json index a7fc908019..51e9e70cc5 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/package.json +++ b/e2e/react-router/scroll-restoration-sandbox-vite/package.json @@ -11,7 +11,7 @@ "start": "vite", "test:e2e:browser": "VITE_APP_HISTORY=browser playwright test --config=playwright.browser.config.ts --project=chromium", "test:e2e:hash": "VITE_APP_HISTORY=hash playwright test --config=playwright.hash.config.ts --project=chromium", - "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:browser && pnpm run test:e2e:hash" + "test:e2e": "pnpm run test:e2e:browser && pnpm run test:e2e:hash" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -20,7 +20,7 @@ "@tanstack/router-plugin": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, @@ -31,5 +31,15 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "vite": "^8.0.14" + }, + "nx": { + "targets": { + "test:e2e": { + "outputs": [ + "...", + "{projectRoot}/dist-hash" + ] + } + } } } diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts b/e2e/react-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts index 972124647c..eb31d94080 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts +++ b/e2e/react-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts @@ -1,15 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, - resolveRuntimeSuffix, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort( - packageJson.name + `-${resolveRuntimeSuffix('browser')}`, -) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,18 +13,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=browser pnpm build && VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `VITE_APP_HISTORY=browser pnpm build && VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts b/e2e/react-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts index a6fa77afbf..6b160e3908 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts +++ b/e2e/react-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts @@ -1,15 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, - resolveRuntimeSuffix, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort( - packageJson.name + `-${resolveRuntimeSuffix('hash')}`, -) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,18 +13,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=hash vite build --outDir dist-hash && VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `VITE_APP_HISTORY=hash vite build --outDir dist-hash && VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx b/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx index e45ef52969..c4a2d0dcca 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx +++ b/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx @@ -10,11 +10,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export class PostNotFoundError extends Error {} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts b/e2e/react-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts index a4dc8750b3..0c6823c368 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts +++ b/e2e/react-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts @@ -12,12 +12,12 @@ import { createFileRoute } from '@tanstack/react-router' import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as testsPageWithSearchRouteImport } from './routes/(tests)/page-with-search' -import { Route as testsNormalPageRouteImport } from './routes/(tests)/normal-page' -import { Route as testsLazyWithLoaderPageRouteImport } from './routes/(tests)/lazy-with-loader-page' -import { Route as testsLazyPageRouteImport } from './routes/(tests)/lazy-page' -import { Route as testsIssue7040TargetRouteImport } from './routes/(tests)/issue-7040-target' import { Route as testsIssue7040SourceRouteImport } from './routes/(tests)/issue-7040-source' +import { Route as testsIssue7040TargetRouteImport } from './routes/(tests)/issue-7040-target' +import { Route as testsLazyPageRouteImport } from './routes/(tests)/lazy-page' +import { Route as testsLazyWithLoaderPageRouteImport } from './routes/(tests)/lazy-with-loader-page' +import { Route as testsNormalPageRouteImport } from './routes/(tests)/normal-page' +import { Route as testsPageWithSearchRouteImport } from './routes/(tests)/page-with-search' const testsVirtualPageLazyRouteImport = createFileRoute( '/(tests)/virtual-page', @@ -28,23 +28,23 @@ const IndexRoute = IndexRouteImport.update({ path: '/', getParentRoute: () => rootRouteImport, } as any) -const testsVirtualPageLazyRoute = testsVirtualPageLazyRouteImport +const testsIssue7040SourceRoute = testsIssue7040SourceRouteImport.update({ + id: '/(tests)/issue-7040-source', + path: '/issue-7040-source', + getParentRoute: () => rootRouteImport, +} as any) +const testsIssue7040TargetRoute = testsIssue7040TargetRouteImport.update({ + id: '/(tests)/issue-7040-target', + path: '/issue-7040-target', + getParentRoute: () => rootRouteImport, +} as any) +const testsLazyPageRoute = testsLazyPageRouteImport .update({ - id: '/(tests)/virtual-page', - path: '/virtual-page', + id: '/(tests)/lazy-page', + path: '/lazy-page', getParentRoute: () => rootRouteImport, } as any) - .lazy(() => import('./routes/(tests)/virtual-page.lazy').then((d) => d.Route)) -const testsPageWithSearchRoute = testsPageWithSearchRouteImport.update({ - id: '/(tests)/page-with-search', - path: '/page-with-search', - getParentRoute: () => rootRouteImport, -} as any) -const testsNormalPageRoute = testsNormalPageRouteImport.update({ - id: '/(tests)/normal-page', - path: '/normal-page', - getParentRoute: () => rootRouteImport, -} as any) + .lazy(() => import('./routes/(tests)/lazy-page.lazy').then((d) => d.Route)) const testsLazyWithLoaderPageRoute = testsLazyWithLoaderPageRouteImport .update({ id: '/(tests)/lazy-with-loader-page', @@ -54,23 +54,23 @@ const testsLazyWithLoaderPageRoute = testsLazyWithLoaderPageRouteImport .lazy(() => import('./routes/(tests)/lazy-with-loader-page.lazy').then((d) => d.Route), ) -const testsLazyPageRoute = testsLazyPageRouteImport +const testsNormalPageRoute = testsNormalPageRouteImport.update({ + id: '/(tests)/normal-page', + path: '/normal-page', + getParentRoute: () => rootRouteImport, +} as any) +const testsPageWithSearchRoute = testsPageWithSearchRouteImport.update({ + id: '/(tests)/page-with-search', + path: '/page-with-search', + getParentRoute: () => rootRouteImport, +} as any) +const testsVirtualPageLazyRoute = testsVirtualPageLazyRouteImport .update({ - id: '/(tests)/lazy-page', - path: '/lazy-page', + id: '/(tests)/virtual-page', + path: '/virtual-page', getParentRoute: () => rootRouteImport, } as any) - .lazy(() => import('./routes/(tests)/lazy-page.lazy').then((d) => d.Route)) -const testsIssue7040TargetRoute = testsIssue7040TargetRouteImport.update({ - id: '/(tests)/issue-7040-target', - path: '/issue-7040-target', - getParentRoute: () => rootRouteImport, -} as any) -const testsIssue7040SourceRoute = testsIssue7040SourceRouteImport.update({ - id: '/(tests)/issue-7040-source', - path: '/issue-7040-source', - getParentRoute: () => rootRouteImport, -} as any) + .lazy(() => import('./routes/(tests)/virtual-page.lazy').then((d) => d.Route)) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -156,39 +156,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/(tests)/virtual-page': { - id: '/(tests)/virtual-page' - path: '/virtual-page' - fullPath: '/virtual-page' - preLoaderRoute: typeof testsVirtualPageLazyRouteImport - parentRoute: typeof rootRouteImport - } - '/(tests)/page-with-search': { - id: '/(tests)/page-with-search' - path: '/page-with-search' - fullPath: '/page-with-search' - preLoaderRoute: typeof testsPageWithSearchRouteImport - parentRoute: typeof rootRouteImport - } - '/(tests)/normal-page': { - id: '/(tests)/normal-page' - path: '/normal-page' - fullPath: '/normal-page' - preLoaderRoute: typeof testsNormalPageRouteImport - parentRoute: typeof rootRouteImport - } - '/(tests)/lazy-with-loader-page': { - id: '/(tests)/lazy-with-loader-page' - path: '/lazy-with-loader-page' - fullPath: '/lazy-with-loader-page' - preLoaderRoute: typeof testsLazyWithLoaderPageRouteImport - parentRoute: typeof rootRouteImport - } - '/(tests)/lazy-page': { - id: '/(tests)/lazy-page' - path: '/lazy-page' - fullPath: '/lazy-page' - preLoaderRoute: typeof testsLazyPageRouteImport + '/(tests)/issue-7040-source': { + id: '/(tests)/issue-7040-source' + path: '/issue-7040-source' + fullPath: '/issue-7040-source' + preLoaderRoute: typeof testsIssue7040SourceRouteImport parentRoute: typeof rootRouteImport } '/(tests)/issue-7040-target': { @@ -198,11 +170,39 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof testsIssue7040TargetRouteImport parentRoute: typeof rootRouteImport } - '/(tests)/issue-7040-source': { - id: '/(tests)/issue-7040-source' - path: '/issue-7040-source' - fullPath: '/issue-7040-source' - preLoaderRoute: typeof testsIssue7040SourceRouteImport + '/(tests)/lazy-page': { + id: '/(tests)/lazy-page' + path: '/lazy-page' + fullPath: '/lazy-page' + preLoaderRoute: typeof testsLazyPageRouteImport + parentRoute: typeof rootRouteImport + } + '/(tests)/lazy-with-loader-page': { + id: '/(tests)/lazy-with-loader-page' + path: '/lazy-with-loader-page' + fullPath: '/lazy-with-loader-page' + preLoaderRoute: typeof testsLazyWithLoaderPageRouteImport + parentRoute: typeof rootRouteImport + } + '/(tests)/normal-page': { + id: '/(tests)/normal-page' + path: '/normal-page' + fullPath: '/normal-page' + preLoaderRoute: typeof testsNormalPageRouteImport + parentRoute: typeof rootRouteImport + } + '/(tests)/page-with-search': { + id: '/(tests)/page-with-search' + path: '/page-with-search' + fullPath: '/page-with-search' + preLoaderRoute: typeof testsPageWithSearchRouteImport + parentRoute: typeof rootRouteImport + } + '/(tests)/virtual-page': { + id: '/(tests)/virtual-page' + path: '/virtual-page' + fullPath: '/virtual-page' + preLoaderRoute: typeof testsVirtualPageLazyRouteImport parentRoute: typeof rootRouteImport } } diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tests/app.spec.ts b/e2e/react-router/scroll-restoration-sandbox-vite/tests/app.spec.ts index 9c2d944dd5..e396c28686 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/tests/app.spec.ts +++ b/e2e/react-router/scroll-restoration-sandbox-vite/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' import { linkOptions } from '@tanstack/react-router' import { toRuntimePath } from '@tanstack/router-e2e-utils' diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tests/issue-7040.repro.spec.ts b/e2e/react-router/scroll-restoration-sandbox-vite/tests/issue-7040.repro.spec.ts index db335f8e2e..2db25517c8 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/tests/issue-7040.repro.spec.ts +++ b/e2e/react-router/scroll-restoration-sandbox-vite/tests/issue-7040.repro.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' import type { Page } from '@playwright/test' import { toRuntimePath } from '@tanstack/router-e2e-utils' @@ -26,7 +27,7 @@ type ReproAttempt = { async function openFreshSourcePage(page: Page) { await page.goto(toRuntimePath('/issue-7040-source')) - await page.waitForLoadState('networkidle') + await expect(page.getByTestId('issue-7040-source-top')).toBeVisible() await page.evaluate(() => { sessionStorage.clear() @@ -34,7 +35,7 @@ async function openFreshSourcePage(page: Page) { }) await page.reload() - await page.waitForLoadState('networkidle') + await expect(page.getByTestId('issue-7040-source-top')).toBeVisible() } async function fastScrollSourcePage(page: Page) { @@ -96,7 +97,7 @@ async function clickTargetLinkImmediatelyAfterScroll(page: Page) { async function waitForTargetPageToSettle(page: Page) { await page.waitForURL('**/issue-7040-target') - await page.waitForLoadState('networkidle') + await expect(page.getByTestId('issue-7040-target-top')).toBeVisible() await page.waitForFunction(() => window.scrollY === 0) } diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts b/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts b/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tsconfig.json b/e2e/react-router/scroll-restoration-sandbox-vite/tsconfig.json index f33b5a7aa3..5d58406b2e 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/tsconfig.json +++ b/e2e/react-router/scroll-restoration-sandbox-vite/tsconfig.json @@ -11,5 +11,5 @@ "allowJs": true, "types": ["vite/client", "node"] }, - "exclude": ["node_modules", "dist"] + "exclude": ["node_modules", "dist", "dist-hash"] } diff --git a/e2e/react-router/sentry-integration/package.json b/e2e/react-router/sentry-integration/package.json index e275758b83..5ebbdf31d9 100644 --- a/e2e/react-router/sentry-integration/package.json +++ b/e2e/react-router/sentry-integration/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@sentry/react": "^10.32.0", @@ -19,7 +19,7 @@ "@tanstack/react-router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2" }, "devDependencies": { diff --git a/e2e/react-router/sentry-integration/playwright.config.ts b/e2e/react-router/sentry-integration/playwright.config.ts index 0c5cee43e4..6a684ac89e 100644 --- a/e2e/react-router/sentry-integration/playwright.config.ts +++ b/e2e/react-router/sentry-integration/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/view-transitions/package.json b/e2e/react-router/view-transitions/package.json index 1f068d690a..e2d7a181e1 100644 --- a/e2e/react-router/view-transitions/package.json +++ b/e2e/react-router/view-transitions/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -17,7 +17,7 @@ "@tanstack/router-plugin": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, @@ -27,7 +27,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/e2e/react-router/view-transitions/playwright.config.ts b/e2e/react-router/view-transitions/playwright.config.ts index c5de6b5611..4eead86444 100644 --- a/e2e/react-router/view-transitions/playwright.config.ts +++ b/e2e/react-router/view-transitions/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -22,13 +17,10 @@ export default defineConfig({ baseURL, }, - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - webServer: { - command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-router/view-transitions/src/routeTree.gen.ts b/e2e/react-router/view-transitions/src/routeTree.gen.ts index 20ee76a1a5..8982fca68f 100644 --- a/e2e/react-router/view-transitions/src/routeTree.gen.ts +++ b/e2e/react-router/view-transitions/src/routeTree.gen.ts @@ -9,16 +9,16 @@ // 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 HowItWorksRouteImport } from './routes/how-it-works' -import { Route as ExploreRouteImport } from './routes/explore' -import { Route as PostsRouteRouteImport } from './routes/posts.route' import { Route as IndexRouteImport } from './routes/index' +import { Route as ExploreRouteImport } from './routes/explore' +import { Route as HowItWorksRouteImport } from './routes/how-it-works' +import { Route as PostsRouteRouteImport } from './routes/posts.route' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -const HowItWorksRoute = HowItWorksRouteImport.update({ - id: '/how-it-works', - path: '/how-it-works', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const ExploreRoute = ExploreRouteImport.update({ @@ -26,16 +26,16 @@ const ExploreRoute = ExploreRouteImport.update({ path: '/explore', getParentRoute: () => rootRouteImport, } as any) +const HowItWorksRoute = HowItWorksRouteImport.update({ + id: '/how-it-works', + path: '/how-it-works', + getParentRoute: () => rootRouteImport, +} as any) const PostsRouteRoute = PostsRouteRouteImport.update({ id: '/posts', path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -101,11 +101,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/how-it-works': { - id: '/how-it-works' - path: '/how-it-works' - fullPath: '/how-it-works' - preLoaderRoute: typeof HowItWorksRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/explore': { @@ -115,6 +115,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ExploreRouteImport parentRoute: typeof rootRouteImport } + '/how-it-works': { + id: '/how-it-works' + path: '/how-it-works' + fullPath: '/how-it-works' + preLoaderRoute: typeof HowItWorksRouteImport + parentRoute: typeof rootRouteImport + } '/posts': { id: '/posts' path: '/posts' @@ -122,13 +129,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/posts/': { id: '/posts/' path: '/' diff --git a/e2e/react-router/view-transitions/tests/app.spec.ts b/e2e/react-router/view-transitions/tests/app.spec.ts index 472bd6ed0b..6c1ccf1a6e 100644 --- a/e2e/react-router/view-transitions/tests/app.spec.ts +++ b/e2e/react-router/view-transitions/tests/app.spec.ts @@ -1,4 +1,4 @@ -import { test } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-router/view-transitions/tests/setup/global.setup.ts b/e2e/react-router/view-transitions/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-router/view-transitions/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-router/view-transitions/tests/setup/global.teardown.ts b/e2e/react-router/view-transitions/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-router/view-transitions/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-start/basic-auth/package.json b/e2e/react-start/basic-auth/package.json index 5976695006..f7ff609e76 100644 --- a/e2e/react-start/basic-auth/package.json +++ b/e2e/react-start/basic-auth/package.json @@ -10,7 +10,7 @@ "preview": "vite preview", "start": "node .output/server/index.mjs", "prisma-generate": "prisma generate", - "test:e2e": "exit 0; rm -rf port*.txt; pnpm run prisma-generate && playwright test --project=chromium" + "test:e2e": "exit 0; pnpm run prisma-generate && playwright test --project=chromium" }, "dependencies": { "@libsql/client": "^0.15.15", @@ -19,9 +19,10 @@ "@tanstack/react-router": "workspace:^", "@tanstack/react-router-devtools": "workspace:^", "@tanstack/react-start": "workspace:^", + "iron-session": "^9.0.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0" }, "devDependencies": { @@ -35,7 +36,8 @@ "dotenv": "^17.2.3", "prisma": "^7.0.0", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/e2e/react-start/basic-auth/playwright.config.ts b/e2e/react-start/basic-auth/playwright.config.ts index 18b8905468..82678ac00b 100644 --- a/e2e/react-start/basic-auth/playwright.config.ts +++ b/e2e/react-start/basic-auth/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-start/basic-auth/src/routeTree.gen.ts b/e2e/react-start/basic-auth/src/routeTree.gen.ts index 6be84444eb..998d34a709 100644 --- a/e2e/react-start/basic-auth/src/routeTree.gen.ts +++ b/e2e/react-start/basic-auth/src/routeTree.gen.ts @@ -9,23 +9,22 @@ // 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 SignupRouteImport } from './routes/signup' -import { Route as LogoutRouteImport } from './routes/logout' -import { Route as LoginRouteImport } from './routes/login' -import { Route as AuthedRouteImport } from './routes/_authed' import { Route as IndexRouteImport } from './routes/index' +import { Route as AuthedRouteImport } from './routes/_authed' +import { Route as LoginRouteImport } from './routes/login' +import { Route as LogoutRouteImport } from './routes/logout' +import { Route as SignupRouteImport } from './routes/signup' import { Route as AuthedPostsRouteImport } from './routes/_authed/posts' import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' -const SignupRoute = SignupRouteImport.update({ - id: '/signup', - path: '/signup', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', getParentRoute: () => rootRouteImport, } as any) const LoginRoute = LoginRouteImport.update({ @@ -33,13 +32,14 @@ const LoginRoute = LoginRouteImport.update({ path: '/login', getParentRoute: () => rootRouteImport, } as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', +const LogoutRoute = LogoutRouteImport.update({ + id: '/logout', + path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SignupRoute = SignupRouteImport.update({ + id: '/signup', + path: '/signup', getParentRoute: () => rootRouteImport, } as any) const AuthedPostsRoute = AuthedPostsRouteImport.update({ @@ -120,25 +120,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/signup': { - id: '/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof SignupRouteImport - parentRoute: typeof rootRouteImport - } - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport - parentRoute: typeof rootRouteImport - } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_authed': { @@ -148,11 +134,25 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthedRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport + } + '/logout': { + id: '/logout' + path: '/logout' + fullPath: '/logout' + preLoaderRoute: typeof LogoutRouteImport + parentRoute: typeof rootRouteImport + } + '/signup': { + id: '/signup' + path: '/signup' + fullPath: '/signup' + preLoaderRoute: typeof SignupRouteImport parentRoute: typeof rootRouteImport } '/_authed/posts': { diff --git a/e2e/react-start/basic-auth/src/routes/__root.tsx b/e2e/react-start/basic-auth/src/routes/__root.tsx index 76e5f8b1d6..fb7868435d 100644 --- a/e2e/react-start/basic-auth/src/routes/__root.tsx +++ b/e2e/react-start/basic-auth/src/routes/__root.tsx @@ -14,18 +14,18 @@ import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' import { NotFound } from '~/components/NotFound.js' import appCss from '~/styles/app.css?url' import { seo } from '~/utils/seo.js' -import { useAppSession } from '~/utils/session.js' +import { getAppSession } from '~/utils/session.js' const fetchUser = createServerFn({ method: 'GET' }).handler(async () => { // We need to auth on the server so we have access to secure cookies - const session = await useAppSession() + const session = await getAppSession() - if (!session.data.userEmail) { + if (!session.userEmail) { return null } return { - email: session.data.userEmail, + email: session.userEmail, } }) diff --git a/e2e/react-start/basic-auth/src/routes/_authed.tsx b/e2e/react-start/basic-auth/src/routes/_authed.tsx index c457cf5e57..fe73185136 100644 --- a/e2e/react-start/basic-auth/src/routes/_authed.tsx +++ b/e2e/react-start/basic-auth/src/routes/_authed.tsx @@ -3,7 +3,7 @@ import { createServerFn } from '@tanstack/react-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { Login } from '~/components/Login' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST', @@ -37,12 +37,11 @@ export const loginFn = createServerFn({ } // Create a session - const session = await useAppSession() + const session = await getAppSession() // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + session.userEmail = user.email + await session.save() }) export const Route = createFileRoute('/_authed')({ @@ -52,7 +51,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error.message === 'Not authenticated') { + if (error instanceof Error && error.message === 'Not authenticated') { return } diff --git a/e2e/react-start/basic-auth/src/routes/logout.tsx b/e2e/react-start/basic-auth/src/routes/logout.tsx index a08f9c737e..0f86b0d4e3 100644 --- a/e2e/react-start/basic-auth/src/routes/logout.tsx +++ b/e2e/react-start/basic-auth/src/routes/logout.tsx @@ -1,12 +1,12 @@ import { redirect, createFileRoute } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await useAppSession() + const session = await getAppSession() - session.clear() + session.destroy() throw redirect({ href: '/', diff --git a/e2e/react-start/basic-auth/src/routes/signup.tsx b/e2e/react-start/basic-auth/src/routes/signup.tsx index 817362dc05..d7d5d40129 100644 --- a/e2e/react-start/basic-auth/src/routes/signup.tsx +++ b/e2e/react-start/basic-auth/src/routes/signup.tsx @@ -4,7 +4,7 @@ import { createServerFn, useServerFn } from '@tanstack/react-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { useMutation } from '~/hooks/useMutation' import { Auth } from '~/components/Auth' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' export const signupFn = createServerFn({ method: 'POST', @@ -24,7 +24,7 @@ export const signupFn = createServerFn({ const password = await hashPassword(payload.password) // Create a session - const session = await useAppSession() + const session = await getAppSession() if (found) { if (found.password !== password) { @@ -36,9 +36,8 @@ export const signupFn = createServerFn({ } // Store the user's email in the session - await session.update({ - userEmail: found.email, - }) + session.userEmail = found.email + await session.save() // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -55,9 +54,8 @@ export const signupFn = createServerFn({ }) // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + session.userEmail = user.email + await session.save() // Redirect to the prev page stored in the "redirect" search param throw redirect({ diff --git a/e2e/react-start/basic-auth/src/utils/session.ts b/e2e/react-start/basic-auth/src/utils/session.ts index c38bac1e48..f1deacf85b 100644 --- a/e2e/react-start/basic-auth/src/utils/session.ts +++ b/e2e/react-start/basic-auth/src/utils/session.ts @@ -1,13 +1,25 @@ -// src/services/session.server.ts -import { useSession } from '@tanstack/react-start/server' +import { getIronSession } from 'iron-session' +import { getCookie, setCookie } from '@tanstack/react-start/server' import type { User } from '@prisma/client' type SessionUser = { userEmail: User['email'] } -export function useAppSession() { - return useSession({ - password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', - }) +export function getAppSession() { + return getIronSession( + { read: getCookie, write: setCookie }, + { + cookieName: 'test-auth-session', + // This fixture only runs locally with test credentials. + password: 'local-e2e-only-session-password-at-least-32-characters', + ttl: 60 * 60, + cookieOptions: { + httpOnly: true, + secure: false, + sameSite: 'lax', + path: '/', + }, + }, + ) } diff --git a/e2e/react-start/basic-cloudflare/package.json b/e2e/react-start/basic-cloudflare/package.json index 45ea13f9da..b9b8031ac4 100644 --- a/e2e/react-start/basic-cloudflare/package.json +++ b/e2e/react-start/basic-cloudflare/package.json @@ -10,7 +10,7 @@ "preview": "vite preview", "cf-typegen": "wrangler types", "postinstall": "WRANGLER_LOG=warn npm run --silent cf-typegen", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -29,8 +29,19 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "wrangler": "^4.74.0" + }, + "nx": { + "targets": { + "test:e2e": { + "outputs": [ + "...", + "{projectRoot}/.wrangler/deploy" + ] + } + } } } diff --git a/e2e/react-start/basic-cloudflare/playwright.config.ts b/e2e/react-start/basic-cloudflare/playwright.config.ts index a545dff891..0925936d55 100644 --- a/e2e/react-start/basic-cloudflare/playwright.config.ts +++ b/e2e/react-start/basic-cloudflare/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -14,9 +13,6 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, @@ -24,8 +20,8 @@ export default defineConfig({ webServer: { command: `pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-start/basic-cloudflare/src/routeTree.gen.ts b/e2e/react-start/basic-cloudflare/src/routeTree.gen.ts index 4219501f5e..b29f0d8d68 100644 --- a/e2e/react-start/basic-cloudflare/src/routeTree.gen.ts +++ b/e2e/react-start/basic-cloudflare/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 StaticRouteImport } from './routes/static' import { Route as IndexRouteImport } from './routes/index' +import { Route as StaticRouteImport } from './routes/static' -const StaticRoute = StaticRouteImport.update({ - id: '/static', - path: '/static', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const StaticRoute = StaticRouteImport.update({ + id: '/static', + path: '/static', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/static': { - id: '/static' - path: '/static' - fullPath: '/static' - preLoaderRoute: typeof StaticRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/static': { + id: '/static' + path: '/static' + fullPath: '/static' + preLoaderRoute: typeof StaticRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/e2e/react-start/basic-cloudflare/tests/app.spec.ts b/e2e/react-start/basic-cloudflare/tests/app.spec.ts index add28cb73e..c9497070dd 100644 --- a/e2e/react-start/basic-cloudflare/tests/app.spec.ts +++ b/e2e/react-start/basic-cloudflare/tests/app.spec.ts @@ -1,3 +1,5 @@ +import { execFileSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' import { existsSync } from 'node:fs' import { join } from 'node:path' import { expect } from '@playwright/test' @@ -29,3 +31,19 @@ test('prerender with Cloudflare Workers runtime', async ({ page }) => { 'The value is Hello from Cloudflare', ) }) + +test('the built Cloudflare app passes a deployment dry run', () => { + const wrangler = fileURLToPath( + new URL('../node_modules/wrangler/bin/wrangler.js', import.meta.url), + ) + const output = execFileSync( + process.execPath, + [wrangler, 'deploy', '--dry-run'], + { + encoding: 'utf8', + env: { ...process.env, WRANGLER_SEND_METRICS: 'false' }, + }, + ) + expect(output).toContain('dist/server/wrangler.json') + expect(output).toContain('--dry-run: exiting now.') +}) diff --git a/e2e/react-start/basic-cloudflare/tests/setup/global.setup.ts b/e2e/react-start/basic-cloudflare/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-start/basic-cloudflare/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-start/basic-cloudflare/tests/setup/global.teardown.ts b/e2e/react-start/basic-cloudflare/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-start/basic-cloudflare/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-start/basic-react-query/package.json b/e2e/react-start/basic-react-query/package.json index c804a89eb3..ee37b82ba6 100644 --- a/e2e/react-start/basic-react-query/package.json +++ b/e2e/react-start/basic-react-query/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-query": "^5.90.0", @@ -20,7 +20,7 @@ "@tanstack/react-start": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "zod": "^4.4.3" }, @@ -32,9 +32,10 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/e2e/react-start/basic-react-query/playwright.config.ts b/e2e/react-start/basic-react-query/playwright.config.ts index fd2150e435..216fade4d5 100644 --- a/e2e/react-start/basic-react-query/playwright.config.ts +++ b/e2e/react-start/basic-react-query/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -18,19 +13,19 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', + env: { + NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, + }, }, projects: [ diff --git a/e2e/react-start/basic-react-query/src/routeTree.gen.ts b/e2e/react-start/basic-react-query/src/routeTree.gen.ts index a1bed86dfa..72bd9579f6 100644 --- a/e2e/react-start/basic-react-query/src/routeTree.gen.ts +++ b/e2e/react-start/basic-react-query/src/routeTree.gen.ts @@ -9,43 +9,32 @@ // 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 UsersRouteImport } from './routes/users' -import { Route as SuspenseTransitionRouteImport } from './routes/suspense-transition' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as ApiUsersRouteImport } from './routes/api.users' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as SuspenseTransitionRouteImport } from './routes/suspense-transition' +import { Route as UsersRouteImport } from './routes/users' import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as TransitionCountQueryRouteImport } from './routes/transition/count/query' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as ApiUsersRouteImport } from './routes/api.users' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as TransitionCountQueryRouteImport } from './routes/transition/count/query' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const SuspenseTransitionRoute = SuspenseTransitionRouteImport.update({ - id: '/suspense-transition', - path: '/suspense-transition', - getParentRoute: () => rootRouteImport, -} as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', getParentRoute: () => rootRouteImport, } as any) const DeferredRoute = DeferredRouteImport.update({ @@ -53,68 +42,79 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, +const SuspenseTransitionRoute = SuspenseTransitionRouteImport.update({ + id: '/suspense-transition', + path: '/suspense-transition', + getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const LayoutLayout2Route = LayoutLayout2RouteImport.update({ id: '/_layout-2', getParentRoute: () => LayoutRoute, } as any) -const TransitionCountQueryRoute = TransitionCountQueryRouteImport.update({ - id: '/transition/count/query', - path: '/transition/count/query', +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, } as any) -const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => ApiUsersRoute, +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRoute, +} as any) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any) const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ id: '/layout-b', path: '/layout-b', getParentRoute: () => LayoutLayout2Route, } as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => ApiUsersRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) +const TransitionCountQueryRoute = TransitionCountQueryRouteImport.update({ + id: '/transition/count/query', + path: '/transition/count/query', + getParentRoute: () => rootRouteImport, } as any) export interface FileRoutesByFullPath { @@ -244,39 +244,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport - parentRoute: typeof rootRouteImport - } - '/suspense-transition': { - id: '/suspense-transition' - path: '/suspense-transition' - fullPath: '/suspense-transition' - preLoaderRoute: typeof SuspenseTransitionRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -286,46 +258,39 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute + '/suspense-transition': { + id: '/suspense-transition' + path: '/suspense-transition' + fullPath: '/suspense-transition' + preLoaderRoute: typeof SuspenseTransitionRouteImport + parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/_layout/_layout-2': { @@ -335,26 +300,47 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LayoutLayout2RouteImport parentRoute: typeof LayoutRoute } - '/transition/count/query': { - id: '/transition/count/query' - path: '/transition/count/query' - fullPath: '/transition/count/query' - preLoaderRoute: typeof TransitionCountQueryRouteImport + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute } - '/api/users/$id': { - id: '/api/users/$id' - path: '/$id' - fullPath: '/api/users/$id' - preLoaderRoute: typeof ApiUsersIdRouteImport - parentRoute: typeof ApiUsersRoute + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute + } + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route } '/_layout/_layout-2/layout-b': { id: '/_layout/_layout-2/layout-b' @@ -363,12 +349,26 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport parentRoute: typeof LayoutLayout2Route } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/api/users/$id': { + id: '/api/users/$id' + path: '/$id' + fullPath: '/api/users/$id' + preLoaderRoute: typeof ApiUsersIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport + } + '/transition/count/query': { + id: '/transition/count/query' + path: '/transition/count/query' + fullPath: '/transition/count/query' + preLoaderRoute: typeof TransitionCountQueryRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/e2e/react-start/basic-react-query/src/routes/api.users.ts b/e2e/react-start/basic-react-query/src/routes/api.users.ts index bb37c6e68d..924c5b6860 100644 --- a/e2e/react-start/basic-react-query/src/routes/api.users.ts +++ b/e2e/react-start/basic-react-query/src/routes/api.users.ts @@ -2,11 +2,7 @@ import { createFileRoute } from '@tanstack/react-router' import axios from 'redaxios' import type { User } from '../utils/users' -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const Route = createFileRoute('/api/users')({ server: { diff --git a/e2e/react-start/basic-react-query/src/routes/api/users.$id.ts b/e2e/react-start/basic-react-query/src/routes/api/users.$id.ts index e11e039652..febea309ea 100644 --- a/e2e/react-start/basic-react-query/src/routes/api/users.$id.ts +++ b/e2e/react-start/basic-react-query/src/routes/api/users.$id.ts @@ -2,11 +2,7 @@ import { createFileRoute } from '@tanstack/react-router' import axios from 'redaxios' import type { User } from '../../utils/users' -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const Route = createFileRoute('/api/users/$id')({ server: { diff --git a/e2e/react-start/basic-react-query/src/utils/posts.tsx b/e2e/react-start/basic-react-query/src/utils/posts.tsx index 3fd16db69a..abb6e95b92 100644 --- a/e2e/react-start/basic-react-query/src/utils/posts.tsx +++ b/e2e/react-start/basic-react-query/src/utils/posts.tsx @@ -9,11 +9,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPosts = createServerFn({ method: 'GET' }).handler( async () => { diff --git a/e2e/react-start/basic-react-query/src/utils/users.tsx b/e2e/react-start/basic-react-query/src/utils/users.tsx index 26b934fcb3..15216680e9 100644 --- a/e2e/react-start/basic-react-query/src/utils/users.tsx +++ b/e2e/react-start/basic-react-query/src/utils/users.tsx @@ -1,4 +1,6 @@ import { queryOptions } from '@tanstack/react-query' +import { createIsomorphicFn } from '@tanstack/react-start' +import { getRequestUrl } from '@tanstack/react-start/server' import axios from 'redaxios' export type User = { @@ -7,17 +9,16 @@ export type User = { email: string } -const PORT = - import.meta.env.VITE_SERVER_PORT || process.env.VITE_SERVER_PORT || 3000 - -export const DEPLOY_URL = `http://localhost:${PORT}` +const getOrigin = createIsomorphicFn() + .server(() => getRequestUrl().origin) + .client(() => window.location.origin) export const usersQueryOptions = () => queryOptions({ queryKey: ['users'], queryFn: () => axios - .get>(DEPLOY_URL + '/api/users') + .get>(getOrigin() + '/api/users') .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch users') @@ -29,7 +30,7 @@ export const userQueryOptions = (id: string) => queryKey: ['users', id], queryFn: () => axios - .get(DEPLOY_URL + '/api/users/' + id) + .get(getOrigin() + '/api/users/' + id) .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch user') diff --git a/e2e/react-start/basic-react-query/tests/setup/global.setup.ts b/e2e/react-start/basic-react-query/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-start/basic-react-query/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-start/basic-react-query/tests/setup/global.teardown.ts b/e2e/react-start/basic-react-query/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-start/basic-react-query/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-start/basic-tsr-config/package.json b/e2e/react-start/basic-tsr-config/package.json index e52f908a6e..99e681ac9d 100644 --- a/e2e/react-start/basic-tsr-config/package.json +++ b/e2e/react-start/basic-tsr-config/package.json @@ -8,7 +8,7 @@ "dev:e2e": "vite dev", "build": "rimraf ./count.txt && vite build && tsc --noEmit", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -21,8 +21,10 @@ "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "srvx": "^0.11.9", - "typescript": "^6.0.2", - "vite": "^8.0.14" + "srvx": "^1.0.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "rimraf": "catalog:" } } diff --git a/e2e/react-start/basic-tsr-config/playwright.config.ts b/e2e/react-start/basic-tsr-config/playwright.config.ts index 18b8905468..82678ac00b 100644 --- a/e2e/react-start/basic-tsr-config/playwright.config.ts +++ b/e2e/react-start/basic-tsr-config/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-start/basic/package.json b/e2e/react-start/basic/package.json index f11df33f3f..3a1a4ea9c8 100644 --- a/e2e/react-start/basic/package.json +++ b/e2e/react-start/basic/package.json @@ -14,8 +14,6 @@ "preview": "vite preview", "preview:rsbuild": "rsbuild preview", "start": "node server.js", - "test:e2e:startDummyServer": "node -e 'import(\"./tests/setup/global.setup.ts\").then(m => m.default())' & node -e 'import(\"./tests/setup/waitForDummyServer.ts\").then(m => m.default())'", - "test:e2e:stopDummyServer": "node -e 'import(\"./tests/setup/global.teardown.ts\").then(m => m.default())'", "test:e2e:local": "playwright test --project=chromium" }, "dependencies": { @@ -24,15 +22,16 @@ "@tanstack/react-start": "workspace:^", "express": "^5.2.1", "http-proxy-middleware": "^3.0.5", + "iron-session": "^9.0.1", "js-cookie": "^3.0.5", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0" }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.0.11", + "@rsbuild/core": "^2.3.1", "@rsbuild/plugin-react": "^2.0.0", "@tailwindcss/postcss": "^4.2.2", "@tailwindcss/vite": "^4.2.2", @@ -43,13 +42,26 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "combinate": "^1.1.11", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "zod": "^4.4.3" }, "nx": { + "targets": { + "test:e2e--vite-spa--dev": { + "dependsOn": [ + "^build" + ] + }, + "test:e2e--rsbuild-spa--dev": { + "dependsOn": [ + "^build" + ] + } + }, "metadata": { "playwrightModes": [ { @@ -62,7 +74,18 @@ }, { "toolchain": "vite", - "mode": "prerender" + "mode": "spa", + "name": "dev", + "env": { + "E2E_DEV_SERVER": "true" + } + }, + { + "toolchain": "vite", + "mode": "prerender", + "env": { + "NODE_OPTIONS": "--import=@tanstack/router-e2e-utils/mock-api" + } }, { "toolchain": "vite", @@ -86,7 +109,18 @@ }, { "toolchain": "rsbuild", - "mode": "prerender" + "mode": "spa", + "name": "dev", + "env": { + "E2E_DEV_SERVER": "true" + } + }, + { + "toolchain": "rsbuild", + "mode": "prerender", + "env": { + "NODE_OPTIONS": "--import=@tanstack/router-e2e-utils/mock-api" + } }, { "toolchain": "rsbuild", diff --git a/e2e/react-start/basic/playwright.config.ts b/e2e/react-start/basic/playwright.config.ts index db07d18608..bb4c2cb761 100644 --- a/e2e/react-start/basic/playwright.config.ts +++ b/e2e/react-start/basic/playwright.config.ts @@ -1,48 +1,42 @@ -import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' const mode = process.env.MODE ?? 'ssr' const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' -const e2ePortKey = process.env.E2E_PORT_KEY ?? packageJson.name + const distDir = process.env.E2E_DIST_DIR ?? 'dist' +// The dev runs start the dev server and run only the SPA shell spec +const devServer = process.env.E2E_DEV_SERVER === 'true' -if (process.env.TEST_WORKER_INDEX === undefined) { - for (const portFile of [ - `port-${e2ePortKey}.txt`, - `port-${e2ePortKey}_start.txt`, - `port-${e2ePortKey}-external.txt`, - ]) { - fs.rmSync(portFile, { force: true }) - } -} - -const PORT = await getTestServerPort(e2ePortKey) -const START_PORT = await getTestServerPort(`${e2ePortKey}_start`) -const EXTERNAL_PORT = await getDummyServerPort(e2ePortKey) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` const previewCommand = toolchain === 'rsbuild' - ? `pnpm preview:rsbuild --port ${PORT}` - : `pnpm preview --outDir ${distDir} --port ${PORT}` -const commandByMode = - mode === 'preview' - ? `pnpm run test:e2e:startDummyServer && ${previewCommand}` - : `pnpm run test:e2e:startDummyServer && pnpm start` + ? `pnpm preview:rsbuild --host 0.0.0.0 --port ${PORT}` + : `pnpm preview --host 0.0.0.0 --outDir ${distDir} --port ${PORT}` +const devCommand = + toolchain === 'rsbuild' + ? `pnpm dev:rsbuild --port ${PORT}` + : `pnpm dev:vite --port ${PORT}` +const commandByMode = devServer + ? devCommand + : mode === 'preview' + ? previewCommand + : 'pnpm start' /** * See https://playwright.dev/docs/test-configuration. */ export default defineConfig({ testDir: './tests', + ...(devServer + ? { + testMatch: 'spa-shell.spec.ts', + globalSetup: './tests/setup/dev-server.setup.ts', + } + : {}), workers: 1, reporter: [['line']], - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, @@ -50,19 +44,16 @@ export default defineConfig({ webServer: { command: commandByMode, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', env: { + NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, MODE: mode, E2E_TOOLCHAIN: toolchain, - VITE_NODE_ENV: 'test', - VITE_EXTERNAL_PORT: String(EXTERNAL_PORT), - VITE_SERVER_PORT: String(PORT), - START_PORT: String(START_PORT), + START_PORT: '0', PORT: String(PORT), E2E_DIST_DIR: distDir, - E2E_PORT_KEY: e2ePortKey, ...(process.env.TSS_RSB_CLIENT_OUTPUT ? { TSS_RSB_CLIENT_OUTPUT: process.env.TSS_RSB_CLIENT_OUTPUT } : {}), diff --git a/e2e/react-start/basic/rsbuild.config.ts b/e2e/react-start/basic/rsbuild.config.ts index d6a9c035eb..23072b6c1b 100644 --- a/e2e/react-start/basic/rsbuild.config.ts +++ b/e2e/react-start/basic/rsbuild.config.ts @@ -7,10 +7,7 @@ const outDir = process.env.E2E_DIST_DIR ?? 'dist' const startModeConfig = getStartModeConfig() export default defineConfig({ - plugins: [ - pluginReact({ splitChunks: false }), - tanstackStart(startModeConfig), - ], + plugins: [pluginReact(), tanstackStart(startModeConfig)], output: { distPath: { root: outDir, diff --git a/e2e/react-start/basic/server.js b/e2e/react-start/basic/server.js index 69c1e4ca91..3e1ddab400 100644 --- a/e2e/react-start/basic/server.js +++ b/e2e/react-start/basic/server.js @@ -1,12 +1,12 @@ -import { toNodeHandler } from 'srvx/node' import fs from 'node:fs' import path from 'node:path' +import { toNodeHandler } from 'srvx/node' import express from 'express' import { createProxyMiddleware } from 'http-proxy-middleware' -const port = process.env.PORT || 3000 +const port = Number(process.env.PORT ?? 3000) -const startPort = process.env.START_PORT || 3001 +const startPort = Number(process.env.START_PORT ?? 0) const isSpaMode = process.env.MODE === 'spa' const isPrerender = process.env.MODE === 'prerender' @@ -49,13 +49,13 @@ export async function createStartServer() { return { app } } -export async function createSpaServer() { +export async function createSpaServer(backendPort) { const app = express() app.use( '/api', createProxyMiddleware({ - target: `http://localhost:${startPort}/api`, // Replace with your target server's URL + target: `http://localhost:${backendPort}/api`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -63,7 +63,7 @@ export async function createSpaServer() { app.use( '/_serverFn', createProxyMiddleware({ - target: `http://localhost:${startPort}/_serverFn`, // Replace with your target server's URL + target: `http://localhost:${backendPort}/_serverFn`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -71,31 +71,28 @@ export async function createSpaServer() { app.use(express.static(distClientDir)) app.get('/{*splat}', (req, res) => { - res.sendFile(path.resolve(distClientDir, 'index.html')) + res.sendFile('index.html', { root: distClientDir }) }) return { app } } -if (isSpaMode) { - createSpaServer().then(async ({ app }) => - app.listen(port, (error) => { - if (error) throw error - console.info(`Client Server: http://localhost:${port}`) - }), - ) - - createStartServer().then(async ({ app }) => - app.listen(startPort, (error) => { - if (error) throw error - console.info(`Start Server: http://localhost:${startPort}`) - }), - ) -} else { - createStartServer().then(async ({ app }) => - app.listen(port, (error) => { - if (error) throw error - console.info(`Start Server: http://localhost:${port}`) - }), - ) -} +// Bind the backend first so the SPA proxy receives the port actually held by it. +const { app: startApp } = await createStartServer() +const backend = startApp.listen(isSpaMode ? startPort : port, async (error) => { + if (error) { + throw error + } + const backendPort = backend.address().port + if (isSpaMode) { + const { app } = await createSpaServer(backendPort) + const frontend = app.listen(port, (frontendError) => { + if (frontendError) { + throw frontendError + } + console.info(`E2E app: http://localhost:${frontend.address().port}`) + }) + } else { + console.info(`E2E app: http://localhost:${backendPort}`) + } +}) diff --git a/e2e/react-start/basic/src/routeTree.gen.ts b/e2e/react-start/basic/src/routeTree.gen.ts index 103853f3b8..b6603dd01d 100644 --- a/e2e/react-start/basic/src/routeTree.gen.ts +++ b/e2e/react-start/basic/src/routeTree.gen.ts @@ -9,100 +9,145 @@ // 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 UsersRouteImport } from './routes/users' -import { Route as TypeOnlyReexportRouteImport } from './routes/type-only-reexport' -import { Route as StreamRouteImport } from './routes/stream' -import { Route as ScriptsRouteImport } from './routes/scripts' -import { Route as RawStreamRouteImport } from './routes/raw-stream' -import { Route as PrimitiveBeforeloadErrorRouteImport } from './routes/primitive-beforeload-error' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as PlainTsTypeAssertionRouteImport } from './routes/plain-ts-type-assertion' -import { Route as LinksRouteImport } from './routes/links' -import { Route as InlineScriptsRouteImport } from './routes/inline-scripts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as ClientOnlyRouteImport } from './routes/client-only' -import { Route as AsyncScriptsRouteImport } from './routes/async-scripts' -import { Route as LayoutRouteImport } from './routes/_layout' -import { Route as SpecialCharsRouteRouteImport } from './routes/specialChars/route' -import { Route as SearchParamsRouteRouteImport } from './routes/search-params/route' -import { Route as NotFoundRouteRouteImport } from './routes/not-found/route' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as SearchParamsIndexRouteImport } from './routes/search-params/index' -import { Route as RedirectIndexRouteImport } from './routes/redirect/index' -import { Route as RawStreamIndexRouteImport } from './routes/raw-stream/index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as NotFoundIndexRouteImport } from './routes/not-found/index' -import { Route as MultiCookieRedirectIndexRouteImport } from './routes/multi-cookie-redirect/index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as SpecialCharsChar45824Char54620Char48124Char44397RouteImport } from './routes/specialChars/대한민국' -import { Route as SpecialCharsSearchRouteImport } from './routes/specialChars/search' -import { Route as SpecialCharsHashRouteImport } from './routes/specialChars/hash' -import { Route as SpecialCharsParamRouteImport } from './routes/specialChars/$param' -import { Route as SearchParamsLoaderThrowsRedirectRouteImport } from './routes/search-params/loader-throws-redirect' -import { Route as SearchParamsDefaultRouteImport } from './routes/search-params/default' -import { Route as RedirectTargetRouteImport } from './routes/redirect/$target' -import { Route as RawStreamSsrTextHintRouteImport } from './routes/raw-stream/ssr-text-hint' -import { Route as RawStreamSsrSingleRouteImport } from './routes/raw-stream/ssr-single' -import { Route as RawStreamSsrMultipleRouteImport } from './routes/raw-stream/ssr-multiple' -import { Route as RawStreamSsrMixedRouteImport } from './routes/raw-stream/ssr-mixed' -import { Route as RawStreamSsrBinaryHintRouteImport } from './routes/raw-stream/ssr-binary-hint' -import { Route as RawStreamClientCallRouteImport } from './routes/raw-stream/client-call' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as NotFoundViaLoaderRouteImport } from './routes/not-found/via-loader' -import { Route as NotFoundViaBeforeLoadTargetRootRouteImport } from './routes/not-found/via-beforeLoad-target-root' -import { Route as NotFoundViaBeforeLoadRouteImport } from './routes/not-found/via-beforeLoad' -import { Route as MultiCookieRedirectTargetRouteImport } from './routes/multi-cookie-redirect/target' -import { Route as ApiUsersRouteImport } from './routes/api.users' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as AsyncScriptsRouteImport } from './routes/async-scripts' +import { Route as AuthDocsRouteImport } from './routes/auth-docs' +import { Route as ClientOnlyRouteImport } from './routes/client-only' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as ExecutionLocalRouteImport } from './routes/execution-local' +import { Route as ExecutionRpcRouteImport } from './routes/execution-rpc' +import { Route as InlineScriptsRouteImport } from './routes/inline-scripts' +import { Route as LinksRouteImport } from './routes/links' +import { Route as NotFoundRouteRouteImport } from './routes/not-found/route' +import { Route as PlainTsTypeAssertionRouteImport } from './routes/plain-ts-type-assertion' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as PrimitiveBeforeloadErrorRouteImport } from './routes/primitive-beforeload-error' +import { Route as RawStreamRouteImport } from './routes/raw-stream' +import { Route as ScriptsRouteImport } from './routes/scripts' +import { Route as SearchParamsRouteRouteImport } from './routes/search-params/route' +import { Route as SpecialCharsRouteRouteImport } from './routes/specialChars/route' +import { Route as StreamRouteImport } from './routes/stream' +import { Route as TypeOnlyReexportRouteImport } from './routes/type-only-reexport' +import { Route as UsersRouteImport } from './routes/users' import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as SpecialCharsMalformedRouteRouteImport } from './routes/specialChars/malformed/route' -import { Route as NotFoundParentBoundaryRouteRouteImport } from './routes/not-found/parent-boundary/route' +import { Route as ApiUsersRouteImport } from './routes/api.users' +import { Route as AuthDocsPrivateRouteImport } from './routes/auth-docs.private' +import { Route as Issue6221DashboardRouteImport } from './routes/issue-6221.dashboard' +import { Route as MultiCookieRedirectIndexRouteImport } from './routes/multi-cookie-redirect/index' +import { Route as MultiCookieRedirectTargetRouteImport } from './routes/multi-cookie-redirect/target' +import { Route as NotFoundIndexRouteImport } from './routes/not-found/index' import { Route as NotFoundDeepRouteRouteImport } from './routes/not-found/deep/route' -import { Route as RedirectTargetIndexRouteImport } from './routes/redirect/$target/index' -import { Route as NotFoundParentBoundaryIndexRouteImport } from './routes/not-found/parent-boundary/index' -import { Route as NotFoundDeepIndexRouteImport } from './routes/not-found/deep/index' -import { Route as SpecialCharsMalformedSearchRouteImport } from './routes/specialChars/malformed/search' -import { Route as SpecialCharsMalformedParamRouteImport } from './routes/specialChars/malformed/$param' -import { Route as RedirectTargetViaLoaderRouteImport } from './routes/redirect/$target/via-loader' -import { Route as RedirectTargetViaBeforeLoadRouteImport } from './routes/redirect/$target/via-beforeLoad' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as NotFoundParentBoundaryViaBeforeLoadRouteImport } from './routes/not-found/parent-boundary/via-beforeLoad' -import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as NotFoundParentBoundaryRouteRouteImport } from './routes/not-found/parent-boundary/route' +import { Route as NotFoundViaBeforeLoadRouteImport } from './routes/not-found/via-beforeLoad' +import { Route as NotFoundViaBeforeLoadTargetRootRouteImport } from './routes/not-found/via-beforeLoad-target-root' +import { Route as NotFoundViaLoaderRouteImport } from './routes/not-found/via-loader' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as RawStreamIndexRouteImport } from './routes/raw-stream/index' +import { Route as RawStreamClientCallRouteImport } from './routes/raw-stream/client-call' +import { Route as RawStreamSsrBinaryHintRouteImport } from './routes/raw-stream/ssr-binary-hint' +import { Route as RawStreamSsrMixedRouteImport } from './routes/raw-stream/ssr-mixed' +import { Route as RawStreamSsrMultipleRouteImport } from './routes/raw-stream/ssr-multiple' +import { Route as RawStreamSsrSingleRouteImport } from './routes/raw-stream/ssr-single' +import { Route as RawStreamSsrTextHintRouteImport } from './routes/raw-stream/ssr-text-hint' +import { Route as RedirectIndexRouteImport } from './routes/redirect/index' +import { Route as RedirectTargetRouteImport } from './routes/redirect/$target' +import { Route as SearchParamsIndexRouteImport } from './routes/search-params/index' +import { Route as SearchParamsDefaultRouteImport } from './routes/search-params/default' +import { Route as SearchParamsLoaderThrowsRedirectRouteImport } from './routes/search-params/loader-throws-redirect' +import { Route as SpecialCharsParamRouteImport } from './routes/specialChars/$param' +import { Route as SpecialCharsHashRouteImport } from './routes/specialChars/hash' +import { Route as SpecialCharsMalformedRouteRouteImport } from './routes/specialChars/malformed/route' +import { Route as SpecialCharsSearchRouteImport } from './routes/specialChars/search' +import { Route as SpecialCharsChar45824Char54620Char48124Char44397RouteImport } from './routes/specialChars/대한민국' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' +import { Route as Issue6221ArticleIdRouteImport } from './routes/issue-6221.article.$id' +import { Route as NotFoundDeepIndexRouteImport } from './routes/not-found/deep/index' import { Route as NotFoundDeepBRouteRouteImport } from './routes/not-found/deep/b/route' -import { Route as RedirectTargetServerFnIndexRouteImport } from './routes/redirect/$target/serverFn/index' -import { Route as RedirectTargetServerFnViaUseServerFnRouteImport } from './routes/redirect/$target/serverFn/via-useServerFn' -import { Route as RedirectTargetServerFnViaLoaderRouteImport } from './routes/redirect/$target/serverFn/via-loader' -import { Route as RedirectTargetServerFnViaBeforeLoadRouteImport } from './routes/redirect/$target/serverFn/via-beforeLoad' +import { Route as NotFoundParentBoundaryIndexRouteImport } from './routes/not-found/parent-boundary/index' +import { Route as NotFoundParentBoundaryViaBeforeLoadRouteImport } from './routes/not-found/parent-boundary/via-beforeLoad' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as RedirectTargetIndexRouteImport } from './routes/redirect/$target/index' +import { Route as RedirectTargetViaBeforeLoadRouteImport } from './routes/redirect/$target/via-beforeLoad' +import { Route as RedirectTargetViaLoaderRouteImport } from './routes/redirect/$target/via-loader' +import { Route as SpecialCharsMalformedParamRouteImport } from './routes/specialChars/malformed/$param' +import { Route as SpecialCharsMalformedSearchRouteImport } from './routes/specialChars/malformed/search' import { Route as FooBarQuxHereRouteImport } from './routes/foo/$bar/$qux/_here' import { Route as NotFoundDeepBCRouteRouteImport } from './routes/not-found/deep/b/c/route' +import { Route as RedirectTargetServerFnIndexRouteImport } from './routes/redirect/$target/serverFn/index' +import { Route as RedirectTargetServerFnViaBeforeLoadRouteImport } from './routes/redirect/$target/serverFn/via-beforeLoad' +import { Route as RedirectTargetServerFnViaLoaderRouteImport } from './routes/redirect/$target/serverFn/via-loader' +import { Route as RedirectTargetServerFnViaUseServerFnRouteImport } from './routes/redirect/$target/serverFn/via-useServerFn' import { Route as FooBarQuxHereIndexRouteImport } from './routes/foo/$bar/$qux/_here/index' import { Route as NotFoundDeepBCDRouteImport } from './routes/not-found/deep/b/c/d' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const TypeOnlyReexportRoute = TypeOnlyReexportRouteImport.update({ - id: '/type-only-reexport', - path: '/type-only-reexport', +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', getParentRoute: () => rootRouteImport, } as any) -const StreamRoute = StreamRouteImport.update({ - id: '/stream', - path: '/stream', +const AsyncScriptsRoute = AsyncScriptsRouteImport.update({ + id: '/async-scripts', + path: '/async-scripts', getParentRoute: () => rootRouteImport, } as any) -const ScriptsRoute = ScriptsRouteImport.update({ - id: '/scripts', - path: '/scripts', +const AuthDocsRoute = AuthDocsRouteImport.update({ + id: '/auth-docs', + path: '/auth-docs', getParentRoute: () => rootRouteImport, } as any) -const RawStreamRoute = RawStreamRouteImport.update({ - id: '/raw-stream', - path: '/raw-stream', +const ClientOnlyRoute = ClientOnlyRouteImport.update({ + id: '/client-only', + path: '/client-only', + getParentRoute: () => rootRouteImport, +} as any) +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', + getParentRoute: () => rootRouteImport, +} as any) +const ExecutionLocalRoute = ExecutionLocalRouteImport.update({ + id: '/execution-local', + path: '/execution-local', + getParentRoute: () => rootRouteImport, +} as any) +const ExecutionRpcRoute = ExecutionRpcRouteImport.update({ + id: '/execution-rpc', + path: '/execution-rpc', + getParentRoute: () => rootRouteImport, +} as any) +const InlineScriptsRoute = InlineScriptsRouteImport.update({ + id: '/inline-scripts', + path: '/inline-scripts', + getParentRoute: () => rootRouteImport, +} as any) +const LinksRoute = LinksRouteImport.update({ + id: '/links', + path: '/links', + getParentRoute: () => rootRouteImport, +} as any) +const NotFoundRouteRoute = NotFoundRouteRouteImport.update({ + id: '/not-found', + path: '/not-found', + getParentRoute: () => rootRouteImport, +} as any) +const PlainTsTypeAssertionRoute = PlainTsTypeAssertionRouteImport.update({ + id: '/plain-ts-type-assertion', + path: '/plain-ts-type-assertion', + getParentRoute: () => rootRouteImport, +} as any) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) const PrimitiveBeforeloadErrorRoute = @@ -111,48 +156,14 @@ const PrimitiveBeforeloadErrorRoute = path: '/primitive-beforeload-error', getParentRoute: () => rootRouteImport, } as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const RawStreamRoute = RawStreamRouteImport.update({ + id: '/raw-stream', + path: '/raw-stream', getParentRoute: () => rootRouteImport, } as any) -const PlainTsTypeAssertionRoute = PlainTsTypeAssertionRouteImport.update({ - id: '/plain-ts-type-assertion', - path: '/plain-ts-type-assertion', - getParentRoute: () => rootRouteImport, -} as any) -const LinksRoute = LinksRouteImport.update({ - id: '/links', - path: '/links', - getParentRoute: () => rootRouteImport, -} as any) -const InlineScriptsRoute = InlineScriptsRouteImport.update({ - id: '/inline-scripts', - path: '/inline-scripts', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', - getParentRoute: () => rootRouteImport, -} as any) -const ClientOnlyRoute = ClientOnlyRouteImport.update({ - id: '/client-only', - path: '/client-only', - getParentRoute: () => rootRouteImport, -} as any) -const AsyncScriptsRoute = AsyncScriptsRouteImport.update({ - id: '/async-scripts', - path: '/async-scripts', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const SpecialCharsRouteRoute = SpecialCharsRouteRouteImport.update({ - id: '/specialChars', - path: '/specialChars', +const ScriptsRoute = ScriptsRouteImport.update({ + id: '/scripts', + path: '/scripts', getParentRoute: () => rootRouteImport, } as any) const SearchParamsRouteRoute = SearchParamsRouteRouteImport.update({ @@ -160,45 +171,44 @@ const SearchParamsRouteRoute = SearchParamsRouteRouteImport.update({ path: '/search-params', getParentRoute: () => rootRouteImport, } as any) -const NotFoundRouteRoute = NotFoundRouteRouteImport.update({ - id: '/not-found', - path: '/not-found', +const SpecialCharsRouteRoute = SpecialCharsRouteRouteImport.update({ + id: '/specialChars', + path: '/specialChars', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const StreamRoute = StreamRouteImport.update({ + id: '/stream', + path: '/stream', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, -} as any) -const SearchParamsIndexRoute = SearchParamsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SearchParamsRouteRoute, -} as any) -const RedirectIndexRoute = RedirectIndexRouteImport.update({ - id: '/redirect/', - path: '/redirect/', +const TypeOnlyReexportRoute = TypeOnlyReexportRouteImport.update({ + id: '/type-only-reexport', + path: '/type-only-reexport', getParentRoute: () => rootRouteImport, } as any) -const RawStreamIndexRoute = RawStreamIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => RawStreamRoute, +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', + getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, } as any) -const NotFoundIndexRoute = NotFoundIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => NotFoundRouteRoute, +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', + getParentRoute: () => rootRouteImport, +} as any) +const AuthDocsPrivateRoute = AuthDocsPrivateRouteImport.update({ + id: '/private', + path: '/private', + getParentRoute: () => AuthDocsRoute, +} as any) +const Issue6221DashboardRoute = Issue6221DashboardRouteImport.update({ + id: '/issue-6221/dashboard', + path: '/issue-6221/dashboard', + getParentRoute: () => rootRouteImport, } as any) const MultiCookieRedirectIndexRoute = MultiCookieRedirectIndexRouteImport.update({ @@ -206,86 +216,31 @@ const MultiCookieRedirectIndexRoute = path: '/multi-cookie-redirect/', getParentRoute: () => rootRouteImport, } as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const SpecialCharsChar45824Char54620Char48124Char44397Route = - SpecialCharsChar45824Char54620Char48124Char44397RouteImport.update({ - id: '/대한민국', - path: '/대한민국', - getParentRoute: () => SpecialCharsRouteRoute, +const MultiCookieRedirectTargetRoute = + MultiCookieRedirectTargetRouteImport.update({ + id: '/multi-cookie-redirect/target', + path: '/multi-cookie-redirect/target', + getParentRoute: () => rootRouteImport, } as any) -const SpecialCharsSearchRoute = SpecialCharsSearchRouteImport.update({ - id: '/search', - path: '/search', - getParentRoute: () => SpecialCharsRouteRoute, +const NotFoundIndexRoute = NotFoundIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => NotFoundRouteRoute, } as any) -const SpecialCharsHashRoute = SpecialCharsHashRouteImport.update({ - id: '/hash', - path: '/hash', - getParentRoute: () => SpecialCharsRouteRoute, +const NotFoundDeepRouteRoute = NotFoundDeepRouteRouteImport.update({ + id: '/deep', + path: '/deep', + getParentRoute: () => NotFoundRouteRoute, } as any) -const SpecialCharsParamRoute = SpecialCharsParamRouteImport.update({ - id: '/$param', - path: '/$param', - getParentRoute: () => SpecialCharsRouteRoute, -} as any) -const SearchParamsLoaderThrowsRedirectRoute = - SearchParamsLoaderThrowsRedirectRouteImport.update({ - id: '/loader-throws-redirect', - path: '/loader-throws-redirect', - getParentRoute: () => SearchParamsRouteRoute, +const NotFoundParentBoundaryRouteRoute = + NotFoundParentBoundaryRouteRouteImport.update({ + id: '/parent-boundary', + path: '/parent-boundary', + getParentRoute: () => NotFoundRouteRoute, } as any) -const SearchParamsDefaultRoute = SearchParamsDefaultRouteImport.update({ - id: '/default', - path: '/default', - getParentRoute: () => SearchParamsRouteRoute, -} as any) -const RedirectTargetRoute = RedirectTargetRouteImport.update({ - id: '/redirect/$target', - path: '/redirect/$target', - getParentRoute: () => rootRouteImport, -} as any) -const RawStreamSsrTextHintRoute = RawStreamSsrTextHintRouteImport.update({ - id: '/ssr-text-hint', - path: '/ssr-text-hint', - getParentRoute: () => RawStreamRoute, -} as any) -const RawStreamSsrSingleRoute = RawStreamSsrSingleRouteImport.update({ - id: '/ssr-single', - path: '/ssr-single', - getParentRoute: () => RawStreamRoute, -} as any) -const RawStreamSsrMultipleRoute = RawStreamSsrMultipleRouteImport.update({ - id: '/ssr-multiple', - path: '/ssr-multiple', - getParentRoute: () => RawStreamRoute, -} as any) -const RawStreamSsrMixedRoute = RawStreamSsrMixedRouteImport.update({ - id: '/ssr-mixed', - path: '/ssr-mixed', - getParentRoute: () => RawStreamRoute, -} as any) -const RawStreamSsrBinaryHintRoute = RawStreamSsrBinaryHintRouteImport.update({ - id: '/ssr-binary-hint', - path: '/ssr-binary-hint', - getParentRoute: () => RawStreamRoute, -} as any) -const RawStreamClientCallRoute = RawStreamClientCallRouteImport.update({ - id: '/client-call', - path: '/client-call', - getParentRoute: () => RawStreamRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const NotFoundViaLoaderRoute = NotFoundViaLoaderRouteImport.update({ - id: '/via-loader', - path: '/via-loader', +const NotFoundViaBeforeLoadRoute = NotFoundViaBeforeLoadRouteImport.update({ + id: '/via-beforeLoad', + path: '/via-beforeLoad', getParentRoute: () => NotFoundRouteRoute, } as any) const NotFoundViaBeforeLoadTargetRootRoute = @@ -294,25 +249,91 @@ const NotFoundViaBeforeLoadTargetRootRoute = path: '/via-beforeLoad-target-root', getParentRoute: () => NotFoundRouteRoute, } as any) -const NotFoundViaBeforeLoadRoute = NotFoundViaBeforeLoadRouteImport.update({ - id: '/via-beforeLoad', - path: '/via-beforeLoad', +const NotFoundViaLoaderRoute = NotFoundViaLoaderRouteImport.update({ + id: '/via-loader', + path: '/via-loader', getParentRoute: () => NotFoundRouteRoute, } as any) -const MultiCookieRedirectTargetRoute = - MultiCookieRedirectTargetRouteImport.update({ - id: '/multi-cookie-redirect/target', - path: '/multi-cookie-redirect/target', - getParentRoute: () => rootRouteImport, - } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const RawStreamIndexRoute = RawStreamIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamClientCallRoute = RawStreamClientCallRouteImport.update({ + id: '/client-call', + path: '/client-call', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrBinaryHintRoute = RawStreamSsrBinaryHintRouteImport.update({ + id: '/ssr-binary-hint', + path: '/ssr-binary-hint', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrMixedRoute = RawStreamSsrMixedRouteImport.update({ + id: '/ssr-mixed', + path: '/ssr-mixed', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrMultipleRoute = RawStreamSsrMultipleRouteImport.update({ + id: '/ssr-multiple', + path: '/ssr-multiple', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrSingleRoute = RawStreamSsrSingleRouteImport.update({ + id: '/ssr-single', + path: '/ssr-single', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrTextHintRoute = RawStreamSsrTextHintRouteImport.update({ + id: '/ssr-text-hint', + path: '/ssr-text-hint', + getParentRoute: () => RawStreamRoute, +} as any) +const RedirectIndexRoute = RedirectIndexRouteImport.update({ + id: '/redirect/', + path: '/redirect/', getParentRoute: () => rootRouteImport, } as any) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, +const RedirectTargetRoute = RedirectTargetRouteImport.update({ + id: '/redirect/$target', + path: '/redirect/$target', + getParentRoute: () => rootRouteImport, +} as any) +const SearchParamsIndexRoute = SearchParamsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SearchParamsRouteRoute, +} as any) +const SearchParamsDefaultRoute = SearchParamsDefaultRouteImport.update({ + id: '/default', + path: '/default', + getParentRoute: () => SearchParamsRouteRoute, +} as any) +const SearchParamsLoaderThrowsRedirectRoute = + SearchParamsLoaderThrowsRedirectRouteImport.update({ + id: '/loader-throws-redirect', + path: '/loader-throws-redirect', + getParentRoute: () => SearchParamsRouteRoute, + } as any) +const SpecialCharsParamRoute = SpecialCharsParamRouteImport.update({ + id: '/$param', + path: '/$param', + getParentRoute: () => SpecialCharsRouteRoute, +} as any) +const SpecialCharsHashRoute = SpecialCharsHashRouteImport.update({ + id: '/hash', + path: '/hash', + getParentRoute: () => SpecialCharsRouteRoute, } as any) const SpecialCharsMalformedRouteRoute = SpecialCharsMalformedRouteRouteImport.update({ @@ -320,21 +341,56 @@ const SpecialCharsMalformedRouteRoute = path: '/malformed', getParentRoute: () => SpecialCharsRouteRoute, } as any) -const NotFoundParentBoundaryRouteRoute = - NotFoundParentBoundaryRouteRouteImport.update({ - id: '/parent-boundary', - path: '/parent-boundary', - getParentRoute: () => NotFoundRouteRoute, - } as any) -const NotFoundDeepRouteRoute = NotFoundDeepRouteRouteImport.update({ - id: '/deep', - path: '/deep', - getParentRoute: () => NotFoundRouteRoute, +const SpecialCharsSearchRoute = SpecialCharsSearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => SpecialCharsRouteRoute, } as any) -const RedirectTargetIndexRoute = RedirectTargetIndexRouteImport.update({ +const SpecialCharsChar45824Char54620Char48124Char44397Route = + SpecialCharsChar45824Char54620Char48124Char44397RouteImport.update({ + id: '/대한민국', + path: '/대한민국', + getParentRoute: () => SpecialCharsRouteRoute, + } as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => RedirectTargetRoute, + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRoute, +} as any) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, +} as any) +const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => LayoutLayout2Route, +} as any) +const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => ApiUsersRoute, +} as any) +const Issue6221ArticleIdRoute = Issue6221ArticleIdRouteImport.update({ + id: '/issue-6221/article/$id', + path: '/issue-6221/article/$id', + getParentRoute: () => rootRouteImport, +} as any) +const NotFoundDeepIndexRoute = NotFoundDeepIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => NotFoundDeepRouteRoute, +} as any) +const NotFoundDeepBRouteRoute = NotFoundDeepBRouteRouteImport.update({ + id: '/b', + path: '/b', + getParentRoute: () => NotFoundDeepRouteRoute, } as any) const NotFoundParentBoundaryIndexRoute = NotFoundParentBoundaryIndexRouteImport.update({ @@ -342,26 +398,20 @@ const NotFoundParentBoundaryIndexRoute = path: '/', getParentRoute: () => NotFoundParentBoundaryRouteRoute, } as any) -const NotFoundDeepIndexRoute = NotFoundDeepIndexRouteImport.update({ +const NotFoundParentBoundaryViaBeforeLoadRoute = + NotFoundParentBoundaryViaBeforeLoadRouteImport.update({ + id: '/via-beforeLoad', + path: '/via-beforeLoad', + getParentRoute: () => NotFoundParentBoundaryRouteRoute, + } as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) +const RedirectTargetIndexRoute = RedirectTargetIndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => NotFoundDeepRouteRoute, -} as any) -const SpecialCharsMalformedSearchRoute = - SpecialCharsMalformedSearchRouteImport.update({ - id: '/search', - path: '/search', - getParentRoute: () => SpecialCharsMalformedRouteRoute, - } as any) -const SpecialCharsMalformedParamRoute = - SpecialCharsMalformedParamRouteImport.update({ - id: '/$param', - path: '/$param', - getParentRoute: () => SpecialCharsMalformedRouteRoute, - } as any) -const RedirectTargetViaLoaderRoute = RedirectTargetViaLoaderRouteImport.update({ - id: '/via-loader', - path: '/via-loader', getParentRoute: () => RedirectTargetRoute, } as any) const RedirectTargetViaBeforeLoadRoute = @@ -370,60 +420,22 @@ const RedirectTargetViaBeforeLoadRoute = path: '/via-beforeLoad', getParentRoute: () => RedirectTargetRoute, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, +const RedirectTargetViaLoaderRoute = RedirectTargetViaLoaderRouteImport.update({ + id: '/via-loader', + path: '/via-loader', + getParentRoute: () => RedirectTargetRoute, } as any) -const NotFoundParentBoundaryViaBeforeLoadRoute = - NotFoundParentBoundaryViaBeforeLoadRouteImport.update({ - id: '/via-beforeLoad', - path: '/via-beforeLoad', - getParentRoute: () => NotFoundParentBoundaryRouteRoute, +const SpecialCharsMalformedParamRoute = + SpecialCharsMalformedParamRouteImport.update({ + id: '/$param', + path: '/$param', + getParentRoute: () => SpecialCharsMalformedRouteRoute, } as any) -const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => ApiUsersRoute, -} as any) -const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => LayoutLayout2Route, -} as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, -} as any) -const NotFoundDeepBRouteRoute = NotFoundDeepBRouteRouteImport.update({ - id: '/b', - path: '/b', - getParentRoute: () => NotFoundDeepRouteRoute, -} as any) -const RedirectTargetServerFnIndexRoute = - RedirectTargetServerFnIndexRouteImport.update({ - id: '/serverFn/', - path: '/serverFn/', - getParentRoute: () => RedirectTargetRoute, - } as any) -const RedirectTargetServerFnViaUseServerFnRoute = - RedirectTargetServerFnViaUseServerFnRouteImport.update({ - id: '/serverFn/via-useServerFn', - path: '/serverFn/via-useServerFn', - getParentRoute: () => RedirectTargetRoute, - } as any) -const RedirectTargetServerFnViaLoaderRoute = - RedirectTargetServerFnViaLoaderRouteImport.update({ - id: '/serverFn/via-loader', - path: '/serverFn/via-loader', - getParentRoute: () => RedirectTargetRoute, - } as any) -const RedirectTargetServerFnViaBeforeLoadRoute = - RedirectTargetServerFnViaBeforeLoadRouteImport.update({ - id: '/serverFn/via-beforeLoad', - path: '/serverFn/via-beforeLoad', - getParentRoute: () => RedirectTargetRoute, +const SpecialCharsMalformedSearchRoute = + SpecialCharsMalformedSearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => SpecialCharsMalformedRouteRoute, } as any) const FooBarQuxHereRoute = FooBarQuxHereRouteImport.update({ id: '/foo/$bar/$qux/_here', @@ -435,6 +447,30 @@ const NotFoundDeepBCRouteRoute = NotFoundDeepBCRouteRouteImport.update({ path: '/c', getParentRoute: () => NotFoundDeepBRouteRoute, } as any) +const RedirectTargetServerFnIndexRoute = + RedirectTargetServerFnIndexRouteImport.update({ + id: '/serverFn/', + path: '/serverFn/', + getParentRoute: () => RedirectTargetRoute, + } as any) +const RedirectTargetServerFnViaBeforeLoadRoute = + RedirectTargetServerFnViaBeforeLoadRouteImport.update({ + id: '/serverFn/via-beforeLoad', + path: '/serverFn/via-beforeLoad', + getParentRoute: () => RedirectTargetRoute, + } as any) +const RedirectTargetServerFnViaLoaderRoute = + RedirectTargetServerFnViaLoaderRouteImport.update({ + id: '/serverFn/via-loader', + path: '/serverFn/via-loader', + getParentRoute: () => RedirectTargetRoute, + } as any) +const RedirectTargetServerFnViaUseServerFnRoute = + RedirectTargetServerFnViaUseServerFnRouteImport.update({ + id: '/serverFn/via-useServerFn', + path: '/serverFn/via-useServerFn', + getParentRoute: () => RedirectTargetRoute, + } as any) const FooBarQuxHereIndexRoute = FooBarQuxHereIndexRouteImport.update({ id: '/', path: '/', @@ -452,8 +488,11 @@ export interface FileRoutesByFullPath { '/search-params': typeof SearchParamsRouteRouteWithChildren '/specialChars': typeof SpecialCharsRouteRouteWithChildren '/async-scripts': typeof AsyncScriptsRoute + '/auth-docs': typeof AuthDocsRouteWithChildren '/client-only': typeof ClientOnlyRoute '/deferred': typeof DeferredRoute + '/execution-local': typeof ExecutionLocalRoute + '/execution-rpc': typeof ExecutionRpcRoute '/inline-scripts': typeof InlineScriptsRoute '/links': typeof LinksRoute '/plain-ts-type-assertion': typeof PlainTsTypeAssertionRoute @@ -468,6 +507,8 @@ export interface FileRoutesByFullPath { '/not-found/parent-boundary': typeof NotFoundParentBoundaryRouteRouteWithChildren '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren + '/auth-docs/private': typeof AuthDocsPrivateRoute + '/issue-6221/dashboard': typeof Issue6221DashboardRoute '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute @@ -498,6 +539,7 @@ export interface FileRoutesByFullPath { '/layout-a': typeof LayoutLayout2LayoutARoute '/layout-b': typeof LayoutLayout2LayoutBRoute '/api/users/$id': typeof ApiUsersIdRoute + '/issue-6221/article/$id': typeof Issue6221ArticleIdRoute '/not-found/parent-boundary/via-beforeLoad': typeof NotFoundParentBoundaryViaBeforeLoadRoute '/posts/$postId/deep': typeof PostsPostIdDeepRoute '/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute @@ -520,8 +562,11 @@ export interface FileRoutesByTo { '/': typeof IndexRoute '/specialChars': typeof SpecialCharsRouteRouteWithChildren '/async-scripts': typeof AsyncScriptsRoute + '/auth-docs': typeof AuthDocsRouteWithChildren '/client-only': typeof ClientOnlyRoute '/deferred': typeof DeferredRoute + '/execution-local': typeof ExecutionLocalRoute + '/execution-rpc': typeof ExecutionRpcRoute '/inline-scripts': typeof InlineScriptsRoute '/links': typeof LinksRoute '/plain-ts-type-assertion': typeof PlainTsTypeAssertionRoute @@ -531,6 +576,8 @@ export interface FileRoutesByTo { '/type-only-reexport': typeof TypeOnlyReexportRoute '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren + '/auth-docs/private': typeof AuthDocsPrivateRoute + '/issue-6221/dashboard': typeof Issue6221DashboardRoute '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute @@ -560,6 +607,7 @@ export interface FileRoutesByTo { '/layout-a': typeof LayoutLayout2LayoutARoute '/layout-b': typeof LayoutLayout2LayoutBRoute '/api/users/$id': typeof ApiUsersIdRoute + '/issue-6221/article/$id': typeof Issue6221ArticleIdRoute '/not-found/parent-boundary/via-beforeLoad': typeof NotFoundParentBoundaryViaBeforeLoadRoute '/posts/$postId/deep': typeof PostsPostIdDeepRoute '/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute @@ -585,8 +633,11 @@ export interface FileRoutesById { '/specialChars': typeof SpecialCharsRouteRouteWithChildren '/_layout': typeof LayoutRouteWithChildren '/async-scripts': typeof AsyncScriptsRoute + '/auth-docs': typeof AuthDocsRouteWithChildren '/client-only': typeof ClientOnlyRoute '/deferred': typeof DeferredRoute + '/execution-local': typeof ExecutionLocalRoute + '/execution-rpc': typeof ExecutionRpcRoute '/inline-scripts': typeof InlineScriptsRoute '/links': typeof LinksRoute '/plain-ts-type-assertion': typeof PlainTsTypeAssertionRoute @@ -602,6 +653,8 @@ export interface FileRoutesById { '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/_layout/_layout-2': typeof LayoutLayout2RouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren + '/auth-docs/private': typeof AuthDocsPrivateRoute + '/issue-6221/dashboard': typeof Issue6221DashboardRoute '/multi-cookie-redirect/target': typeof MultiCookieRedirectTargetRoute '/not-found/via-beforeLoad': typeof NotFoundViaBeforeLoadRoute '/not-found/via-beforeLoad-target-root': typeof NotFoundViaBeforeLoadTargetRootRoute @@ -632,6 +685,7 @@ export interface FileRoutesById { '/_layout/_layout-2/layout-a': typeof LayoutLayout2LayoutARoute '/_layout/_layout-2/layout-b': typeof LayoutLayout2LayoutBRoute '/api/users/$id': typeof ApiUsersIdRoute + '/issue-6221/article/$id': typeof Issue6221ArticleIdRoute '/not-found/parent-boundary/via-beforeLoad': typeof NotFoundParentBoundaryViaBeforeLoadRoute '/posts_/$postId/deep': typeof PostsPostIdDeepRoute '/redirect/$target/via-beforeLoad': typeof RedirectTargetViaBeforeLoadRoute @@ -658,8 +712,11 @@ export interface FileRouteTypes { | '/search-params' | '/specialChars' | '/async-scripts' + | '/auth-docs' | '/client-only' | '/deferred' + | '/execution-local' + | '/execution-rpc' | '/inline-scripts' | '/links' | '/plain-ts-type-assertion' @@ -674,6 +731,8 @@ export interface FileRouteTypes { | '/not-found/parent-boundary' | '/specialChars/malformed' | '/api/users' + | '/auth-docs/private' + | '/issue-6221/dashboard' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' | '/not-found/via-beforeLoad-target-root' @@ -704,6 +763,7 @@ export interface FileRouteTypes { | '/layout-a' | '/layout-b' | '/api/users/$id' + | '/issue-6221/article/$id' | '/not-found/parent-boundary/via-beforeLoad' | '/posts/$postId/deep' | '/redirect/$target/via-beforeLoad' @@ -726,8 +786,11 @@ export interface FileRouteTypes { | '/' | '/specialChars' | '/async-scripts' + | '/auth-docs' | '/client-only' | '/deferred' + | '/execution-local' + | '/execution-rpc' | '/inline-scripts' | '/links' | '/plain-ts-type-assertion' @@ -737,6 +800,8 @@ export interface FileRouteTypes { | '/type-only-reexport' | '/specialChars/malformed' | '/api/users' + | '/auth-docs/private' + | '/issue-6221/dashboard' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' | '/not-found/via-beforeLoad-target-root' @@ -766,6 +831,7 @@ export interface FileRouteTypes { | '/layout-a' | '/layout-b' | '/api/users/$id' + | '/issue-6221/article/$id' | '/not-found/parent-boundary/via-beforeLoad' | '/posts/$postId/deep' | '/redirect/$target/via-beforeLoad' @@ -790,8 +856,11 @@ export interface FileRouteTypes { | '/specialChars' | '/_layout' | '/async-scripts' + | '/auth-docs' | '/client-only' | '/deferred' + | '/execution-local' + | '/execution-rpc' | '/inline-scripts' | '/links' | '/plain-ts-type-assertion' @@ -807,6 +876,8 @@ export interface FileRouteTypes { | '/specialChars/malformed' | '/_layout/_layout-2' | '/api/users' + | '/auth-docs/private' + | '/issue-6221/dashboard' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' | '/not-found/via-beforeLoad-target-root' @@ -837,6 +908,7 @@ export interface FileRouteTypes { | '/_layout/_layout-2/layout-a' | '/_layout/_layout-2/layout-b' | '/api/users/$id' + | '/issue-6221/article/$id' | '/not-found/parent-boundary/via-beforeLoad' | '/posts_/$postId/deep' | '/redirect/$target/via-beforeLoad' @@ -863,8 +935,11 @@ export interface RootRouteChildren { SpecialCharsRouteRoute: typeof SpecialCharsRouteRouteWithChildren LayoutRoute: typeof LayoutRouteWithChildren AsyncScriptsRoute: typeof AsyncScriptsRoute + AuthDocsRoute: typeof AuthDocsRouteWithChildren ClientOnlyRoute: typeof ClientOnlyRoute DeferredRoute: typeof DeferredRoute + ExecutionLocalRoute: typeof ExecutionLocalRoute + ExecutionRpcRoute: typeof ExecutionRpcRoute InlineScriptsRoute: typeof InlineScriptsRoute LinksRoute: typeof LinksRoute PlainTsTypeAssertionRoute: typeof PlainTsTypeAssertionRoute @@ -876,105 +951,23 @@ export interface RootRouteChildren { TypeOnlyReexportRoute: typeof TypeOnlyReexportRoute UsersRoute: typeof UsersRouteWithChildren ApiUsersRoute: typeof ApiUsersRouteWithChildren + Issue6221DashboardRoute: typeof Issue6221DashboardRoute MultiCookieRedirectTargetRoute: typeof MultiCookieRedirectTargetRoute RedirectTargetRoute: typeof RedirectTargetRouteWithChildren MultiCookieRedirectIndexRoute: typeof MultiCookieRedirectIndexRoute RedirectIndexRoute: typeof RedirectIndexRoute + Issue6221ArticleIdRoute: typeof Issue6221ArticleIdRoute PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute FooBarQuxHereRoute: typeof FooBarQuxHereRouteWithChildren } declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport - parentRoute: typeof rootRouteImport - } - '/type-only-reexport': { - id: '/type-only-reexport' - path: '/type-only-reexport' - fullPath: '/type-only-reexport' - preLoaderRoute: typeof TypeOnlyReexportRouteImport - parentRoute: typeof rootRouteImport - } - '/stream': { - id: '/stream' - path: '/stream' - fullPath: '/stream' - preLoaderRoute: typeof StreamRouteImport - parentRoute: typeof rootRouteImport - } - '/scripts': { - id: '/scripts' - path: '/scripts' - fullPath: '/scripts' - preLoaderRoute: typeof ScriptsRouteImport - parentRoute: typeof rootRouteImport - } - '/raw-stream': { - id: '/raw-stream' - path: '/raw-stream' - fullPath: '/raw-stream' - preLoaderRoute: typeof RawStreamRouteImport - parentRoute: typeof rootRouteImport - } - '/primitive-beforeload-error': { - id: '/primitive-beforeload-error' - path: '/primitive-beforeload-error' - fullPath: '/primitive-beforeload-error' - preLoaderRoute: typeof PrimitiveBeforeloadErrorRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/plain-ts-type-assertion': { - id: '/plain-ts-type-assertion' - path: '/plain-ts-type-assertion' - fullPath: '/plain-ts-type-assertion' - preLoaderRoute: typeof PlainTsTypeAssertionRouteImport - parentRoute: typeof rootRouteImport - } - '/links': { - id: '/links' - path: '/links' - fullPath: '/links' - preLoaderRoute: typeof LinksRouteImport - parentRoute: typeof rootRouteImport - } - '/inline-scripts': { - id: '/inline-scripts' - path: '/inline-scripts' - fullPath: '/inline-scripts' - preLoaderRoute: typeof InlineScriptsRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/client-only': { - id: '/client-only' - path: '/client-only' - fullPath: '/client-only' - preLoaderRoute: typeof ClientOnlyRouteImport - parentRoute: typeof rootRouteImport - } - '/async-scripts': { - id: '/async-scripts' - path: '/async-scripts' - fullPath: '/async-scripts' - preLoaderRoute: typeof AsyncScriptsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -984,18 +977,60 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/specialChars': { - id: '/specialChars' - path: '/specialChars' - fullPath: '/specialChars' - preLoaderRoute: typeof SpecialCharsRouteRouteImport + '/async-scripts': { + id: '/async-scripts' + path: '/async-scripts' + fullPath: '/async-scripts' + preLoaderRoute: typeof AsyncScriptsRouteImport parentRoute: typeof rootRouteImport } - '/search-params': { - id: '/search-params' - path: '/search-params' - fullPath: '/search-params' - preLoaderRoute: typeof SearchParamsRouteRouteImport + '/auth-docs': { + id: '/auth-docs' + path: '/auth-docs' + fullPath: '/auth-docs' + preLoaderRoute: typeof AuthDocsRouteImport + parentRoute: typeof rootRouteImport + } + '/client-only': { + id: '/client-only' + path: '/client-only' + fullPath: '/client-only' + preLoaderRoute: typeof ClientOnlyRouteImport + parentRoute: typeof rootRouteImport + } + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/execution-local': { + id: '/execution-local' + path: '/execution-local' + fullPath: '/execution-local' + preLoaderRoute: typeof ExecutionLocalRouteImport + parentRoute: typeof rootRouteImport + } + '/execution-rpc': { + id: '/execution-rpc' + path: '/execution-rpc' + fullPath: '/execution-rpc' + preLoaderRoute: typeof ExecutionRpcRouteImport + parentRoute: typeof rootRouteImport + } + '/inline-scripts': { + id: '/inline-scripts' + path: '/inline-scripts' + fullPath: '/inline-scripts' + preLoaderRoute: typeof InlineScriptsRouteImport + parentRoute: typeof rootRouteImport + } + '/links': { + id: '/links' + path: '/links' + fullPath: '/links' + preLoaderRoute: typeof LinksRouteImport parentRoute: typeof rootRouteImport } '/not-found': { @@ -1005,200 +1040,74 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof NotFoundRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/plain-ts-type-assertion': { + id: '/plain-ts-type-assertion' + path: '/plain-ts-type-assertion' + fullPath: '/plain-ts-type-assertion' + preLoaderRoute: typeof PlainTsTypeAssertionRouteImport parentRoute: typeof rootRouteImport } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute - } - '/search-params/': { - id: '/search-params/' - path: '/' - fullPath: '/search-params/' - preLoaderRoute: typeof SearchParamsIndexRouteImport - parentRoute: typeof SearchParamsRouteRoute - } - '/redirect/': { - id: '/redirect/' - path: '/redirect' - fullPath: '/redirect/' - preLoaderRoute: typeof RedirectIndexRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/raw-stream/': { - id: '/raw-stream/' - path: '/' - fullPath: '/raw-stream/' - preLoaderRoute: typeof RawStreamIndexRouteImport - parentRoute: typeof RawStreamRoute - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/not-found/': { - id: '/not-found/' - path: '/' - fullPath: '/not-found/' - preLoaderRoute: typeof NotFoundIndexRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/multi-cookie-redirect/': { - id: '/multi-cookie-redirect/' - path: '/multi-cookie-redirect' - fullPath: '/multi-cookie-redirect/' - preLoaderRoute: typeof MultiCookieRedirectIndexRouteImport + '/primitive-beforeload-error': { + id: '/primitive-beforeload-error' + path: '/primitive-beforeload-error' + fullPath: '/primitive-beforeload-error' + preLoaderRoute: typeof PrimitiveBeforeloadErrorRouteImport parentRoute: typeof rootRouteImport } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/specialChars/대한민국': { - id: '/specialChars/대한민국' - path: '/대한민국' - fullPath: '/specialChars/대한민국' - preLoaderRoute: typeof SpecialCharsChar45824Char54620Char48124Char44397RouteImport - parentRoute: typeof SpecialCharsRouteRoute - } - '/specialChars/search': { - id: '/specialChars/search' - path: '/search' - fullPath: '/specialChars/search' - preLoaderRoute: typeof SpecialCharsSearchRouteImport - parentRoute: typeof SpecialCharsRouteRoute - } - '/specialChars/hash': { - id: '/specialChars/hash' - path: '/hash' - fullPath: '/specialChars/hash' - preLoaderRoute: typeof SpecialCharsHashRouteImport - parentRoute: typeof SpecialCharsRouteRoute - } - '/specialChars/$param': { - id: '/specialChars/$param' - path: '/$param' - fullPath: '/specialChars/$param' - preLoaderRoute: typeof SpecialCharsParamRouteImport - parentRoute: typeof SpecialCharsRouteRoute - } - '/search-params/loader-throws-redirect': { - id: '/search-params/loader-throws-redirect' - path: '/loader-throws-redirect' - fullPath: '/search-params/loader-throws-redirect' - preLoaderRoute: typeof SearchParamsLoaderThrowsRedirectRouteImport - parentRoute: typeof SearchParamsRouteRoute - } - '/search-params/default': { - id: '/search-params/default' - path: '/default' - fullPath: '/search-params/default' - preLoaderRoute: typeof SearchParamsDefaultRouteImport - parentRoute: typeof SearchParamsRouteRoute - } - '/redirect/$target': { - id: '/redirect/$target' - path: '/redirect/$target' - fullPath: '/redirect/$target' - preLoaderRoute: typeof RedirectTargetRouteImport + '/raw-stream': { + id: '/raw-stream' + path: '/raw-stream' + fullPath: '/raw-stream' + preLoaderRoute: typeof RawStreamRouteImport parentRoute: typeof rootRouteImport } - '/raw-stream/ssr-text-hint': { - id: '/raw-stream/ssr-text-hint' - path: '/ssr-text-hint' - fullPath: '/raw-stream/ssr-text-hint' - preLoaderRoute: typeof RawStreamSsrTextHintRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-single': { - id: '/raw-stream/ssr-single' - path: '/ssr-single' - fullPath: '/raw-stream/ssr-single' - preLoaderRoute: typeof RawStreamSsrSingleRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-multiple': { - id: '/raw-stream/ssr-multiple' - path: '/ssr-multiple' - fullPath: '/raw-stream/ssr-multiple' - preLoaderRoute: typeof RawStreamSsrMultipleRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-mixed': { - id: '/raw-stream/ssr-mixed' - path: '/ssr-mixed' - fullPath: '/raw-stream/ssr-mixed' - preLoaderRoute: typeof RawStreamSsrMixedRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-binary-hint': { - id: '/raw-stream/ssr-binary-hint' - path: '/ssr-binary-hint' - fullPath: '/raw-stream/ssr-binary-hint' - preLoaderRoute: typeof RawStreamSsrBinaryHintRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/client-call': { - id: '/raw-stream/client-call' - path: '/client-call' - fullPath: '/raw-stream/client-call' - preLoaderRoute: typeof RawStreamClientCallRouteImport - parentRoute: typeof RawStreamRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/not-found/via-loader': { - id: '/not-found/via-loader' - path: '/via-loader' - fullPath: '/not-found/via-loader' - preLoaderRoute: typeof NotFoundViaLoaderRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/not-found/via-beforeLoad-target-root': { - id: '/not-found/via-beforeLoad-target-root' - path: '/via-beforeLoad-target-root' - fullPath: '/not-found/via-beforeLoad-target-root' - preLoaderRoute: typeof NotFoundViaBeforeLoadTargetRootRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/not-found/via-beforeLoad': { - id: '/not-found/via-beforeLoad' - path: '/via-beforeLoad' - fullPath: '/not-found/via-beforeLoad' - preLoaderRoute: typeof NotFoundViaBeforeLoadRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/multi-cookie-redirect/target': { - id: '/multi-cookie-redirect/target' - path: '/multi-cookie-redirect/target' - fullPath: '/multi-cookie-redirect/target' - preLoaderRoute: typeof MultiCookieRedirectTargetRouteImport + '/scripts': { + id: '/scripts' + path: '/scripts' + fullPath: '/scripts' + preLoaderRoute: typeof ScriptsRouteImport parentRoute: typeof rootRouteImport } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/search-params': { + id: '/search-params' + path: '/search-params' + fullPath: '/search-params' + preLoaderRoute: typeof SearchParamsRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/specialChars': { + id: '/specialChars' + path: '/specialChars' + fullPath: '/specialChars' + preLoaderRoute: typeof SpecialCharsRouteRouteImport + parentRoute: typeof rootRouteImport + } + '/stream': { + id: '/stream' + path: '/stream' + fullPath: '/stream' + preLoaderRoute: typeof StreamRouteImport + parentRoute: typeof rootRouteImport + } + '/type-only-reexport': { + id: '/type-only-reexport' + path: '/type-only-reexport' + fullPath: '/type-only-reexport' + preLoaderRoute: typeof TypeOnlyReexportRouteImport + parentRoute: typeof rootRouteImport + } + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/_layout/_layout-2': { @@ -1208,18 +1117,46 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LayoutLayout2RouteImport parentRoute: typeof LayoutRoute } - '/specialChars/malformed': { - id: '/specialChars/malformed' - path: '/malformed' - fullPath: '/specialChars/malformed' - preLoaderRoute: typeof SpecialCharsMalformedRouteRouteImport - parentRoute: typeof SpecialCharsRouteRoute + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport + parentRoute: typeof rootRouteImport } - '/not-found/parent-boundary': { - id: '/not-found/parent-boundary' - path: '/parent-boundary' - fullPath: '/not-found/parent-boundary' - preLoaderRoute: typeof NotFoundParentBoundaryRouteRouteImport + '/auth-docs/private': { + id: '/auth-docs/private' + path: '/private' + fullPath: '/auth-docs/private' + preLoaderRoute: typeof AuthDocsPrivateRouteImport + parentRoute: typeof AuthDocsRoute + } + '/issue-6221/dashboard': { + id: '/issue-6221/dashboard' + path: '/issue-6221/dashboard' + fullPath: '/issue-6221/dashboard' + preLoaderRoute: typeof Issue6221DashboardRouteImport + parentRoute: typeof rootRouteImport + } + '/multi-cookie-redirect/': { + id: '/multi-cookie-redirect/' + path: '/multi-cookie-redirect' + fullPath: '/multi-cookie-redirect/' + preLoaderRoute: typeof MultiCookieRedirectIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/multi-cookie-redirect/target': { + id: '/multi-cookie-redirect/target' + path: '/multi-cookie-redirect/target' + fullPath: '/multi-cookie-redirect/target' + preLoaderRoute: typeof MultiCookieRedirectTargetRouteImport + parentRoute: typeof rootRouteImport + } + '/not-found/': { + id: '/not-found/' + path: '/' + fullPath: '/not-found/' + preLoaderRoute: typeof NotFoundIndexRouteImport parentRoute: typeof NotFoundRouteRoute } '/not-found/deep': { @@ -1229,19 +1166,208 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof NotFoundDeepRouteRouteImport parentRoute: typeof NotFoundRouteRoute } - '/redirect/$target/': { - id: '/redirect/$target/' - path: '/' - fullPath: '/redirect/$target/' - preLoaderRoute: typeof RedirectTargetIndexRouteImport - parentRoute: typeof RedirectTargetRoute + '/not-found/parent-boundary': { + id: '/not-found/parent-boundary' + path: '/parent-boundary' + fullPath: '/not-found/parent-boundary' + preLoaderRoute: typeof NotFoundParentBoundaryRouteRouteImport + parentRoute: typeof NotFoundRouteRoute } - '/not-found/parent-boundary/': { - id: '/not-found/parent-boundary/' + '/not-found/via-beforeLoad': { + id: '/not-found/via-beforeLoad' + path: '/via-beforeLoad' + fullPath: '/not-found/via-beforeLoad' + preLoaderRoute: typeof NotFoundViaBeforeLoadRouteImport + parentRoute: typeof NotFoundRouteRoute + } + '/not-found/via-beforeLoad-target-root': { + id: '/not-found/via-beforeLoad-target-root' + path: '/via-beforeLoad-target-root' + fullPath: '/not-found/via-beforeLoad-target-root' + preLoaderRoute: typeof NotFoundViaBeforeLoadTargetRootRouteImport + parentRoute: typeof NotFoundRouteRoute + } + '/not-found/via-loader': { + id: '/not-found/via-loader' + path: '/via-loader' + fullPath: '/not-found/via-loader' + preLoaderRoute: typeof NotFoundViaLoaderRouteImport + parentRoute: typeof NotFoundRouteRoute + } + '/posts/': { + id: '/posts/' path: '/' - fullPath: '/not-found/parent-boundary/' - preLoaderRoute: typeof NotFoundParentBoundaryIndexRouteImport - parentRoute: typeof NotFoundParentBoundaryRouteRoute + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/raw-stream/': { + id: '/raw-stream/' + path: '/' + fullPath: '/raw-stream/' + preLoaderRoute: typeof RawStreamIndexRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/client-call': { + id: '/raw-stream/client-call' + path: '/client-call' + fullPath: '/raw-stream/client-call' + preLoaderRoute: typeof RawStreamClientCallRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-binary-hint': { + id: '/raw-stream/ssr-binary-hint' + path: '/ssr-binary-hint' + fullPath: '/raw-stream/ssr-binary-hint' + preLoaderRoute: typeof RawStreamSsrBinaryHintRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-mixed': { + id: '/raw-stream/ssr-mixed' + path: '/ssr-mixed' + fullPath: '/raw-stream/ssr-mixed' + preLoaderRoute: typeof RawStreamSsrMixedRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-multiple': { + id: '/raw-stream/ssr-multiple' + path: '/ssr-multiple' + fullPath: '/raw-stream/ssr-multiple' + preLoaderRoute: typeof RawStreamSsrMultipleRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-single': { + id: '/raw-stream/ssr-single' + path: '/ssr-single' + fullPath: '/raw-stream/ssr-single' + preLoaderRoute: typeof RawStreamSsrSingleRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-text-hint': { + id: '/raw-stream/ssr-text-hint' + path: '/ssr-text-hint' + fullPath: '/raw-stream/ssr-text-hint' + preLoaderRoute: typeof RawStreamSsrTextHintRouteImport + parentRoute: typeof RawStreamRoute + } + '/redirect/': { + id: '/redirect/' + path: '/redirect' + fullPath: '/redirect/' + preLoaderRoute: typeof RedirectIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect/$target': { + id: '/redirect/$target' + path: '/redirect/$target' + fullPath: '/redirect/$target' + preLoaderRoute: typeof RedirectTargetRouteImport + parentRoute: typeof rootRouteImport + } + '/search-params/': { + id: '/search-params/' + path: '/' + fullPath: '/search-params/' + preLoaderRoute: typeof SearchParamsIndexRouteImport + parentRoute: typeof SearchParamsRouteRoute + } + '/search-params/default': { + id: '/search-params/default' + path: '/default' + fullPath: '/search-params/default' + preLoaderRoute: typeof SearchParamsDefaultRouteImport + parentRoute: typeof SearchParamsRouteRoute + } + '/search-params/loader-throws-redirect': { + id: '/search-params/loader-throws-redirect' + path: '/loader-throws-redirect' + fullPath: '/search-params/loader-throws-redirect' + preLoaderRoute: typeof SearchParamsLoaderThrowsRedirectRouteImport + parentRoute: typeof SearchParamsRouteRoute + } + '/specialChars/$param': { + id: '/specialChars/$param' + path: '/$param' + fullPath: '/specialChars/$param' + preLoaderRoute: typeof SpecialCharsParamRouteImport + parentRoute: typeof SpecialCharsRouteRoute + } + '/specialChars/hash': { + id: '/specialChars/hash' + path: '/hash' + fullPath: '/specialChars/hash' + preLoaderRoute: typeof SpecialCharsHashRouteImport + parentRoute: typeof SpecialCharsRouteRoute + } + '/specialChars/malformed': { + id: '/specialChars/malformed' + path: '/malformed' + fullPath: '/specialChars/malformed' + preLoaderRoute: typeof SpecialCharsMalformedRouteRouteImport + parentRoute: typeof SpecialCharsRouteRoute + } + '/specialChars/search': { + id: '/specialChars/search' + path: '/search' + fullPath: '/specialChars/search' + preLoaderRoute: typeof SpecialCharsSearchRouteImport + parentRoute: typeof SpecialCharsRouteRoute + } + '/specialChars/대한민국': { + id: '/specialChars/대한민국' + path: '/대한민국' + fullPath: '/specialChars/대한민국' + preLoaderRoute: typeof SpecialCharsChar45824Char54620Char48124Char44397RouteImport + parentRoute: typeof SpecialCharsRouteRoute + } + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute + } + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route + } + '/_layout/_layout-2/layout-b': { + id: '/_layout/_layout-2/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport + parentRoute: typeof LayoutLayout2Route + } + '/api/users/$id': { + id: '/api/users/$id' + path: '/$id' + fullPath: '/api/users/$id' + preLoaderRoute: typeof ApiUsersIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/issue-6221/article/$id': { + id: '/issue-6221/article/$id' + path: '/issue-6221/article/$id' + fullPath: '/issue-6221/article/$id' + preLoaderRoute: typeof Issue6221ArticleIdRouteImport + parentRoute: typeof rootRouteImport } '/not-found/deep/': { id: '/not-found/deep/' @@ -1250,25 +1376,39 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof NotFoundDeepIndexRouteImport parentRoute: typeof NotFoundDeepRouteRoute } - '/specialChars/malformed/search': { - id: '/specialChars/malformed/search' - path: '/search' - fullPath: '/specialChars/malformed/search' - preLoaderRoute: typeof SpecialCharsMalformedSearchRouteImport - parentRoute: typeof SpecialCharsMalformedRouteRoute + '/not-found/deep/b': { + id: '/not-found/deep/b' + path: '/b' + fullPath: '/not-found/deep/b' + preLoaderRoute: typeof NotFoundDeepBRouteRouteImport + parentRoute: typeof NotFoundDeepRouteRoute } - '/specialChars/malformed/$param': { - id: '/specialChars/malformed/$param' - path: '/$param' - fullPath: '/specialChars/malformed/$param' - preLoaderRoute: typeof SpecialCharsMalformedParamRouteImport - parentRoute: typeof SpecialCharsMalformedRouteRoute + '/not-found/parent-boundary/': { + id: '/not-found/parent-boundary/' + path: '/' + fullPath: '/not-found/parent-boundary/' + preLoaderRoute: typeof NotFoundParentBoundaryIndexRouteImport + parentRoute: typeof NotFoundParentBoundaryRouteRoute } - '/redirect/$target/via-loader': { - id: '/redirect/$target/via-loader' - path: '/via-loader' - fullPath: '/redirect/$target/via-loader' - preLoaderRoute: typeof RedirectTargetViaLoaderRouteImport + '/not-found/parent-boundary/via-beforeLoad': { + id: '/not-found/parent-boundary/via-beforeLoad' + path: '/via-beforeLoad' + fullPath: '/not-found/parent-boundary/via-beforeLoad' + preLoaderRoute: typeof NotFoundParentBoundaryViaBeforeLoadRouteImport + parentRoute: typeof NotFoundParentBoundaryRouteRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect/$target/': { + id: '/redirect/$target/' + path: '/' + fullPath: '/redirect/$target/' + preLoaderRoute: typeof RedirectTargetIndexRouteImport parentRoute: typeof RedirectTargetRoute } '/redirect/$target/via-beforeLoad': { @@ -1278,75 +1418,26 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof RedirectTargetViaBeforeLoadRouteImport parentRoute: typeof RedirectTargetRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport - } - '/not-found/parent-boundary/via-beforeLoad': { - id: '/not-found/parent-boundary/via-beforeLoad' - path: '/via-beforeLoad' - fullPath: '/not-found/parent-boundary/via-beforeLoad' - preLoaderRoute: typeof NotFoundParentBoundaryViaBeforeLoadRouteImport - parentRoute: typeof NotFoundParentBoundaryRouteRoute - } - '/api/users/$id': { - id: '/api/users/$id' - path: '/$id' - fullPath: '/api/users/$id' - preLoaderRoute: typeof ApiUsersIdRouteImport - parentRoute: typeof ApiUsersRoute - } - '/_layout/_layout-2/layout-b': { - id: '/_layout/_layout-2/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport - parentRoute: typeof LayoutLayout2Route - } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route - } - '/not-found/deep/b': { - id: '/not-found/deep/b' - path: '/b' - fullPath: '/not-found/deep/b' - preLoaderRoute: typeof NotFoundDeepBRouteRouteImport - parentRoute: typeof NotFoundDeepRouteRoute - } - '/redirect/$target/serverFn/': { - id: '/redirect/$target/serverFn/' - path: '/serverFn' - fullPath: '/redirect/$target/serverFn/' - preLoaderRoute: typeof RedirectTargetServerFnIndexRouteImport + '/redirect/$target/via-loader': { + id: '/redirect/$target/via-loader' + path: '/via-loader' + fullPath: '/redirect/$target/via-loader' + preLoaderRoute: typeof RedirectTargetViaLoaderRouteImport parentRoute: typeof RedirectTargetRoute } - '/redirect/$target/serverFn/via-useServerFn': { - id: '/redirect/$target/serverFn/via-useServerFn' - path: '/serverFn/via-useServerFn' - fullPath: '/redirect/$target/serverFn/via-useServerFn' - preLoaderRoute: typeof RedirectTargetServerFnViaUseServerFnRouteImport - parentRoute: typeof RedirectTargetRoute + '/specialChars/malformed/$param': { + id: '/specialChars/malformed/$param' + path: '/$param' + fullPath: '/specialChars/malformed/$param' + preLoaderRoute: typeof SpecialCharsMalformedParamRouteImport + parentRoute: typeof SpecialCharsMalformedRouteRoute } - '/redirect/$target/serverFn/via-loader': { - id: '/redirect/$target/serverFn/via-loader' - path: '/serverFn/via-loader' - fullPath: '/redirect/$target/serverFn/via-loader' - preLoaderRoute: typeof RedirectTargetServerFnViaLoaderRouteImport - parentRoute: typeof RedirectTargetRoute - } - '/redirect/$target/serverFn/via-beforeLoad': { - id: '/redirect/$target/serverFn/via-beforeLoad' - path: '/serverFn/via-beforeLoad' - fullPath: '/redirect/$target/serverFn/via-beforeLoad' - preLoaderRoute: typeof RedirectTargetServerFnViaBeforeLoadRouteImport - parentRoute: typeof RedirectTargetRoute + '/specialChars/malformed/search': { + id: '/specialChars/malformed/search' + path: '/search' + fullPath: '/specialChars/malformed/search' + preLoaderRoute: typeof SpecialCharsMalformedSearchRouteImport + parentRoute: typeof SpecialCharsMalformedRouteRoute } '/foo/$bar/$qux/_here': { id: '/foo/$bar/$qux/_here' @@ -1362,6 +1453,34 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof NotFoundDeepBCRouteRouteImport parentRoute: typeof NotFoundDeepBRouteRoute } + '/redirect/$target/serverFn/': { + id: '/redirect/$target/serverFn/' + path: '/serverFn' + fullPath: '/redirect/$target/serverFn/' + preLoaderRoute: typeof RedirectTargetServerFnIndexRouteImport + parentRoute: typeof RedirectTargetRoute + } + '/redirect/$target/serverFn/via-beforeLoad': { + id: '/redirect/$target/serverFn/via-beforeLoad' + path: '/serverFn/via-beforeLoad' + fullPath: '/redirect/$target/serverFn/via-beforeLoad' + preLoaderRoute: typeof RedirectTargetServerFnViaBeforeLoadRouteImport + parentRoute: typeof RedirectTargetRoute + } + '/redirect/$target/serverFn/via-loader': { + id: '/redirect/$target/serverFn/via-loader' + path: '/serverFn/via-loader' + fullPath: '/redirect/$target/serverFn/via-loader' + preLoaderRoute: typeof RedirectTargetServerFnViaLoaderRouteImport + parentRoute: typeof RedirectTargetRoute + } + '/redirect/$target/serverFn/via-useServerFn': { + id: '/redirect/$target/serverFn/via-useServerFn' + path: '/serverFn/via-useServerFn' + fullPath: '/redirect/$target/serverFn/via-useServerFn' + preLoaderRoute: typeof RedirectTargetServerFnViaUseServerFnRouteImport + parentRoute: typeof RedirectTargetRoute + } '/foo/$bar/$qux/_here/': { id: '/foo/$bar/$qux/_here/' path: '/' @@ -1530,6 +1649,18 @@ const LayoutRouteChildren: LayoutRouteChildren = { const LayoutRouteWithChildren = LayoutRoute._addFileChildren(LayoutRouteChildren) +interface AuthDocsRouteChildren { + AuthDocsPrivateRoute: typeof AuthDocsPrivateRoute +} + +const AuthDocsRouteChildren: AuthDocsRouteChildren = { + AuthDocsPrivateRoute: AuthDocsPrivateRoute, +} + +const AuthDocsRouteWithChildren = AuthDocsRoute._addFileChildren( + AuthDocsRouteChildren, +) + interface PostsRouteChildren { PostsPostIdRoute: typeof PostsPostIdRoute PostsIndexRoute: typeof PostsIndexRoute @@ -1635,8 +1766,11 @@ const rootRouteChildren: RootRouteChildren = { SpecialCharsRouteRoute: SpecialCharsRouteRouteWithChildren, LayoutRoute: LayoutRouteWithChildren, AsyncScriptsRoute: AsyncScriptsRoute, + AuthDocsRoute: AuthDocsRouteWithChildren, ClientOnlyRoute: ClientOnlyRoute, DeferredRoute: DeferredRoute, + ExecutionLocalRoute: ExecutionLocalRoute, + ExecutionRpcRoute: ExecutionRpcRoute, InlineScriptsRoute: InlineScriptsRoute, LinksRoute: LinksRoute, PlainTsTypeAssertionRoute: PlainTsTypeAssertionRoute, @@ -1648,10 +1782,12 @@ const rootRouteChildren: RootRouteChildren = { TypeOnlyReexportRoute: TypeOnlyReexportRoute, UsersRoute: UsersRouteWithChildren, ApiUsersRoute: ApiUsersRouteWithChildren, + Issue6221DashboardRoute: Issue6221DashboardRoute, MultiCookieRedirectTargetRoute: MultiCookieRedirectTargetRoute, RedirectTargetRoute: RedirectTargetRouteWithChildren, MultiCookieRedirectIndexRoute: MultiCookieRedirectIndexRoute, RedirectIndexRoute: RedirectIndexRoute, + Issue6221ArticleIdRoute: Issue6221ArticleIdRoute, PostsPostIdDeepRoute: PostsPostIdDeepRoute, FooBarQuxHereRoute: FooBarQuxHereRouteWithChildren, } diff --git a/e2e/react-start/basic/src/routes/__root.tsx b/e2e/react-start/basic/src/routes/__root.tsx index d8fc0d3b24..ed521817d6 100644 --- a/e2e/react-start/basic/src/routes/__root.tsx +++ b/e2e/react-start/basic/src/routes/__root.tsx @@ -197,6 +197,9 @@ function RootDocument({ children }: { children: React.ReactNode }) { > Client Only {' '} + + Server function loader + {' '} { console.info('Fetching users... @', request.url) - const res = await axios.get>(`${queryURL}/users`) + const res = await axios.get>( + 'https://jsonplaceholder.typicode.com/users', + ) const list = res.data.slice(0, 10) diff --git a/e2e/react-start/basic/src/routes/api/users.$id.ts b/e2e/react-start/basic/src/routes/api/users.$id.ts index ac665381f1..797dffb637 100644 --- a/e2e/react-start/basic/src/routes/api/users.$id.ts +++ b/e2e/react-start/basic/src/routes/api/users.$id.ts @@ -2,19 +2,15 @@ import { createFileRoute } from '@tanstack/react-router' import axios from 'redaxios' import type { User } from '~/utils/users' -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} - export const Route = createFileRoute('/api/users/$id')({ server: { handlers: { GET: async ({ request, params }) => { console.info(`Fetching users by id=${params.id}... @`, request.url) try { - const res = await axios.get(`${queryURL}/users/` + params.id) + const res = await axios.get( + `https://jsonplaceholder.typicode.com/users/${params.id}`, + ) return Response.json({ id: res.data.id, diff --git a/e2e/react-start/basic/src/routes/auth-docs.private.tsx b/e2e/react-start/basic/src/routes/auth-docs.private.tsx new file mode 100644 index 0000000000..85fc8a0fc9 --- /dev/null +++ b/e2e/react-start/basic/src/routes/auth-docs.private.tsx @@ -0,0 +1,17 @@ +import { createFileRoute, redirect } from '@tanstack/react-router' +import { getPrivateDataFn } from '../utils/auth-docs' + +export const Route = createFileRoute('/auth-docs/private')({ + beforeLoad: ({ context }) => { + if (!context.user) { + throw redirect({ to: '/auth-docs' }) + } + }, + loader: () => getPrivateDataFn(), + component: PrivatePage, +}) + +function PrivatePage() { + const message = Route.useLoaderData() + return

{message}

+} diff --git a/e2e/react-start/basic/src/routes/auth-docs.tsx b/e2e/react-start/basic/src/routes/auth-docs.tsx new file mode 100644 index 0000000000..6ea1b813ef --- /dev/null +++ b/e2e/react-start/basic/src/routes/auth-docs.tsx @@ -0,0 +1,100 @@ +import { + createFileRoute, + Outlet, + useHydrated, + useRouter, +} from '@tanstack/react-router' +import { useServerFn } from '@tanstack/react-start' +import { useState } from 'react' +import type { FormEvent } from 'react' +import { + getCurrentUserFn, + getPrivateDataFn, + loginFn, + logoutFn, +} from '../utils/auth-docs' + +export const Route = createFileRoute('/auth-docs')({ + beforeLoad: async () => ({ user: await getCurrentUserFn() }), + headers: () => ({ 'Cache-Control': 'private, no-store' }), + component: AuthDocs, +}) + +function AuthDocs() { + const hydrated = useHydrated() + const { user } = Route.useRouteContext() + const router = useRouter() + const login = useServerFn(loginFn) + const logout = useServerFn(logoutFn) + const getPrivateData = useServerFn(getPrivateDataFn) + const [isLoading, setIsLoading] = useState(false) + const [error, setError] = useState('') + const [privateResult, setPrivateResult] = useState('') + + const handleSubmit = async (event: FormEvent) => { + event.preventDefault() + const formData = new FormData(event.currentTarget) + const email = formData.get('email') + const password = formData.get('password') + if (typeof email !== 'string' || typeof password !== 'string') { + return + } + setIsLoading(true) + setError('') + try { + const result = await login({ data: { email, password } }) + if (result?.error) { + setError(result.error) + return + } + await router.invalidate() + } catch { + setError('Login failed. Please try again.') + } finally { + setIsLoading(false) + } + } + + return ( +
+

{user?.email ?? 'Signed out'}

+
+
+ + + +
+

{error}

+
+ + +

{privateResult}

+ +
+ ) +} diff --git a/e2e/react-start/basic/src/routes/execution-local.tsx b/e2e/react-start/basic/src/routes/execution-local.tsx new file mode 100644 index 0000000000..477cd81740 --- /dev/null +++ b/e2e/react-start/basic/src/routes/execution-local.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/react-router' +import { readOnlyOnServer } from '~/utils/execution-functions' + +// This intentionally fails during browser navigation. It is the negative case +// for the environment-functions troubleshooting guide. +export const Route = createFileRoute('/execution-local')({ + loader: () => readOnlyOnServer(), + component: Result, + errorComponent: ({ error }) => ( +

{error instanceof Error ? error.message : String(error)}

+ ), +}) + +function Result() { + return

{Route.useLoaderData()}

+} diff --git a/e2e/react-start/basic/src/routes/execution-rpc.tsx b/e2e/react-start/basic/src/routes/execution-rpc.tsx new file mode 100644 index 0000000000..f934015522 --- /dev/null +++ b/e2e/react-start/basic/src/routes/execution-rpc.tsx @@ -0,0 +1,18 @@ +import { createFileRoute, Link } from '@tanstack/react-router' +import { readThroughRpc } from '~/utils/execution-functions' + +export const Route = createFileRoute('/execution-rpc')({ + loader: () => readThroughRpc(), + component: Result, +}) + +function Result() { + return ( + <> +

{Route.useLoaderData()}

+ + Call the server-only helper directly + + + ) +} diff --git a/e2e/react-start/basic/src/routes/issue-6221.article.$id.tsx b/e2e/react-start/basic/src/routes/issue-6221.article.$id.tsx new file mode 100644 index 0000000000..c923a5f1cb --- /dev/null +++ b/e2e/react-start/basic/src/routes/issue-6221.article.$id.tsx @@ -0,0 +1,42 @@ +import { Link, createFileRoute } from '@tanstack/react-router' +import { createClientOnlyFn } from '@tanstack/react-start' + +const isAuthed = createClientOnlyFn( + () => localStorage.getItem('issue-6221-auth') === 'good', +) + +const fetchArticle = async (id: string) => { + await new Promise((resolve) => setTimeout(resolve, 1000)) + return isAuthed() + ? { + title: `Article Title for ${id}`, + content: `Article content for ${id}`, + } + : null +} + +export const Route = createFileRoute('/issue-6221/article/$id')({ + ssr: false, + loader: ({ params }) => fetchArticle(params.id), + head: ({ loaderData }) => ({ + meta: [{ title: loaderData?.title ?? 'title n/a' }], + }), + component: Article, +}) + +function Article() { + const article = Route.useLoaderData() + + return ( +
+ + Dashboard + + {article ? ( +
{article.content}
+ ) : ( +
Article Not Accessible.
+ )} +
+ ) +} diff --git a/e2e/react-start/basic/src/routes/issue-6221.dashboard.tsx b/e2e/react-start/basic/src/routes/issue-6221.dashboard.tsx new file mode 100644 index 0000000000..8c93da669c --- /dev/null +++ b/e2e/react-start/basic/src/routes/issue-6221.dashboard.tsx @@ -0,0 +1,6 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/issue-6221/dashboard')({ + head: () => ({ meta: [{ title: 'Dashboard' }] }), + component: () =>
Dashboard
, +}) diff --git a/e2e/react-start/basic/src/utils/auth-docs.ts b/e2e/react-start/basic/src/utils/auth-docs.ts new file mode 100644 index 0000000000..22b36ee808 --- /dev/null +++ b/e2e/react-start/basic/src/utils/auth-docs.ts @@ -0,0 +1,60 @@ +import { createServerFn } from '@tanstack/react-start' +import { redirect } from '@tanstack/react-router' +import { getCookie, setCookie } from '@tanstack/react-start/server' +import { getIronSession } from 'iron-session' + +function getSession() { + return getIronSession<{ email: string }>( + { read: getCookie, write: setCookie }, + { + cookieName: 'auth-docs-test', + password: 'authentication-docs-browser-test-secret-only-2026', + ttl: 60 * 60, + cookieOptions: { + httpOnly: true, + secure: false, + sameSite: 'lax', + path: '/', + }, + }, + ) +} + +export const getCurrentUserFn = createServerFn({ method: 'GET' }).handler( + async () => { + const session = await getSession() + return session.email ? { email: session.email } : null + }, +) + +export const loginFn = createServerFn({ method: 'POST' }) + .validator((data: { email: string; password: string }) => data) + .handler(async ({ data }) => { + // Fixed credentials belong only to this browser-test fixture. + if ( + data.email !== 'reader@example.com' || + data.password !== 'test-password' + ) { + return { error: 'Invalid credentials' } + } + const session = await getSession() + session.email = data.email + await session.save() + throw redirect({ to: '/auth-docs/private' }) + }) + +export const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { + const session = await getSession() + session.destroy() + throw redirect({ to: '/auth-docs' }) +}) + +export const getPrivateDataFn = createServerFn({ method: 'GET' }).handler( + async () => { + const session = await getSession() + if (!session.email) { + throw new Error('Unauthorized') + } + return 'Private account data' + }, +) diff --git a/e2e/react-start/basic/src/utils/execution-functions.ts b/e2e/react-start/basic/src/utils/execution-functions.ts new file mode 100644 index 0000000000..97e66573d8 --- /dev/null +++ b/e2e/react-start/basic/src/utils/execution-functions.ts @@ -0,0 +1,5 @@ +import { createServerFn, createServerOnlyFn } from '@tanstack/react-start' + +export const readOnlyOnServer = createServerOnlyFn(() => 'Read on the server') + +export const readThroughRpc = createServerFn().handler(() => readOnlyOnServer()) diff --git a/e2e/react-start/basic/src/utils/posts.tsx b/e2e/react-start/basic/src/utils/posts.tsx index 4cc5dcc4c6..9fdff27673 100644 --- a/e2e/react-start/basic/src/utils/posts.tsx +++ b/e2e/react-start/basic/src/utils/posts.tsx @@ -8,18 +8,12 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} - export const fetchPost = createServerFn({ method: 'GET' }) .validator((postId: string) => postId) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios - .get(`${queryURL}/posts/${postId}`) + .get(`https://jsonplaceholder.typicode.com/posts/${postId}`) .then((r) => r.data) .catch((err) => { console.error(err) @@ -36,7 +30,7 @@ export const fetchPosts = createServerFn({ method: 'GET' }).handler( async () => { console.info('Fetching posts...') return axios - .get>(`${queryURL}/posts`) + .get>('https://jsonplaceholder.typicode.com/posts') .then((r) => r.data.slice(0, 10)) }, ) diff --git a/e2e/react-start/basic/src/utils/users.tsx b/e2e/react-start/basic/src/utils/users.tsx index 46be4b1580..7ba645b383 100644 --- a/e2e/react-start/basic/src/utils/users.tsx +++ b/e2e/react-start/basic/src/utils/users.tsx @@ -3,7 +3,3 @@ export type User = { name: string email: string } - -const PORT = process.env.VITE_SERVER_PORT || 3000 - -export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/react-start/basic/tests/auth-docs.spec.ts b/e2e/react-start/basic/tests/auth-docs.spec.ts new file mode 100644 index 0000000000..47a57c9da2 --- /dev/null +++ b/e2e/react-start/basic/tests/auth-docs.spec.ts @@ -0,0 +1,89 @@ +import { expect, test } from '@playwright/test' +import { isSpaMode } from './utils/isSpaMode' + +test('authentication docs pattern handles login, logout, route context, and server authorization', async ({ + page, +}) => { + await page.goto('/auth-docs/private') + await expect(page).toHaveURL(/\/auth-docs$/) + await expect(page.getByTestId('auth-docs-user')).toHaveText('Signed out') + + await page + .getByRole('button', { name: 'Request private data directly' }) + .click() + await expect(page.getByTestId('auth-docs-private-result')).toHaveText( + 'Access denied', + ) + + await page.getByLabel('Email', { exact: true }).fill('reader@example.com') + await page.getByLabel('Password', { exact: true }).fill('wrong-password') + await page.getByRole('button', { name: 'Login', exact: true }).click() + await expect(page.getByRole('alert')).toHaveText('Invalid credentials') + await expect(page.getByTestId('auth-docs-user')).toHaveText('Signed out') + + await page.getByLabel('Password', { exact: true }).fill('test-password') + await page.getByRole('button', { name: 'Login', exact: true }).click() + await expect(page).toHaveURL(/\/auth-docs\/private$/) + await expect(page.getByTestId('auth-docs-user')).toHaveText( + 'reader@example.com', + ) + await expect(page.getByTestId('auth-docs-private-page')).toHaveText( + 'Private account data', + ) + + const response = await page.reload() + expect(response?.status()).toBe(200) + if (isSpaMode) { + // The shared SPA shell must not contain authenticated account data. + expect(await response?.text()).not.toContain('reader@example.com') + expect(await response?.text()).not.toContain('Private account data') + } else { + expect(response?.headers()['cache-control']).toBe('private, no-store') + } + await expect(page.getByTestId('auth-docs-user')).toHaveText( + 'reader@example.com', + ) + await page.getByRole('button', { name: 'Logout', exact: true }).click() + await expect(page).toHaveURL(/\/auth-docs$/) + await expect(page.getByTestId('auth-docs-user')).toHaveText('Signed out') + await page + .getByRole('button', { name: 'Request private data directly' }) + .click() + await expect(page.getByTestId('auth-docs-private-result')).toHaveText( + 'Access denied', + ) + await page.goto('/auth-docs/private') + await expect(page).toHaveURL(/\/auth-docs$/) +}) + +test('the authentication form cannot submit credentials before hydration', async ({ + browser, + baseURL, +}) => { + const context = await browser.newContext({ + javaScriptEnabled: false, + baseURL, + }) + const page = await context.newPage() + try { + await page.goto('/auth-docs') + if (isSpaMode) { + // Without JavaScript, the SPA shell cannot render credential controls. + await expect(page.locator('form')).toHaveCount(0) + await expect(page.getByLabel('Email', { exact: true })).toHaveCount(0) + await expect(page.getByLabel('Password', { exact: true })).toHaveCount(0) + await expect( + page.getByRole('button', { name: 'Login', exact: true }), + ).toHaveCount(0) + } else { + await expect(page.locator('form')).toHaveAttribute('method', 'post') + await expect(page.getByLabel('Email', { exact: true })).toBeDisabled() + await expect(page.getByLabel('Password', { exact: true })).toBeDisabled() + await expect( + page.getByRole('button', { name: 'Login', exact: true }), + ).toBeDisabled() + } + } finally { + await context.close() + } +}) diff --git a/e2e/react-start/basic/tests/client-only.spec.ts b/e2e/react-start/basic/tests/client-only.spec.ts index a3b6f99442..299744f636 100644 --- a/e2e/react-start/basic/tests/client-only.spec.ts +++ b/e2e/react-start/basic/tests/client-only.spec.ts @@ -1,5 +1,6 @@ import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' +import { isSpaMode } from './utils/isSpaMode' /** * These tests verify the compiler optimization. @@ -15,7 +16,15 @@ import { test } from '@tanstack/router-e2e-utils' test('ClientOnly renders fallback on server, then client content after hydration', async ({ page, + request, }) => { + const response = await request.get('/client-only') + expect(response.status()).toBe(200) + const html = await response.text() + expect(html).not.toContain('data-testid="window-size"') + if (!isSpaMode) { + expect(html).toContain('Loading window size...') + } // Navigate directly to the client-only route // If the compiler optimization isn't working, this would crash the server // because WindowSize.tsx accesses `window` at module scope diff --git a/e2e/react-start/basic/tests/environment-functions.spec.ts b/e2e/react-start/basic/tests/environment-functions.spec.ts new file mode 100644 index 0000000000..410b1d999e --- /dev/null +++ b/e2e/react-start/basic/tests/environment-functions.spec.ts @@ -0,0 +1,46 @@ +import { expect, test } from '@playwright/test' +import { isSpaMode } from './utils/isSpaMode' + +const guardError = + 'createServerOnlyFn() functions can only be called on the server!' + +test('a server-only loader works on the server but rejects client navigation', async ({ + page, + request, +}) => { + const direct = await request.get('/execution-local') + expect(direct.status()).toBe(200) + if (!isSpaMode) { + expect(await direct.text()).toContain('Read on the server') + } + await page.goto('/execution-rpc') + await expect(page.getByTestId('execution-result')).toHaveText( + 'Read on the server', + ) + await page + .getByRole('link', { name: 'Call the server-only helper directly' }) + .click() + await expect(page.getByRole('alert')).toHaveText(guardError) +}) + +test('a server function preserves the loader result on direct requests and navigation', async ({ + page, + request, +}) => { + const direct = await request.get('/execution-rpc') + expect(direct.status()).toBe(200) + if (!isSpaMode) { + expect(await direct.text()).toContain('Read on the server') + } + await page.goto('/') + await page + .getByRole('link', { name: 'Server function loader', exact: true }) + .click() + await expect(page.getByTestId('execution-result')).toHaveText( + 'Read on the server', + ) + await page.reload() + await expect(page.getByTestId('execution-result')).toHaveText( + 'Read on the server', + ) +}) diff --git a/e2e/react-start/basic/tests/fixture-api.spec.ts b/e2e/react-start/basic/tests/fixture-api.spec.ts new file mode 100644 index 0000000000..6c9b26dc4c --- /dev/null +++ b/e2e/react-start/basic/tests/fixture-api.spec.ts @@ -0,0 +1,11 @@ +import { expect, test } from '@playwright/test' + +test('server API receives canned users without a fixture listener', async ({ + request, +}) => { + const response = await request.get('/api/users') + expect(response.ok()).toBe(true) + const users = await response.json() + expect(users).toHaveLength(10) + expect(users[0]).toMatchObject({ id: 1, name: 'Leanne Graham' }) +}) diff --git a/e2e/react-start/basic/tests/issue-6221-head.spec.ts b/e2e/react-start/basic/tests/issue-6221-head.spec.ts new file mode 100644 index 0000000000..96274ce0f9 --- /dev/null +++ b/e2e/react-start/basic/tests/issue-6221-head.spec.ts @@ -0,0 +1,41 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' +import { isPreview } from './utils/isPreview' +import { isSpaMode } from './utils/isSpaMode' + +// Ported to React from the regression app in +// https://github.com/TanStack/router/pull/6222 +test.skip( + isSpaMode || isPreview, + 'head() coverage for an ssr:false route requires the SSR test mode', +) + +test('browser back uses fresh loaderData for both the body and head (#6221)', async ({ + page, +}) => { + await page.goto('/') + await page.evaluate(() => localStorage.setItem('issue-6221-auth', 'good')) + + await page.goto('/issue-6221/article/1') + + await expect(page.getByTestId('issue-6221-article')).toHaveText( + 'Article content for 1', + ) + await expect(page).toHaveTitle('Article Title for 1') + + await page.evaluate(() => localStorage.removeItem('issue-6221-auth')) + await page.reload() + await expect(page.getByText('Article Not Accessible.')).toBeVisible() + await expect(page).toHaveTitle('title n/a') + + await page.evaluate(() => localStorage.setItem('issue-6221-auth', 'good')) + await page.getByTestId('issue-6221-dashboard-link').click() + await expect(page.getByTestId('issue-6221-dashboard')).toBeVisible() + await expect(page).toHaveTitle('Dashboard') + + await page.goBack() + await expect(page.getByTestId('issue-6221-article')).toHaveText( + 'Article content for 1', + ) + await expect(page).toHaveTitle('Article Title for 1') +}) diff --git a/e2e/react-start/basic/tests/redirect.spec.ts b/e2e/react-start/basic/tests/redirect.spec.ts index 34ba7b6ea9..010ecec155 100644 --- a/e2e/react-start/basic/tests/redirect.spec.ts +++ b/e2e/react-start/basic/tests/redirect.spec.ts @@ -1,20 +1,15 @@ import queryString from 'node:querystring' -import { expect, type Page } from '@playwright/test' +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' import combinateImport from 'combinate' -import { - getDummyServerPort, - getTestServerPort, - test, -} from '@tanstack/router-e2e-utils' -import { getE2EPortKey } from './utils/getE2EPortKey.ts' +import type { Page } from '@playwright/test' // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport -const e2ePortKey = getE2EPortKey() -const PORT = await getTestServerPort(e2ePortKey) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const EXTERNAL_HOST_PORT = await getDummyServerPort(e2ePortKey) +const EXTERNAL_ORIGIN = `http://127.0.0.1:${PORT}` const POSTS_URL = `http://localhost:${PORT}/posts` async function waitForRouterIdle(page: Page) { @@ -111,7 +106,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, + externalHost: `${EXTERNAL_ORIGIN}/`, }) if (scenario === 'navigate') { @@ -124,7 +119,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/external/via-${thrower}?${q}`) } - const url = `http://localhost:${EXTERNAL_HOST_PORT}/` + const url = `${EXTERNAL_ORIGIN}/` await page.waitForURL(url) expect(page.url()).toBe(url) @@ -147,7 +142,7 @@ test.describe('redirects', () => { }) => { let fullPageLoad = false const q = queryString.stringify({ - externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, + externalHost: `${EXTERNAL_ORIGIN}/`, reloadDocument, }) @@ -170,10 +165,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/${target}/serverFn/via-${thrower}?${q}`) } - const url = - target === 'internal' - ? POSTS_URL - : `http://localhost:${EXTERNAL_HOST_PORT}/` + const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` await page.waitForURL(url) @@ -202,7 +194,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, + externalHost: `${EXTERNAL_ORIGIN}/`, reloadDocument, }) @@ -219,10 +211,7 @@ test.describe('redirects', () => { await button.click() - const url = - target === 'internal' - ? POSTS_URL - : `http://localhost:${EXTERNAL_HOST_PORT}/` + const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` await page.waitForURL(url) expect(page.url()).toBe(url) if (target === 'internal') { diff --git a/e2e/react-start/basic/tests/setup/dev-server.setup.ts b/e2e/react-start/basic/tests/setup/dev-server.setup.ts new file mode 100644 index 0000000000..d16ff0bb54 --- /dev/null +++ b/e2e/react-start/basic/tests/setup/dev-server.setup.ts @@ -0,0 +1,19 @@ +import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' + +export default async function setup() { + const port = Number(process.env.E2E_APP_PORT ?? 0) + const baseURL = `http://localhost:${port}` + + await waitForServer(baseURL) + await preOptimizeDevServer({ + baseURL, + warmup: async (page) => { + await page.getByRole('heading').getByText('Welcome Home').waitFor() + await page.goto(`${baseURL}/specialChars/search?searchParam=warmup`) + await page.getByTestId('special-search-loaded-info').waitFor() + await page.goto(`${baseURL}/posts`) + await page.getByRole('link', { name: 'sunt aut facere repe' }).waitFor() + await page.waitForLoadState('networkidle') + }, + }) +} diff --git a/e2e/react-start/basic/tests/setup/global.setup.ts b/e2e/react-start/basic/tests/setup/global.setup.ts deleted file mode 100644 index cd38c35885..0000000000 --- a/e2e/react-start/basic/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import { getE2EPortKey } from '../utils/getE2EPortKey.ts' - -export default async function setup() { - await e2eStartDummyServer(getE2EPortKey()) -} diff --git a/e2e/react-start/basic/tests/setup/global.teardown.ts b/e2e/react-start/basic/tests/setup/global.teardown.ts deleted file mode 100644 index 36e5c92858..0000000000 --- a/e2e/react-start/basic/tests/setup/global.teardown.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import { getE2EPortKey } from '../utils/getE2EPortKey.ts' - -export default async function teardown() { - try { - await e2eStopDummyServer(getE2EPortKey()) - } catch {} -} diff --git a/e2e/react-start/basic/tests/setup/waitForDummyServer.ts b/e2e/react-start/basic/tests/setup/waitForDummyServer.ts deleted file mode 100644 index 88c18fd79e..0000000000 --- a/e2e/react-start/basic/tests/setup/waitForDummyServer.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { getDummyServerPort } from '@tanstack/router-e2e-utils' -import { getE2EPortKey } from '../utils/getE2EPortKey.ts' - -const timeoutMs = 10_000 -const retryIntervalMs = 100 - -export default async function waitForDummyServer() { - const port = await getDummyServerPort(getE2EPortKey()) - const deadline = Date.now() + timeoutMs - - while (Date.now() < deadline) { - try { - const response = await fetch(`http://localhost:${port}/`) - - if (response.ok) { - return - } - } catch {} - - await new Promise((resolve) => setTimeout(resolve, retryIntervalMs)) - } - - throw new Error(`Timed out waiting for dummy server on port ${port}`) -} diff --git a/e2e/react-start/basic/tests/spa-shell.spec.ts b/e2e/react-start/basic/tests/spa-shell.spec.ts new file mode 100644 index 0000000000..f42195e762 --- /dev/null +++ b/e2e/react-start/basic/tests/spa-shell.spec.ts @@ -0,0 +1,53 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' +import { isSpaMode } from './utils/isSpaMode' + +// The prod SPA run and the dev SPA runs (`E2E_DEV_SERVER`) all run this file. +// The dev runs run nothing else. +test.skip(!isSpaMode, 'only SPA mode answers documents with the shell') + +// Its loader and beforeLoad report where they ran. +const searchRoute = '/specialChars/search?searchParam=shell' + +test('a document request gets the shell, not the rendered route', async ({ + request, +}) => { + const response = await request.get(searchRoute) + + expect(response.status()).toBe(200) + const html = await response.text() + // The root route's document renders... + expect(html).toContain('This Route Does Not Exist') + // ...but not the matched route, nor its loader's output. + expect(html).not.toContain('special-search-loaded-info') + expect(html).not.toContain('Loaded on: server') +}) + +test('the route loads in the browser', async ({ page }) => { + await page.goto(searchRoute) + + await expect(page.getByTestId('special-search-loaded-info')).toHaveText( + 'Loaded on: client', + ) + await expect(page.getByTestId('special-search-before-load-info')).toHaveText( + 'Before load on: client', + ) + await expect(page.getByTestId('special-search-param')).toHaveText('shell') +}) + +test('client navigation works from the shell', async ({ page }) => { + await page.goto('/') + await expect(page.getByRole('heading')).toContainText('Welcome Home') + await expect(page.getByTestId('router-status')).toHaveText('idle') + + // A full page load would drop this. + await page.evaluate(() => { + ;(window as any).__spaShellPage = true + }) + await page.getByRole('link', { name: 'Posts' }).click() + await page.waitForURL('/posts') + await expect( + page.getByRole('link', { name: 'sunt aut facere repe' }), + ).toBeVisible() + expect(await page.evaluate(() => (window as any).__spaShellPage)).toBe(true) +}) diff --git a/e2e/react-start/basic/tests/utils/getE2EPortKey.ts b/e2e/react-start/basic/tests/utils/getE2EPortKey.ts deleted file mode 100644 index 48be6a9027..0000000000 --- a/e2e/react-start/basic/tests/utils/getE2EPortKey.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { getPackageName } from './getPackageName.ts' - -export function getE2EPortKey() { - return process.env.E2E_PORT_KEY ?? getPackageName() -} diff --git a/e2e/react-start/clerk-basic/package.json b/e2e/react-start/clerk-basic/package.json index 137a0e7fda..7838b4cee1 100644 --- a/e2e/react-start/clerk-basic/package.json +++ b/e2e/react-start/clerk-basic/package.json @@ -8,7 +8,7 @@ "dev:e2e": "vite dev", "build": "exit 0; vite build", "start": "node .output/server/index.mjs", - "test:e2e": "exit 0; rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "exit 0; playwright test --project=chromium" }, "dependencies": { "@clerk/tanstack-react-start": "^0.19.0", @@ -17,7 +17,7 @@ "@tanstack/react-start": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0" }, "devDependencies": { @@ -29,7 +29,8 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/e2e/react-start/clerk-basic/playwright.config.ts b/e2e/react-start/clerk-basic/playwright.config.ts index 18b8905468..82678ac00b 100644 --- a/e2e/react-start/clerk-basic/playwright.config.ts +++ b/e2e/react-start/clerk-basic/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-start/clerk-basic/src/routeTree.gen.ts b/e2e/react-start/clerk-basic/src/routeTree.gen.ts index 5b9f75e27a..d8111b637a 100644 --- a/e2e/react-start/clerk-basic/src/routeTree.gen.ts +++ b/e2e/react-start/clerk-basic/src/routeTree.gen.ts @@ -9,22 +9,22 @@ // 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 AuthedRouteImport } from './routes/_authed' import { Route as IndexRouteImport } from './routes/index' +import { Route as AuthedRouteImport } from './routes/_authed' import { Route as AuthedPostsRouteImport } from './routes/_authed/posts' import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' -import { Route as AuthedProfileSplatRouteImport } from './routes/_authed/profile.$' import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' +import { Route as AuthedProfileSplatRouteImport } from './routes/_authed/profile.$' -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', + getParentRoute: () => rootRouteImport, +} as any) const AuthedPostsRoute = AuthedPostsRouteImport.update({ id: '/posts', path: '/posts', @@ -35,16 +35,16 @@ const AuthedPostsIndexRoute = AuthedPostsIndexRouteImport.update({ path: '/', getParentRoute: () => AuthedPostsRoute, } as any) -const AuthedProfileSplatRoute = AuthedProfileSplatRouteImport.update({ - id: '/profile/$', - path: '/profile/$', - getParentRoute: () => AuthedRoute, -} as any) const AuthedPostsPostIdRoute = AuthedPostsPostIdRouteImport.update({ id: '/$postId', path: '/$postId', getParentRoute: () => AuthedPostsRoute, } as any) +const AuthedProfileSplatRoute = AuthedProfileSplatRouteImport.update({ + id: '/profile/$', + path: '/profile/$', + getParentRoute: () => AuthedRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -90,13 +90,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/_authed': { - id: '/_authed' - path: '' - fullPath: '/' - preLoaderRoute: typeof AuthedRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -104,6 +97,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/_authed': { + id: '/_authed' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthedRouteImport + parentRoute: typeof rootRouteImport + } '/_authed/posts': { id: '/_authed/posts' path: '/posts' @@ -118,13 +118,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthedPostsIndexRouteImport parentRoute: typeof AuthedPostsRoute } - '/_authed/profile/$': { - id: '/_authed/profile/$' - path: '/profile/$' - fullPath: '/profile/$' - preLoaderRoute: typeof AuthedProfileSplatRouteImport - parentRoute: typeof AuthedRoute - } '/_authed/posts/$postId': { id: '/_authed/posts/$postId' path: '/$postId' @@ -132,6 +125,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthedPostsPostIdRouteImport parentRoute: typeof AuthedPostsRoute } + '/_authed/profile/$': { + id: '/_authed/profile/$' + path: '/profile/$' + fullPath: '/profile/$' + preLoaderRoute: typeof AuthedProfileSplatRouteImport + parentRoute: typeof AuthedRoute + } } } diff --git a/e2e/react-start/clerk-basic/src/routes/_authed.tsx b/e2e/react-start/clerk-basic/src/routes/_authed.tsx index 226ae0829f..440d0e3f3c 100644 --- a/e2e/react-start/clerk-basic/src/routes/_authed.tsx +++ b/e2e/react-start/clerk-basic/src/routes/_authed.tsx @@ -8,7 +8,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error.message === 'Not authenticated') { + if (error instanceof Error && error.message === 'Not authenticated') { return (
diff --git a/e2e/react-start/csp/package.json b/e2e/react-start/csp/package.json index 22ffb81237..fd8987bcef 100644 --- a/e2e/react-start/csp/package.json +++ b/e2e/react-start/csp/package.json @@ -8,7 +8,7 @@ "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -22,8 +22,9 @@ "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "srvx": "^0.11.9", - "typescript": "^6.0.2", + "srvx": "^1.0.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/e2e/react-start/csp/playwright.config.ts b/e2e/react-start/csp/playwright.config.ts index 5f9de5709e..87b32e1f50 100644 --- a/e2e/react-start/csp/playwright.config.ts +++ b/e2e/react-start/csp/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-start/css-inline/package.json b/e2e/react-start/css-inline/package.json index 5e0b6d104d..6c5dd031c6 100644 --- a/e2e/react-start/css-inline/package.json +++ b/e2e/react-start/css-inline/package.json @@ -20,24 +20,65 @@ "express": "^5.2.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "srvx": "^0.11.9" + "srvx": "^1.0.0" }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.0.11", + "@rsbuild/core": "^2.3.1", "@rsbuild/plugin-react": "^2.0.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" }, "nx": { "targets": { "test:e2e": { - "parallelism": false + "parallelism": false, + "outputs": [ + "...", + "{projectRoot}/dist-vite-ssr", + "{projectRoot}/dist-vite-ssr-transform-assets", + "{projectRoot}/dist-vite-transform-assets-ssr", + "{projectRoot}/dist-rsbuild-ssr", + "{projectRoot}/dist-rsbuild-ssr-transform-assets", + "{projectRoot}/dist-rsbuild-transform-assets-ssr" + ] + }, + "build": { + "outputs": [ + "...", + "{projectRoot}/dist-vite-ssr", + "{projectRoot}/dist-rsbuild-ssr" + ] + }, + "test:e2e--vite-ssr": { + "outputs": [ + "...", + "{projectRoot}/dist-vite-ssr" + ] + }, + "test:e2e--vite-ssr--transform-assets": { + "outputs": [ + "...", + "{projectRoot}/dist-vite-ssr-transform-assets" + ] + }, + "test:e2e--rsbuild-ssr": { + "outputs": [ + "...", + "{projectRoot}/dist-rsbuild-ssr" + ] + }, + "test:e2e--rsbuild-ssr--transform-assets": { + "outputs": [ + "...", + "{projectRoot}/dist-rsbuild-ssr-transform-assets" + ] } }, "metadata": { diff --git a/e2e/react-start/css-inline/playwright.config.ts b/e2e/react-start/css-inline/playwright.config.ts index b5d78f3608..78e7b75252 100644 --- a/e2e/react-start/css-inline/playwright.config.ts +++ b/e2e/react-start/css-inline/playwright.config.ts @@ -1,7 +1,5 @@ -import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' const inlineCssTransformAssets = @@ -18,15 +16,8 @@ const transformAssetsSuffix = isInlineCssTransformAssets : '' const distDir = process.env.E2E_DIST_DIR ?? `dist-${toolchain}${transformAssetsSuffix}-ssr` -const e2ePortKey = - process.env.E2E_PORT_KEY ?? - `${packageJson.name}-${toolchain}${transformAssetsSuffix}` -if (process.env.TEST_WORKER_INDEX === undefined) { - fs.rmSync(`port-${e2ePortKey}.txt`, { force: true }) -} - -const PORT = await getTestServerPort(e2ePortKey) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -40,8 +31,8 @@ export default defineConfig({ webServer: { command: `pnpm build:${toolchain} && pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', env: { E2E_DIST_DIR: distDir, diff --git a/e2e/react-start/css-inline/rsbuild.config.ts b/e2e/react-start/css-inline/rsbuild.config.ts index 2fd1208250..8957fc9a06 100644 --- a/e2e/react-start/css-inline/rsbuild.config.ts +++ b/e2e/react-start/css-inline/rsbuild.config.ts @@ -8,7 +8,7 @@ const transformInlineCssAssets = export default defineConfig({ plugins: [ - pluginReact({ splitChunks: false }), + pluginReact(), tanstackStart({ server: { build: { diff --git a/e2e/react-start/css-inline/server.js b/e2e/react-start/css-inline/server.js index fcdec3b888..27b2357284 100644 --- a/e2e/react-start/css-inline/server.js +++ b/e2e/react-start/css-inline/server.js @@ -3,7 +3,7 @@ import path from 'node:path' import express from 'express' import { toNodeHandler } from 'srvx/node' -const port = process.env.PORT || 3000 +const port = Number(process.env.PORT ?? 3000) const distDir = process.env.E2E_DIST_DIR || 'dist-vite-ssr' const distClientDir = path.resolve(distDir, 'client') @@ -37,8 +37,10 @@ async function createStartServer() { } createStartServer().then((app) => { - app.listen(port, (error) => { - if (error) throw error - console.info(`Start Server: http://localhost:${port}`) + const httpServer = app.listen(port, (error) => { + if (error) { + throw error + } + console.info(`E2E app: http://localhost:${httpServer.address().port}`) }) }) diff --git a/e2e/react-start/css-inline/src/routeTree.gen.ts b/e2e/react-start/css-inline/src/routeTree.gen.ts index f663ab1b4e..1b5e5886b1 100644 --- a/e2e/react-start/css-inline/src/routeTree.gen.ts +++ b/e2e/react-start/css-inline/src/routeTree.gen.ts @@ -9,22 +9,22 @@ // 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 AppRouteRouteImport } from './routes/app/route' import { Route as IndexRouteImport } from './routes/index' +import { Route as AppRouteRouteImport } from './routes/app/route' import { Route as AppDashboardRouteRouteImport } from './routes/app/dashboard/route' import { Route as AppDashboardIndexRouteImport } from './routes/app/dashboard/index' import { Route as AppDashboardDetailsRouteImport } from './routes/app/dashboard/details' -const AppRouteRoute = AppRouteRouteImport.update({ - id: '/app', - path: '/app', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AppRouteRoute = AppRouteRouteImport.update({ + id: '/app', + path: '/app', + getParentRoute: () => rootRouteImport, +} as any) const AppDashboardRouteRoute = AppDashboardRouteRouteImport.update({ id: '/dashboard', path: '/dashboard', @@ -88,13 +88,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/app': { - id: '/app' - path: '/app' - fullPath: '/app' - preLoaderRoute: typeof AppRouteRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -102,6 +95,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/app': { + id: '/app' + path: '/app' + fullPath: '/app' + preLoaderRoute: typeof AppRouteRouteImport + parentRoute: typeof rootRouteImport + } '/app/dashboard': { id: '/app/dashboard' path: '/dashboard' diff --git a/e2e/react-start/css-inline/src/routes/app/dashboard/index.tsx b/e2e/react-start/css-inline/src/routes/app/dashboard/index.tsx index a796656b3d..35205cc9cf 100644 --- a/e2e/react-start/css-inline/src/routes/app/dashboard/index.tsx +++ b/e2e/react-start/css-inline/src/routes/app/dashboard/index.tsx @@ -3,6 +3,9 @@ import { NestedPanel } from '~/components/NestedPanel' import styles from '~/styles/dashboard-index.module.css' export const Route = createFileRoute('/app/dashboard/')({ + head: () => ({ + meta: [{ title: 'Inline CSS dashboard' }], + }), component: DashboardIndex, }) diff --git a/e2e/react-start/css-inline/tests/css-inline.spec.ts b/e2e/react-start/css-inline/tests/css-inline.spec.ts index 339fedd4ca..89d7d3992f 100644 --- a/e2e/react-start/css-inline/tests/css-inline.spec.ts +++ b/e2e/react-start/css-inline/tests/css-inline.spec.ts @@ -1,5 +1,5 @@ import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' +import { collectBrowserErrors, test } from '@tanstack/router-e2e-utils' const buildUrl = (baseURL: string, pathname: string) => baseURL.replace(/\/$/, '') + pathname @@ -151,6 +151,23 @@ test('client navigation preserves the SSR inline shell stylesheet', async ({ await page.goto(buildUrl(baseURL!, '/')) await waitForHydration(page) + const inlineStyle = page.locator('style[data-tsr-inline-css]') + await expect(inlineStyle).toHaveCount(1) + const original = await inlineStyle.evaluateHandle( + (style: HTMLStyleElement) => { + const mutations: Array = [] + const observer = new MutationObserver((records) => { + mutations.push(...records) + }) + observer.observe(style, { + childList: true, + characterData: true, + subtree: true, + }) + return { style, sheet: style.sheet, observer, mutations } + }, + ) + await expect.poll(() => getInlineCssTexts(page)).toHaveLength(1) await expect .poll(() => getInlineCssTexts(page)) @@ -161,6 +178,28 @@ test('client navigation preserves the SSR inline shell stylesheet', async ({ await page.getByTestId('nav-dashboard').click() await page.waitForURL('**/app/dashboard') + await expect(page).toHaveTitle('Inline CSS dashboard') + await expect(page.getByTestId('dashboard-card')).toBeVisible() + + await page.getByTestId('nav-home').click() + await expect(page).toHaveTitle('Inline CSS E2E') + await expect(page.getByTestId('home')).toBeVisible() + + // #8250: unchanged CSS text can hide a redundant innerHTML write that + // replaces the stylesheet or fails under Trusted Types. Observe native DOM + // mutations and CSSOM identity without patching the innerHTML setter. + expect( + await original.evaluate(({ style, sheet, observer, mutations }) => { + const mutationCount = mutations.length + observer.takeRecords().length + observer.disconnect() + return { + connected: style.isConnected, + sameSheet: style.sheet === sheet, + mutationCount, + } + }), + ).toEqual({ connected: true, sameSheet: true, mutationCount: 0 }) + await original.dispose() await expect.poll(() => getInlineCssTexts(page)).toHaveLength(1) await expect @@ -170,3 +209,45 @@ test('client navigation preserves the SSR inline shell stylesheet', async ({ .poll(() => getStyle(page, 'shell', 'background-color')) .toBe('rgb(240, 249, 255)') }) + +test('client navigation preserves inline CSS with Trusted Types enforced', async ({ + page, +}) => { + const browserErrors = collectBrowserErrors(page) + const csp = "require-trusted-types-for 'script'; trusted-types 'none'" + await page.route('/', async (route) => { + const response = await route.fetch() + await route.fulfill({ + response, + headers: { ...response.headers(), 'content-security-policy': csp }, + }) + }) + + const response = await page.goto('/') + expect(response?.headers()['content-security-policy']).toBe(csp) + expect(await page.evaluate(() => 'trustedTypes' in window)).toBe(true) + await waitForHydration(page) + + const violations = await page.evaluateHandle(() => { + const directives: Array = [] + document.addEventListener('securitypolicyviolation', (event) => { + directives.push(event.effectiveDirective) + }) + return directives + }) + + await page.getByTestId('nav-dashboard').click() + await expect(page).toHaveTitle('Inline CSS dashboard') + await expect(page.getByTestId('dashboard-card')).toBeVisible() + await expect + .poll(() => getStyle(page, 'shell', 'background-color')) + .toBe('rgb(240, 249, 255)') + + await page.getByTestId('nav-home').click() + await expect(page).toHaveTitle('Inline CSS E2E') + await expect(page.getByTestId('home')).toBeVisible() + + expect(await violations.jsonValue()).toEqual([]) + expect(browserErrors).toEqual([]) + await violations.dispose() +}) diff --git a/e2e/react-start/css-modules/.gitignore b/e2e/react-start/css-modules/.gitignore index 229709a89d..a1fbca128d 100644 --- a/e2e/react-start/css-modules/.gitignore +++ b/e2e/react-start/css-modules/.gitignore @@ -3,3 +3,4 @@ dist test-results playwright-report port*.txt +.cloudflare diff --git a/e2e/react-start/css-modules/cloudflare.config.ts b/e2e/react-start/css-modules/cloudflare.config.ts new file mode 100644 index 0000000000..e2bd5e13f1 --- /dev/null +++ b/e2e/react-start/css-modules/cloudflare.config.ts @@ -0,0 +1,11 @@ +import { defineConfig } from 'cf/config' + +// Used by rsbuild-plugin-cloudflare (E2E_RSBUILD_CLOUDFLARE=true). +// The Vite Cloudflare variant still reads wrangler.jsonc. +export default defineConfig({ + worker: { + name: 'tanstack-start-css-modules', + entrypoint: '@tanstack/react-start/server-entry', + compatibilityDate: '2026-11-01', + }, +}) diff --git a/e2e/react-start/css-modules/package.json b/e2e/react-start/css-modules/package.json index 381fa13b3a..25c11d7321 100644 --- a/e2e/react-start/css-modules/package.json +++ b/e2e/react-start/css-modules/package.json @@ -12,6 +12,8 @@ "dev:e2e:basepath": "VITE_BASE_PATH=/my-app vite dev --port $PORT", "dev:cloudflare": "echo 'Cloudflare dev mode has React duplication issues - use build+preview instead' && exit 1", "dev:e2e:cloudflare": "echo 'Cloudflare dev mode has React duplication issues - use build+preview instead' && exit 1", + "dev:e2e:rsbuild": "rsbuild dev --port $PORT", + "dev:e2e:rsbuild-cloudflare": "E2E_RSBUILD_CLOUDFLARE=true rsbuild dev --port $PORT", "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", @@ -19,13 +21,16 @@ "test:e2e:dev:nitro": "MODE=dev VITE_CONFIG=nitro playwright test --project=chromium", "test:e2e:dev:basepath": "MODE=dev VITE_CONFIG=basepath playwright test --project=chromium", "_test:e2e:dev:cloudflare": "MODE=dev VITE_CONFIG=cloudflare playwright test --project=chromium", + "test:e2e:dev:rsbuild": "MODE=dev VITE_CONFIG=rsbuild playwright test --project=chromium", + "test:e2e:dev:rsbuild-cloudflare": "MODE=dev VITE_CONFIG=rsbuild-cloudflare playwright test --project=chromium", "test:e2e:prod:default": "MODE=prod playwright test --project=chromium", "test:e2e:prod": "pnpm run test:e2e:prod:default && pnpm run test:e2e:prod:css-code-split-false", "test:e2e:prod:css-code-split-false": "MODE=prod VITE_CSS_CODE_SPLIT=false playwright test tests/css.prod.spec.ts --project=chromium", - "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:dev && pnpm run test:e2e:prod", - "test:e2e:nitro": "rm -rf port*.txt; pnpm run test:e2e:dev:nitro", - "test:e2e:basepath": "rm -rf port*.txt; pnpm run test:e2e:dev:basepath", - "_test:e2e:cloudflare": "echo 'Cloudflare dev mode disabled - React duplication issues' && exit 0" + "test:e2e": "pnpm run test:e2e:dev && pnpm run test:e2e:prod", + "test:e2e:nitro": "pnpm run test:e2e:dev:nitro", + "test:e2e:basepath": "pnpm run test:e2e:dev:basepath", + "_test:e2e:cloudflare": "echo 'Cloudflare dev mode disabled - React duplication issues' && exit 0", + "build:rsbuild": "rsbuild build && tsc --noEmit" }, "dependencies": { "@tanstack/react-router": "workspace:*", @@ -36,16 +41,36 @@ "devDependencies": { "@cloudflare/vite-plugin": "^1.29.0", "@playwright/test": "^1.61.0", + "@rsbuild/core": "^2.3.1", + "@rsbuild/plugin-react": "^2.0.0", + "@rsbuild/plugin-sass": "^2.0.1", "@tanstack/router-e2e-utils": "workspace:*", "@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", - "nitro": "^3.0.260311-beta", + "cf": "1.0.0-beta.28", + "nitro": "^3.0.260903-beta", + "rsbuild-plugin-cloudflare": "^0.0.4", "sass": "^1.97.2", - "srvx": "^0.11.9", - "typescript": "^6.0.2", + "srvx": "^1.0.0", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "wrangler": "^4.74.0" + }, + "nx": { + "metadata": { + "playwrightModes": [ + { + "toolchain": "vite", + "mode": "ssr" + }, + { + "toolchain": "rsbuild", + "mode": "ssr" + } + ] + } } } diff --git a/e2e/react-start/css-modules/playwright.config.ts b/e2e/react-start/css-modules/playwright.config.ts index 644798ca99..7e7ad3d9b3 100644 --- a/e2e/react-start/css-modules/playwright.config.ts +++ b/e2e/react-start/css-modules/playwright.config.ts @@ -1,37 +1,41 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' const mode = process.env.MODE ?? 'prod' const isDev = mode === 'dev' +const distDir = process.env.E2E_DIST_DIR const viteConfig = process.env.VITE_CONFIG // 'nitro' | 'basepath' | 'cloudflare' | undefined -const PORT = await getTestServerPort( - viteConfig ? `${packageJson.name}-${viteConfig}` : packageJson.name, -) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) // When using basepath config, the app is served at /my-app const basePath = viteConfig === 'basepath' ? '/my-app' : '' const baseURL = `http://localhost:${PORT}${basePath}` // Select the appropriate dev command based on VITE_CONFIG -const devCommand = viteConfig ? `pnpm dev:e2e:${viteConfig}` : 'pnpm dev:e2e' +const devCommand = viteConfig + ? `pnpm dev:e2e:${viteConfig}` + : 'pnpm dev:e2e --port 0' export default defineConfig({ testDir: './tests', + testMatch: isDev ? '**/*.dev.spec.ts' : '**/*.prod.spec.ts', workers: 1, reporter: [['line']], globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', use: { baseURL, }, webServer: { - command: isDev ? devCommand : `pnpm build && PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: isDev + ? devCommand + : distDir + ? `pnpm exec srvx --prod --dir=. -s ${distDir}/client --entry ${distDir}/server/server.js` + : `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', env: { VITE_NODE_ENV: 'test', diff --git a/e2e/react-start/css-modules/rsbuild.config.ts b/e2e/react-start/css-modules/rsbuild.config.ts new file mode 100644 index 0000000000..499ed67ebc --- /dev/null +++ b/e2e/react-start/css-modules/rsbuild.config.ts @@ -0,0 +1,63 @@ +import { defineConfig } from '@rsbuild/core' +import { pluginReact } from '@rsbuild/plugin-react' +import { pluginSass } from '@rsbuild/plugin-sass' +import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' +import { cloudflare } from 'rsbuild-plugin-cloudflare' + +// E2E_RSBUILD_CLOUDFLARE: Set to 'true' to run the SSR environment in workerd +const useCloudflare = process.env.E2E_RSBUILD_CLOUDFLARE === 'true' + +export default defineConfig({ + plugins: [ + pluginReact(), + pluginSass(), + ...(useCloudflare + ? [ + cloudflare({ + rsbuildEnvironment: { name: 'ssr' }, + inspectorPort: false, + }), + ] + : []), + tanstackStart(), + ], + output: { + distPath: { + root: process.env.E2E_DIST_DIR ?? 'dist-rsbuild-ssr', + }, + }, + tools: { + rspack(config, { environment }) { + if (environment.name === 'ssr') { + config.output ??= {} + config.output.filename = 'server.js' + } + if (environment.name !== 'client') { + return + } + config.optimization ??= {} + // Extract the shared component and its helper into their own chunks so + // a route depends on a shared chunk that depends on another shared chunk. + config.optimization.splitChunks = { + cacheGroups: { + sharedHeader: { + test: /[\\/]src[\\/]components[\\/]/, + chunks: 'async', + minChunks: 2, + minSize: 0, + enforce: true, + name: 'shared-header', + }, + sharedFormat: { + test: /[\\/]src[\\/]utils[\\/]/, + chunks: 'async', + minChunks: 2, + minSize: 0, + enforce: true, + name: 'shared-format', + }, + }, + } + }, + }, +}) diff --git a/e2e/react-start/css-modules/src/components/Header.module.css b/e2e/react-start/css-modules/src/components/Header.module.css new file mode 100644 index 0000000000..e6878a5410 --- /dev/null +++ b/e2e/react-start/css-modules/src/components/Header.module.css @@ -0,0 +1,14 @@ +.header { + --repro-shared-header: 1; + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: center; + height: 64px; + padding-inline: 16px; + background: #e4f2e9; +} + +.header h1 { + margin: 0; + font-size: 24px; +} diff --git a/e2e/react-start/css-modules/src/components/Header.tsx b/e2e/react-start/css-modules/src/components/Header.tsx new file mode 100644 index 0000000000..f16b12e8ff --- /dev/null +++ b/e2e/react-start/css-modules/src/components/Header.tsx @@ -0,0 +1,11 @@ +import { formatTitle } from '../utils/formatTitle' +import styles from './Header.module.css' + +export function Header({ title }: { title: string }) { + return ( +
+

{formatTitle(title)}

+ +
+ ) +} diff --git a/e2e/react-start/css-modules/src/routeTree.gen.ts b/e2e/react-start/css-modules/src/routeTree.gen.ts index d19ae80e5a..2789a3490a 100644 --- a/e2e/react-start/css-modules/src/routeTree.gen.ts +++ b/e2e/react-start/css-modules/src/routeTree.gen.ts @@ -9,19 +9,32 @@ // 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 SassMixinRouteImport } from './routes/sass-mixin' -import { Route as QuotesRouteImport } from './routes/quotes' -import { Route as ModulesRouteImport } from './routes/modules' import { Route as IndexRouteImport } from './routes/index' +import { Route as AlphaRouteImport } from './routes/alpha' +import { Route as BetaRouteImport } from './routes/beta' +import { Route as GammaRouteImport } from './routes/gamma' +import { Route as ModulesRouteImport } from './routes/modules' +import { Route as QuotesRouteImport } from './routes/quotes' +import { Route as SassMixinRouteImport } from './routes/sass-mixin' -const SassMixinRoute = SassMixinRouteImport.update({ - id: '/sass-mixin', - path: '/sass-mixin', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const QuotesRoute = QuotesRouteImport.update({ - id: '/quotes', - path: '/quotes', +const AlphaRoute = AlphaRouteImport.update({ + id: '/alpha', + path: '/alpha', + getParentRoute: () => rootRouteImport, +} as any) +const BetaRoute = BetaRouteImport.update({ + id: '/beta', + path: '/beta', + getParentRoute: () => rootRouteImport, +} as any) +const GammaRoute = GammaRouteImport.update({ + id: '/gamma', + path: '/gamma', getParentRoute: () => rootRouteImport, } as any) const ModulesRoute = ModulesRouteImport.update({ @@ -29,20 +42,31 @@ const ModulesRoute = ModulesRouteImport.update({ path: '/modules', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const QuotesRoute = QuotesRouteImport.update({ + id: '/quotes', + path: '/quotes', + getParentRoute: () => rootRouteImport, +} as any) +const SassMixinRoute = SassMixinRouteImport.update({ + id: '/sass-mixin', + path: '/sass-mixin', getParentRoute: () => rootRouteImport, } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute + '/alpha': typeof AlphaRoute + '/beta': typeof BetaRoute + '/gamma': typeof GammaRoute '/modules': typeof ModulesRoute '/quotes': typeof QuotesRoute '/sass-mixin': typeof SassMixinRoute } export interface FileRoutesByTo { '/': typeof IndexRoute + '/alpha': typeof AlphaRoute + '/beta': typeof BetaRoute + '/gamma': typeof GammaRoute '/modules': typeof ModulesRoute '/quotes': typeof QuotesRoute '/sass-mixin': typeof SassMixinRoute @@ -50,20 +74,36 @@ export interface FileRoutesByTo { export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute + '/alpha': typeof AlphaRoute + '/beta': typeof BetaRoute + '/gamma': typeof GammaRoute '/modules': typeof ModulesRoute '/quotes': typeof QuotesRoute '/sass-mixin': typeof SassMixinRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/modules' | '/quotes' | '/sass-mixin' + fullPaths: + '/' | '/alpha' | '/beta' | '/gamma' | '/modules' | '/quotes' | '/sass-mixin' fileRoutesByTo: FileRoutesByTo - to: '/' | '/modules' | '/quotes' | '/sass-mixin' - id: '__root__' | '/' | '/modules' | '/quotes' | '/sass-mixin' + to: + '/' | '/alpha' | '/beta' | '/gamma' | '/modules' | '/quotes' | '/sass-mixin' + id: + | '__root__' + | '/' + | '/alpha' + | '/beta' + | '/gamma' + | '/modules' + | '/quotes' + | '/sass-mixin' fileRoutesById: FileRoutesById } export interface RootRouteChildren { IndexRoute: typeof IndexRoute + AlphaRoute: typeof AlphaRoute + BetaRoute: typeof BetaRoute + GammaRoute: typeof GammaRoute ModulesRoute: typeof ModulesRoute QuotesRoute: typeof QuotesRoute SassMixinRoute: typeof SassMixinRoute @@ -71,18 +111,32 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/sass-mixin': { - id: '/sass-mixin' - path: '/sass-mixin' - fullPath: '/sass-mixin' - preLoaderRoute: typeof SassMixinRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/quotes': { - id: '/quotes' - path: '/quotes' - fullPath: '/quotes' - preLoaderRoute: typeof QuotesRouteImport + '/alpha': { + id: '/alpha' + path: '/alpha' + fullPath: '/alpha' + preLoaderRoute: typeof AlphaRouteImport + parentRoute: typeof rootRouteImport + } + '/beta': { + id: '/beta' + path: '/beta' + fullPath: '/beta' + preLoaderRoute: typeof BetaRouteImport + parentRoute: typeof rootRouteImport + } + '/gamma': { + id: '/gamma' + path: '/gamma' + fullPath: '/gamma' + preLoaderRoute: typeof GammaRouteImport parentRoute: typeof rootRouteImport } '/modules': { @@ -92,11 +146,18 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ModulesRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/quotes': { + id: '/quotes' + path: '/quotes' + fullPath: '/quotes' + preLoaderRoute: typeof QuotesRouteImport + parentRoute: typeof rootRouteImport + } + '/sass-mixin': { + id: '/sass-mixin' + path: '/sass-mixin' + fullPath: '/sass-mixin' + preLoaderRoute: typeof SassMixinRouteImport parentRoute: typeof rootRouteImport } } @@ -104,6 +165,9 @@ declare module '@tanstack/react-router' { const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, + AlphaRoute: AlphaRoute, + BetaRoute: BetaRoute, + GammaRoute: GammaRoute, ModulesRoute: ModulesRoute, QuotesRoute: QuotesRoute, SassMixinRoute: SassMixinRoute, diff --git a/e2e/react-start/css-modules/src/routes/alpha.tsx b/e2e/react-start/css-modules/src/routes/alpha.tsx new file mode 100644 index 0000000000..e894cd758f --- /dev/null +++ b/e2e/react-start/css-modules/src/routes/alpha.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/react-router' +import { Header } from '../components/Header' +import styles from '../styles/alpha.module.css' + +export const Route = createFileRoute('/alpha')({ component: Alpha }) + +function Alpha() { + return ( +
+
+
+ ) +} diff --git a/e2e/react-start/css-modules/src/routes/beta.tsx b/e2e/react-start/css-modules/src/routes/beta.tsx new file mode 100644 index 0000000000..4f139ac41a --- /dev/null +++ b/e2e/react-start/css-modules/src/routes/beta.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/react-router' +import { Header } from '../components/Header' +import styles from '../styles/beta.module.css' + +export const Route = createFileRoute('/beta')({ component: Beta }) + +function Beta() { + return ( +
+
+
+ ) +} diff --git a/e2e/react-start/css-modules/src/routes/gamma.tsx b/e2e/react-start/css-modules/src/routes/gamma.tsx new file mode 100644 index 0000000000..a8e036b85f --- /dev/null +++ b/e2e/react-start/css-modules/src/routes/gamma.tsx @@ -0,0 +1,8 @@ +import { createFileRoute } from '@tanstack/react-router' +import { formatTitle } from '../utils/formatTitle' + +export const Route = createFileRoute('/gamma')({ component: Gamma }) + +function Gamma() { + return
{formatTitle('Gamma')}
+} diff --git a/e2e/react-start/css-modules/src/styles/alpha.module.css b/e2e/react-start/css-modules/src/styles/alpha.module.css new file mode 100644 index 0000000000..12a606a8d3 --- /dev/null +++ b/e2e/react-start/css-modules/src/styles/alpha.module.css @@ -0,0 +1,4 @@ +.page { + --repro-alpha: 1; + border: 4px solid #226844; +} diff --git a/e2e/react-start/css-modules/src/styles/beta.module.css b/e2e/react-start/css-modules/src/styles/beta.module.css new file mode 100644 index 0000000000..719686a76b --- /dev/null +++ b/e2e/react-start/css-modules/src/styles/beta.module.css @@ -0,0 +1,4 @@ +.page { + --repro-beta: 1; + border: 4px solid #ac344c; +} diff --git a/e2e/react-start/css-modules/src/utils/formatTitle.ts b/e2e/react-start/css-modules/src/utils/formatTitle.ts new file mode 100644 index 0000000000..d0325ac63e --- /dev/null +++ b/e2e/react-start/css-modules/src/utils/formatTitle.ts @@ -0,0 +1,3 @@ +export function formatTitle(title: string) { + return `${title} (repro-format-title)` +} diff --git a/e2e/react-start/css-modules/tests/setup/global.setup.ts b/e2e/react-start/css-modules/tests/setup/global.setup.ts index e8879c0165..7c0fce762a 100644 --- a/e2e/react-start/css-modules/tests/setup/global.setup.ts +++ b/e2e/react-start/css-modules/tests/setup/global.setup.ts @@ -1,20 +1,10 @@ -import { - e2eStartDummyServer, - getTestServerPort, - preOptimizeDevServer, - waitForServer, -} from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } +import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' export default async function setup() { - await e2eStartDummyServer(packageJson.name) - if (process.env.MODE !== 'dev') return const viteConfig = process.env.VITE_CONFIG // 'nitro' | 'basepath' | 'cloudflare' | undefined - const port = await getTestServerPort( - viteConfig ? `${packageJson.name}-${viteConfig}` : packageJson.name, - ) + const port = Number(process.env.E2E_APP_PORT ?? 0) const basePath = viteConfig === 'basepath' ? '/my-app' : '' const baseURL = `http://localhost:${port}${basePath}` diff --git a/e2e/react-start/css-modules/tests/setup/global.teardown.ts b/e2e/react-start/css-modules/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-start/css-modules/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-start/css-modules/tests/shared-css.prod.spec.ts b/e2e/react-start/css-modules/tests/shared-css.prod.spec.ts new file mode 100644 index 0000000000..9a9595f819 --- /dev/null +++ b/e2e/react-start/css-modules/tests/shared-css.prod.spec.ts @@ -0,0 +1,94 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' +import type { Page } from '@playwright/test' + +test.skip( + process.env.VITE_CSS_CODE_SPLIT === 'false', + 'Route stylesheet isolation requires CSS code splitting', +) +test.use({ javaScriptEnabled: false }) + +async function getStylesheetContent(page: Page) { + const hrefs = await page + .locator('link[rel="stylesheet"]') + .evaluateAll((links: Array) => + links.map((link) => link.href), + ) + expect(hrefs.length).toBeGreaterThan(0) + const stylesheets = await Promise.all( + hrefs.map(async (href) => { + const response = await page.request.get(href) + expect(response.ok()).toBe(true) + return response.text() + }), + ) + return stylesheets.join('\n') +} + +for (const route of ['alpha', 'beta']) { + test(`${route} has complete and isolated CSS without JavaScript`, async ({ + page, + }) => { + await page.goto(`/${route}`) + + const header = page.getByTestId('shared-header') + await expect(header).toHaveCSS('display', 'grid') + await expect(header).toHaveCSS('height', '64px') + await expect(page.getByTestId('route-page')).toHaveCSS( + `--repro-${route}`, + '1', + ) + + const css = await getStylesheetContent(page) + expect(css).toContain('--repro-shared-header') + expect(css).toContain(`--repro-${route}`) + expect(css).not.toContain(`--repro-${route === 'alpha' ? 'beta' : 'alpha'}`) + }) +} + +function getScriptPreloadHrefs(html: string) { + return Array.from(html.matchAll(/]*>/g), (match) => match[0]) + .filter( + (tag) => + /\brel="modulepreload"/.test(tag) || + (/\brel="preload"/.test(tag) && /\bas="script"/.test(tag)), + ) + .map((tag) => tag.match(/\bhref="([^"]+)"/)?.[1]) + .filter((href): href is string => !!href) +} + +test('alpha preloads the shared header chunk and the chunk it depends on', async ({ + page, +}) => { + const response = await page.request.get('/alpha') + expect(response.ok()).toBe(true) + + const hrefs = getScriptPreloadHrefs(await response.text()) + expect(hrefs.length).toBeGreaterThan(0) + + const scripts = await Promise.all( + hrefs.map(async (href) => { + const script = await page.request.get(href) + expect(script.ok()).toBe(true) + return script.text() + }), + ) + + expect(scripts.some((code) => code.includes('shared-header'))).toBe(true) + expect(scripts.some((code) => code.includes('repro-format-title'))).toBe(true) +}) + +test('home does not load the shared header or route styles', async ({ + page, +}) => { + await page.goto('/') + await expect(page.getByTestId('global-styled')).toHaveCSS( + 'background-color', + 'rgb(59, 130, 246)', + ) + + const css = await getStylesheetContent(page) + expect(css).not.toContain('--repro-shared-header') + expect(css).not.toContain('--repro-alpha') + expect(css).not.toContain('--repro-beta') +}) diff --git a/e2e/react-start/css-modules/vite.config.ts b/e2e/react-start/css-modules/vite.config.ts index 9923ab3384..c9c27f7f9a 100644 --- a/e2e/react-start/css-modules/vite.config.ts +++ b/e2e/react-start/css-modules/vite.config.ts @@ -21,6 +21,7 @@ export default defineConfig(async () => { port: 3000, }, build: { + outDir: process.env.E2E_DIST_DIR ?? 'dist', cssCodeSplit, }, plugins: [ diff --git a/e2e/react-start/custom-basepath/express-server.ts b/e2e/react-start/custom-basepath/express-server.ts index 1884c5eb5a..b9bf393466 100644 --- a/e2e/react-start/custom-basepath/express-server.ts +++ b/e2e/react-start/custom-basepath/express-server.ts @@ -1,5 +1,6 @@ import express from 'express' import { toNodeHandler } from 'srvx/node' +import type { AddressInfo } from 'node:net' import type { NodeHttp1Handler } from 'srvx' const DEVELOPMENT = process.env.NODE_ENV === 'development' @@ -40,7 +41,11 @@ if (DEVELOPMENT) { }) } -app.listen(PORT, (error) => { - if (error) throw error - console.log(`Server is running on http://localhost:${PORT}`) +const httpServer = app.listen(PORT, (error) => { + if (error) { + throw error + } + console.log( + `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, + ) }) diff --git a/e2e/react-start/custom-basepath/package.json b/e2e/react-start/custom-basepath/package.json index 4bf492acca..e93949eea2 100644 --- a/e2e/react-start/custom-basepath/package.json +++ b/e2e/react-start/custom-basepath/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "tsx express-server.ts", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -17,7 +17,7 @@ "express": "^5.2.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1" + "redaxios": "catalog:" }, "devDependencies": { "@playwright/test": "^1.61.0", @@ -29,10 +29,11 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "cross-env": "^10.0.0", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "tailwindcss": "^4.2.2", "tsx": "^4.20.3", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/e2e/react-start/custom-basepath/playwright.config.ts b/e2e/react-start/custom-basepath/playwright.config.ts index 5095425f47..e113ce64ad 100644 --- a/e2e/react-start/custom-basepath/playwright.config.ts +++ b/e2e/react-start/custom-basepath/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}/custom/basepath` /** @@ -18,19 +13,19 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', + env: { + NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, + }, }, projects: [ diff --git a/e2e/react-start/custom-basepath/src/routeTree.gen.ts b/e2e/react-start/custom-basepath/src/routeTree.gen.ts index 9aacbfbdf0..18cc9b5163 100644 --- a/e2e/react-start/custom-basepath/src/routeTree.gen.ts +++ b/e2e/react-start/custom-basepath/src/routeTree.gen.ts @@ -9,40 +9,25 @@ // 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 UsersRouteImport } from './routes/users' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as NavigateTestRouteImport } from './routes/navigate-test' -import { Route as LogoutRouteImport } from './routes/logout' -import { Route as DeferredRouteImport } from './routes/deferred' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as RedirectIndexRouteImport } from './routes/redirect/index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as RedirectThrowItRouteImport } from './routes/redirect/throw-it' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as LogoutRouteImport } from './routes/logout' +import { Route as NavigateTestRouteImport } from './routes/navigate-test' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as UsersRouteImport } from './routes/users' import { Route as ApiUsersRouteImport } from './routes/api.users' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as RedirectIndexRouteImport } from './routes/redirect/index' +import { Route as RedirectThrowItRouteImport } from './routes/redirect/throw-it' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const NavigateTestRoute = NavigateTestRouteImport.update({ - id: '/navigate-test', - path: '/navigate-test', - getParentRoute: () => rootRouteImport, -} as any) -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const DeferredRoute = DeferredRouteImport.update({ @@ -50,19 +35,29 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LogoutRoute = LogoutRouteImport.update({ + id: '/logout', + path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, +const NavigateTestRoute = NavigateTestRouteImport.update({ + id: '/navigate-test', + path: '/navigate-test', + getParentRoute: () => rootRouteImport, } as any) -const RedirectIndexRoute = RedirectIndexRouteImport.update({ - id: '/redirect/', - path: '/redirect/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', + getParentRoute: () => rootRouteImport, +} as any) +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ @@ -70,36 +65,41 @@ const PostsIndexRoute = PostsIndexRouteImport.update({ path: '/', getParentRoute: () => PostsRoute, } as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const RedirectIndexRoute = RedirectIndexRouteImport.update({ + id: '/redirect/', + path: '/redirect/', + getParentRoute: () => rootRouteImport, } as any) const RedirectThrowItRoute = RedirectThrowItRouteImport.update({ id: '/redirect/throw-it', path: '/redirect/throw-it', getParentRoute: () => rootRouteImport, } as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', - getParentRoute: () => rootRouteImport, -} as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRoute, } as any) const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ id: '/$id', path: '/$id', getParentRoute: () => ApiUsersRoute, } as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -218,32 +218,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/navigate-test': { - id: '/navigate-test' - path: '/navigate-test' - fullPath: '/navigate-test' - preLoaderRoute: typeof NavigateTestRouteImport - parentRoute: typeof rootRouteImport - } - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/deferred': { @@ -253,25 +232,39 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/logout': { + id: '/logout' + path: '/logout' + fullPath: '/logout' + preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute + '/navigate-test': { + id: '/navigate-test' + path: '/navigate-test' + fullPath: '/navigate-test' + preLoaderRoute: typeof NavigateTestRouteImport + parentRoute: typeof rootRouteImport } - '/redirect/': { - id: '/redirect/' - path: '/redirect' - fullPath: '/redirect/' - preLoaderRoute: typeof RedirectIndexRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport + parentRoute: typeof rootRouteImport + } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } '/posts/': { @@ -281,12 +274,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsIndexRouteImport parentRoute: typeof PostsRoute } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/redirect/': { + id: '/redirect/' + path: '/redirect' + fullPath: '/redirect/' + preLoaderRoute: typeof RedirectIndexRouteImport + parentRoute: typeof rootRouteImport } '/redirect/throw-it': { id: '/redirect/throw-it' @@ -295,26 +295,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof RedirectThrowItRouteImport parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport - parentRoute: typeof rootRouteImport - } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute } '/api/users/$id': { id: '/api/users/$id' @@ -323,6 +316,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiUsersIdRouteImport parentRoute: typeof ApiUsersRoute } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/e2e/react-start/custom-basepath/src/routes/api.users.ts b/e2e/react-start/custom-basepath/src/routes/api.users.ts index 9e055549ef..6fc8cde830 100644 --- a/e2e/react-start/custom-basepath/src/routes/api.users.ts +++ b/e2e/react-start/custom-basepath/src/routes/api.users.ts @@ -3,11 +3,7 @@ import axios from 'redaxios' import type { User } from '~/utils/users' -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const Route = createFileRoute('/api/users')({ server: { diff --git a/e2e/react-start/custom-basepath/src/routes/api/users.$id.ts b/e2e/react-start/custom-basepath/src/routes/api/users.$id.ts index 57682660fd..81c071afb5 100644 --- a/e2e/react-start/custom-basepath/src/routes/api/users.$id.ts +++ b/e2e/react-start/custom-basepath/src/routes/api/users.$id.ts @@ -2,11 +2,7 @@ import axios from 'redaxios' import type { User } from '~/utils/users' import { createFileRoute } from '@tanstack/react-router' -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const Route = createFileRoute('/api/users/$id')({ server: { diff --git a/e2e/react-start/custom-basepath/src/utils/posts.tsx b/e2e/react-start/custom-basepath/src/utils/posts.tsx index 4cc5dcc4c6..d9b98a8c9c 100644 --- a/e2e/react-start/custom-basepath/src/utils/posts.tsx +++ b/e2e/react-start/custom-basepath/src/utils/posts.tsx @@ -8,11 +8,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = createServerFn({ method: 'GET' }) .validator((postId: string) => postId) diff --git a/e2e/react-start/custom-basepath/src/utils/users.tsx b/e2e/react-start/custom-basepath/src/utils/users.tsx index 46be4b1580..7ba645b383 100644 --- a/e2e/react-start/custom-basepath/src/utils/users.tsx +++ b/e2e/react-start/custom-basepath/src/utils/users.tsx @@ -3,7 +3,3 @@ export type User = { name: string email: string } - -const PORT = process.env.VITE_SERVER_PORT || 3000 - -export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/react-start/custom-basepath/tests/setup/global.setup.ts b/e2e/react-start/custom-basepath/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/react-start/custom-basepath/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/react-start/custom-basepath/tests/setup/global.teardown.ts b/e2e/react-start/custom-basepath/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/react-start/custom-basepath/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/react-start/custom-server-rsbuild/express-server.ts b/e2e/react-start/custom-server-rsbuild/express-server.ts index 23784f2efc..68537956b4 100644 --- a/e2e/react-start/custom-server-rsbuild/express-server.ts +++ b/e2e/react-start/custom-server-rsbuild/express-server.ts @@ -1,5 +1,6 @@ import express from 'express' import { toNodeHandler } from 'srvx/node' +import type { AddressInfo } from 'node:net' import type { NodeHttp1Handler } from 'srvx' const DEVELOPMENT = process.env.NODE_ENV === 'development' @@ -58,9 +59,13 @@ if (DEVELOPMENT) { }) const httpServer = app.listen(PORT, async (error) => { - if (error) throw error + if (error) { + throw error + } await devServer.afterListen() - console.log(`Server is running on http://localhost:${PORT}`) + console.log( + `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, + ) }) devServer.connectWebSocket({ server: httpServer }) } else { @@ -75,8 +80,12 @@ if (DEVELOPMENT) { next(error) } }) - app.listen(PORT, (error) => { - if (error) throw error - console.log(`Server is running on http://localhost:${PORT}`) + const httpServer = app.listen(PORT, (error) => { + if (error) { + throw error + } + console.log( + `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, + ) }) } diff --git a/e2e/react-start/custom-server-rsbuild/package.json b/e2e/react-start/custom-server-rsbuild/package.json index 87acfacd05..1c5b3af393 100644 --- a/e2e/react-start/custom-server-rsbuild/package.json +++ b/e2e/react-start/custom-server-rsbuild/package.json @@ -10,7 +10,7 @@ "start": "tsx express-server.ts", "test:e2e:dev": "cross-env MODE=dev playwright test --project=chromium", "test:e2e:prod": "cross-env MODE=prod playwright test --project=chromium", - "test:e2e": "rm -rf port*.txt && pnpm run test:e2e:dev && pnpm run test:e2e:prod" + "test:e2e": "pnpm run test:e2e:dev && pnpm run test:e2e:prod" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -21,7 +21,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.0.11", + "@rsbuild/core": "^2.3.1", "@rsbuild/plugin-react": "^2.0.0", "@tailwindcss/postcss": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", @@ -30,9 +30,10 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "cross-env": "^10.0.0", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "tailwindcss": "^4.2.2", "tsx": "^4.20.3", - "typescript": "^6.0.2" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2" } } diff --git a/e2e/react-start/custom-server-rsbuild/playwright.config.ts b/e2e/react-start/custom-server-rsbuild/playwright.config.ts index eb8b43f648..f0542500fd 100644 --- a/e2e/react-start/custom-server-rsbuild/playwright.config.ts +++ b/e2e/react-start/custom-server-rsbuild/playwright.config.ts @@ -1,11 +1,9 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } const mode = process.env.MODE ?? 'prod' const isDev = mode === 'dev' -const PORT = await getTestServerPort(`${packageJson.name}-${mode}`) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -15,8 +13,8 @@ export default defineConfig({ use: { baseURL }, webServer: { command: isDev ? 'pnpm dev:e2e' : 'pnpm build && pnpm start', - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: { stdout: /E2E app: http:\/\/localhost:(?\d+)/ }, + reuseExistingServer: false, stdout: 'pipe', env: { PORT: String(PORT), diff --git a/e2e/react-start/custom-server-rsbuild/rsbuild.config.ts b/e2e/react-start/custom-server-rsbuild/rsbuild.config.ts index dec3a6d0fc..5f9aa96e16 100644 --- a/e2e/react-start/custom-server-rsbuild/rsbuild.config.ts +++ b/e2e/react-start/custom-server-rsbuild/rsbuild.config.ts @@ -28,7 +28,7 @@ import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' // explicit prefix. export default defineConfig({ plugins: [ - pluginReact({ splitChunks: false }), + pluginReact(), tanstackStart({ rsbuild: { installDevServerMiddleware: false, diff --git a/e2e/react-start/deferred-hydration/package.json b/e2e/react-start/deferred-hydration/package.json index b225528b49..5a33407435 100644 --- a/e2e/react-start/deferred-hydration/package.json +++ b/e2e/react-start/deferred-hydration/package.json @@ -26,21 +26,28 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@rsbuild/core": "^2.0.11", + "@rsbuild/core": "^2.3.1", "@rsbuild/plugin-react": "^2.0.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^0.11.9", - "typescript": "^6.0.2", + "srvx": "^1.0.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" }, "nx": { "targets": { "test:e2e": { "parallelism": false + }, + "build": { + "outputs": [ + "...", + "{projectRoot}/dist-vite-ssr" + ] } }, "metadata": { diff --git a/e2e/react-start/deferred-hydration/playwright.config.ts b/e2e/react-start/deferred-hydration/playwright.config.ts index 0125792d4b..d88c59fc9d 100644 --- a/e2e/react-start/deferred-hydration/playwright.config.ts +++ b/e2e/react-start/deferred-hydration/playwright.config.ts @@ -1,12 +1,9 @@ -import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' const distDir = process.env.E2E_DIST_DIR ?? `dist-${toolchain}-ssr` -const e2ePortKey = - process.env.E2E_PORT_KEY ?? `${packageJson.name}-${toolchain}` + const mode = process.env.MODE ?? 'prod' const isDev = mode === 'dev' const serverEntryFile = toolchain === 'rsbuild' ? 'index.js' : 'server.js' @@ -14,11 +11,7 @@ const startCommand = `pnpm exec srvx --prod --dir=. -s ${distDir}/client --entry const devCommand = toolchain === 'rsbuild' ? 'pnpm dev:rsbuild' : 'pnpm dev:vite' -if (process.env.TEST_WORKER_INDEX === undefined) { - fs.rmSync(`port-${e2ePortKey}.txt`, { force: true }) -} - -const PORT = await getTestServerPort(e2ePortKey) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -26,12 +19,11 @@ export default defineConfig({ workers: 1, reporter: [['line']], globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', use: { baseURL }, webServer: { command: isDev ? `${devCommand} --port ${PORT}` : startCommand, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', env: { E2E_DIST_DIR: distDir, @@ -40,7 +32,6 @@ export default defineConfig({ PORT: String(PORT), VITE_SERVER_PORT: String(PORT), E2E_TOOLCHAIN: toolchain, - E2E_PORT_KEY: e2ePortKey, }, }, projects: [ diff --git a/e2e/react-start/deferred-hydration/rsbuild.config.ts b/e2e/react-start/deferred-hydration/rsbuild.config.ts index 6279705adb..a9d1942a6f 100644 --- a/e2e/react-start/deferred-hydration/rsbuild.config.ts +++ b/e2e/react-start/deferred-hydration/rsbuild.config.ts @@ -5,7 +5,7 @@ import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' const outDir = process.env.E2E_DIST_DIR ?? 'dist-rsbuild-ssr' export default defineConfig({ - plugins: [pluginReact({ splitChunks: false }), tanstackStart()], + plugins: [pluginReact(), tanstackStart()], output: { distPath: { root: outDir, diff --git a/e2e/react-start/deferred-hydration/src/routeTree.gen.ts b/e2e/react-start/deferred-hydration/src/routeTree.gen.ts index a5b35a698f..451af49ddf 100644 --- a/e2e/react-start/deferred-hydration/src/routeTree.gen.ts +++ b/e2e/react-start/deferred-hydration/src/routeTree.gen.ts @@ -9,31 +9,16 @@ // 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 ScrollRestorationRouteImport } from './routes/scroll-restoration' -import { Route as ImportedRouteImport } from './routes/imported' -import { Route as EnhancedRouteImport } from './routes/enhanced' -import { Route as CssRouteImport } from './routes/css' -import { Route as ComponentsRouteImport } from './routes/components' import { Route as IndexRouteImport } from './routes/index' +import { Route as ComponentsRouteImport } from './routes/components' +import { Route as CssRouteImport } from './routes/css' +import { Route as EnhancedRouteImport } from './routes/enhanced' +import { Route as ImportedRouteImport } from './routes/imported' +import { Route as ScrollRestorationRouteImport } from './routes/scroll-restoration' -const ScrollRestorationRoute = ScrollRestorationRouteImport.update({ - id: '/scroll-restoration', - path: '/scroll-restoration', - getParentRoute: () => rootRouteImport, -} as any) -const ImportedRoute = ImportedRouteImport.update({ - id: '/imported', - path: '/imported', - getParentRoute: () => rootRouteImport, -} as any) -const EnhancedRoute = EnhancedRouteImport.update({ - id: '/enhanced', - path: '/enhanced', - getParentRoute: () => rootRouteImport, -} as any) -const CssRoute = CssRouteImport.update({ - id: '/css', - path: '/css', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const ComponentsRoute = ComponentsRouteImport.update({ @@ -41,9 +26,24 @@ const ComponentsRoute = ComponentsRouteImport.update({ path: '/components', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const CssRoute = CssRouteImport.update({ + id: '/css', + path: '/css', + getParentRoute: () => rootRouteImport, +} as any) +const EnhancedRoute = EnhancedRouteImport.update({ + id: '/enhanced', + path: '/enhanced', + getParentRoute: () => rootRouteImport, +} as any) +const ImportedRoute = ImportedRouteImport.update({ + id: '/imported', + path: '/imported', + getParentRoute: () => rootRouteImport, +} as any) +const ScrollRestorationRoute = ScrollRestorationRouteImport.update({ + id: '/scroll-restoration', + path: '/scroll-restoration', getParentRoute: () => rootRouteImport, } as any) @@ -110,32 +110,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/scroll-restoration': { - id: '/scroll-restoration' - path: '/scroll-restoration' - fullPath: '/scroll-restoration' - preLoaderRoute: typeof ScrollRestorationRouteImport - parentRoute: typeof rootRouteImport - } - '/imported': { - id: '/imported' - path: '/imported' - fullPath: '/imported' - preLoaderRoute: typeof ImportedRouteImport - parentRoute: typeof rootRouteImport - } - '/enhanced': { - id: '/enhanced' - path: '/enhanced' - fullPath: '/enhanced' - preLoaderRoute: typeof EnhancedRouteImport - parentRoute: typeof rootRouteImport - } - '/css': { - id: '/css' - path: '/css' - fullPath: '/css' - preLoaderRoute: typeof CssRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/components': { @@ -145,11 +124,32 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ComponentsRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/css': { + id: '/css' + path: '/css' + fullPath: '/css' + preLoaderRoute: typeof CssRouteImport + parentRoute: typeof rootRouteImport + } + '/enhanced': { + id: '/enhanced' + path: '/enhanced' + fullPath: '/enhanced' + preLoaderRoute: typeof EnhancedRouteImport + parentRoute: typeof rootRouteImport + } + '/imported': { + id: '/imported' + path: '/imported' + fullPath: '/imported' + preLoaderRoute: typeof ImportedRouteImport + parentRoute: typeof rootRouteImport + } + '/scroll-restoration': { + id: '/scroll-restoration' + path: '/scroll-restoration' + fullPath: '/scroll-restoration' + preLoaderRoute: typeof ScrollRestorationRouteImport parentRoute: typeof rootRouteImport } } diff --git a/e2e/react-start/deferred-hydration/tests/setup/global.setup.ts b/e2e/react-start/deferred-hydration/tests/setup/global.setup.ts index 1117664a14..704bbef3e2 100644 --- a/e2e/react-start/deferred-hydration/tests/setup/global.setup.ts +++ b/e2e/react-start/deferred-hydration/tests/setup/global.setup.ts @@ -1,24 +1,11 @@ -import { - e2eStartDummyServer, - getTestServerPort, - preOptimizeDevServer, - waitForServer, -} from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -function getE2EPortKey() { - const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' - return process.env.E2E_PORT_KEY ?? `${packageJson.name}-${toolchain}` -} +import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' export default async function setup() { - if (process.env.MODE !== 'dev') return + if (process.env.MODE !== 'dev') { + return + } - const e2ePortKey = getE2EPortKey() - - await e2eStartDummyServer(e2ePortKey) - - const port = await getTestServerPort(e2ePortKey) + const port = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${port}` await waitForServer(baseURL) diff --git a/e2e/react-start/deferred-hydration/tests/setup/global.teardown.ts b/e2e/react-start/deferred-hydration/tests/setup/global.teardown.ts deleted file mode 100644 index df79f50e82..0000000000 --- a/e2e/react-start/deferred-hydration/tests/setup/global.teardown.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -function getE2EPortKey() { - const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' - return process.env.E2E_PORT_KEY ?? `${packageJson.name}-${toolchain}` -} - -export default async function teardown() { - if (process.env.MODE !== 'dev') return - - await e2eStopDummyServer(getE2EPortKey()) -} diff --git a/e2e/react-start/dev-ssr-styles/package.json b/e2e/react-start/dev-ssr-styles/package.json index 829eddedd3..a5300e836e 100644 --- a/e2e/react-start/dev-ssr-styles/package.json +++ b/e2e/react-start/dev-ssr-styles/package.json @@ -22,13 +22,9 @@ "test:e2e:dev:nitro": "MODE=dev VITE_USE_NITRO=true playwright test --project=chromium", "test:e2e:dev:disabled:nitro": "MODE=dev SSR_STYLES=disabled VITE_USE_NITRO=true playwright test --project=chromium", "test:e2e:dev:custom-basepath:nitro": "MODE=dev SSR_STYLES=custom-basepath VITE_USE_NITRO=true playwright test --project=chromium", - "test:e2e:dev:bundled-dev:nitro": "MODE=dev VITE_USE_NITRO=true E2E_VITE_BUNDLED_DEV=true playwright test --project=chromium", - "test:e2e:dev:disabled:bundled-dev:nitro": "MODE=dev SSR_STYLES=disabled VITE_USE_NITRO=true E2E_VITE_BUNDLED_DEV=true playwright test --project=chromium", - "test:e2e:dev:custom-basepath:bundled-dev:nitro": "MODE=dev SSR_STYLES=custom-basepath VITE_USE_NITRO=true E2E_VITE_BUNDLED_DEV=true playwright test --project=chromium", "test:e2e:bundled-dev": "pnpm run test:e2e:dev:bundled-dev && pnpm run test:e2e:dev:disabled:bundled-dev && pnpm run test:e2e:dev:custom-basepath:bundled-dev", - "test:e2e:nitro:bundled-dev": "pnpm run test:e2e:dev:bundled-dev:nitro && pnpm run test:e2e:dev:disabled:bundled-dev:nitro && pnpm run test:e2e:dev:custom-basepath:bundled-dev:nitro", - "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:dev && pnpm run test:e2e:dev:disabled && pnpm run test:e2e:dev:custom-basepath && pnpm run test:e2e:bundled-dev", - "test:e2e:nitro": "rm -rf port*.txt; pnpm run test:e2e:dev:nitro && pnpm run test:e2e:dev:disabled:nitro && pnpm run test:e2e:dev:custom-basepath:nitro && pnpm run test:e2e:nitro:bundled-dev" + "test:e2e": "pnpm run test:e2e:dev && pnpm run test:e2e:dev:disabled && pnpm run test:e2e:dev:custom-basepath && pnpm run test:e2e:bundled-dev", + "test:e2e:nitro": "pnpm run test:e2e:dev:nitro && pnpm run test:e2e:dev:disabled:nitro && pnpm run test:e2e:dev:custom-basepath:nitro" }, "dependencies": { "@tanstack/react-router": "workspace:*", @@ -44,9 +40,10 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "nitro": "^3.0.260311-beta", - "srvx": "^0.11.9", - "typescript": "^6.0.2", + "nitro": "^3.0.260903-beta", + "srvx": "^1.0.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "zod": "^4.4.3" } diff --git a/e2e/react-start/dev-ssr-styles/playwright.config.ts b/e2e/react-start/dev-ssr-styles/playwright.config.ts index a1fdd7c3ef..71cc8ed2da 100644 --- a/e2e/react-start/dev-ssr-styles/playwright.config.ts +++ b/e2e/react-start/dev-ssr-styles/playwright.config.ts @@ -1,6 +1,5 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' import { ssrStylesMode, useNitro, viteBundledDev } from './env' const mode = process.env.MODE ?? 'prod' @@ -9,24 +8,13 @@ const isDev = mode === 'dev' // Build a unique port key per dimension combination (ssrStyles mode + nitro) // e.g. "...dev-ssr-styles", "...dev-ssr-styles-disabled", "...dev-ssr-styles-nitro", // "...dev-ssr-styles-disabled-nitro" -function getPortKey() { - let key = packageJson.name - if (ssrStylesMode !== 'default') { - key += `-${ssrStylesMode}` - } - if (useNitro) { - key += '-nitro' - } - if (viteBundledDev) { - key += '-bundled-dev' - } - return key -} -const PORT = await getTestServerPort(getPortKey()) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` // Select the appropriate dev command based on SSR_STYLES + VITE_USE_NITRO +// package.json omits bundled Nitro runs because its asset plugin produces +// invalid Vite client code. Re-enable those tests once the upstream fix lands. function getDevCommand() { const scriptParts = ['dev:e2e'] if (ssrStylesMode !== 'default') { @@ -44,7 +32,6 @@ export default defineConfig({ reporter: [['line']], globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', use: { baseURL, @@ -52,8 +39,8 @@ export default defineConfig({ webServer: { command: isDev ? getDevCommand() : `pnpm build && PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', env: { VITE_NODE_ENV: 'test', diff --git a/e2e/react-start/dev-ssr-styles/src/components/CodeSplitStyledBox.tsx b/e2e/react-start/dev-ssr-styles/src/components/CodeSplitStyledBox.tsx new file mode 100644 index 0000000000..49d2f96c39 --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/components/CodeSplitStyledBox.tsx @@ -0,0 +1,9 @@ +import styles from '../styles/code-split-route.module.css' + +export function CodeSplitStyledBox() { + return ( +
+ This box should have a blue background when dev styles are enabled. +
+ ) +} diff --git a/e2e/react-start/dev-ssr-styles/src/routeTree.gen.ts b/e2e/react-start/dev-ssr-styles/src/routeTree.gen.ts index dceedffdc1..96c0a37142 100644 --- a/e2e/react-start/dev-ssr-styles/src/routeTree.gen.ts +++ b/e2e/react-start/dev-ssr-styles/src/routeTree.gen.ts @@ -10,33 +10,63 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' +import { Route as CssImportOrderRouteImport } from './routes/css-import-order' +import { Route as InlineCssRouteImport } from './routes/inline-css' +import { Route as ModuleStateRouteImport } from './routes/module-state' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const CssImportOrderRoute = CssImportOrderRouteImport.update({ + id: '/css-import-order', + path: '/css-import-order', + getParentRoute: () => rootRouteImport, +} as any) +const InlineCssRoute = InlineCssRouteImport.update({ + id: '/inline-css', + path: '/inline-css', + getParentRoute: () => rootRouteImport, +} as any) +const ModuleStateRoute = ModuleStateRouteImport.update({ + id: '/module-state', + path: '/module-state', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute + '/css-import-order': typeof CssImportOrderRoute + '/inline-css': typeof InlineCssRoute + '/module-state': typeof ModuleStateRoute } export interface FileRoutesByTo { '/': typeof IndexRoute + '/css-import-order': typeof CssImportOrderRoute + '/inline-css': typeof InlineCssRoute + '/module-state': typeof ModuleStateRoute } export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute + '/css-import-order': typeof CssImportOrderRoute + '/inline-css': typeof InlineCssRoute + '/module-state': typeof ModuleStateRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' + fullPaths: '/' | '/css-import-order' | '/inline-css' | '/module-state' fileRoutesByTo: FileRoutesByTo - to: '/' - id: '__root__' | '/' + to: '/' | '/css-import-order' | '/inline-css' | '/module-state' + id: '__root__' | '/' | '/css-import-order' | '/inline-css' | '/module-state' fileRoutesById: FileRoutesById } export interface RootRouteChildren { IndexRoute: typeof IndexRoute + CssImportOrderRoute: typeof CssImportOrderRoute + InlineCssRoute: typeof InlineCssRoute + ModuleStateRoute: typeof ModuleStateRoute } declare module '@tanstack/react-router' { @@ -48,11 +78,35 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/css-import-order': { + id: '/css-import-order' + path: '/css-import-order' + fullPath: '/css-import-order' + preLoaderRoute: typeof CssImportOrderRouteImport + parentRoute: typeof rootRouteImport + } + '/inline-css': { + id: '/inline-css' + path: '/inline-css' + fullPath: '/inline-css' + preLoaderRoute: typeof InlineCssRouteImport + parentRoute: typeof rootRouteImport + } + '/module-state': { + id: '/module-state' + path: '/module-state' + fullPath: '/module-state' + preLoaderRoute: typeof ModuleStateRouteImport + parentRoute: typeof rootRouteImport + } } } const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, + CssImportOrderRoute: CssImportOrderRoute, + InlineCssRoute: InlineCssRoute, + ModuleStateRoute: ModuleStateRoute, } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) diff --git a/e2e/react-start/dev-ssr-styles/src/routes/css-import-order.tsx b/e2e/react-start/dev-ssr-styles/src/routes/css-import-order.tsx new file mode 100644 index 0000000000..345254bb8c --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/routes/css-import-order.tsx @@ -0,0 +1,17 @@ +import { createFileRoute } from '@tanstack/react-router' +import '../styles/css-import-order.css' + +export const Route = createFileRoute('/css-import-order')({ + component: CssImportOrder, +}) + +function CssImportOrder() { + return ( +
+

CSS import order

+
+ The route stylesheet should override its imported base stylesheet. +
+
+ ) +} diff --git a/e2e/react-start/dev-ssr-styles/src/routes/index.tsx b/e2e/react-start/dev-ssr-styles/src/routes/index.tsx index f5fadf464d..62fb237750 100644 --- a/e2e/react-start/dev-ssr-styles/src/routes/index.tsx +++ b/e2e/react-start/dev-ssr-styles/src/routes/index.tsx @@ -1,4 +1,5 @@ import { createFileRoute } from '@tanstack/react-router' +import { CodeSplitStyledBox } from '../components/CodeSplitStyledBox' export const Route = createFileRoute('/')({ component: Home, @@ -8,9 +9,7 @@ function Home() { return (

Dev SSR Styles Test

-
- This box should have a blue background when dev styles are enabled. -
+
) } diff --git a/e2e/react-start/dev-ssr-styles/src/routes/inline-css.tsx b/e2e/react-start/dev-ssr-styles/src/routes/inline-css.tsx new file mode 100644 index 0000000000..ffc59128e0 --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/routes/inline-css.tsx @@ -0,0 +1,19 @@ +import { createFileRoute } from '@tanstack/react-router' +import embeddedCss from '../styles/embedded.css?inline' + +export const Route = createFileRoute('/inline-css')({ + loader: () => embeddedCss, + component: InlineCss, +}) + +function InlineCss() { + const css = Route.useLoaderData() + return ( +
+
+ Inline styles must not change the page layout. +
+
{css}
+
+ ) +} diff --git a/e2e/react-start/dev-ssr-styles/src/routes/module-state.ts b/e2e/react-start/dev-ssr-styles/src/routes/module-state.ts new file mode 100644 index 0000000000..546217efc3 --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/routes/module-state.ts @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +const instanceId = crypto.randomUUID() + +export const Route = createFileRoute('/module-state')({ + server: { + handlers: { + GET: () => new Response(instanceId), + }, + }, +}) diff --git a/e2e/react-start/dev-ssr-styles/src/styles/app.css b/e2e/react-start/dev-ssr-styles/src/styles/app.css index 06b48f8a7c..4285da0c86 100644 --- a/e2e/react-start/dev-ssr-styles/src/styles/app.css +++ b/e2e/react-start/dev-ssr-styles/src/styles/app.css @@ -5,9 +5,10 @@ body { background-color: #f0f4f8; } -.styled-box { - background-color: #3b82f6; - color: white; - padding: 24px; - border-radius: 12px; +@layer utilities { + .inline-css-layout { + margin: 12px; + padding: 24px; + border: 3px solid black; + } } diff --git a/e2e/react-start/dev-ssr-styles/src/styles/code-split-route.module.css b/e2e/react-start/dev-ssr-styles/src/styles/code-split-route.module.css new file mode 100644 index 0000000000..d6a50211ee --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/styles/code-split-route.module.css @@ -0,0 +1,7 @@ +.styledBox { + background-color: #3b82f6; + background-image: url('./ssr-background.svg?no-inline'); + color: white; + padding: 24px; + border-radius: 12px; +} diff --git a/e2e/react-start/dev-ssr-styles/src/styles/css-import-base.css b/e2e/react-start/dev-ssr-styles/src/styles/css-import-base.css new file mode 100644 index 0000000000..4f73ddab9c --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/styles/css-import-base.css @@ -0,0 +1,5 @@ +.css-import-order { + --css-import-base-marker: issue-7794; + background-color: #ffffff; + color: #000000; +} diff --git a/e2e/react-start/dev-ssr-styles/src/styles/css-import-order.css b/e2e/react-start/dev-ssr-styles/src/styles/css-import-order.css new file mode 100644 index 0000000000..afcb4797d9 --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/styles/css-import-order.css @@ -0,0 +1,7 @@ +@import './css-import-base.css'; + +.css-import-order { + background-color: #111827; + color: #ffffff; + padding: 24px; +} diff --git a/e2e/react-start/dev-ssr-styles/src/styles/embedded-preflight.css b/e2e/react-start/dev-ssr-styles/src/styles/embedded-preflight.css new file mode 100644 index 0000000000..13810d6c98 --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/styles/embedded-preflight.css @@ -0,0 +1,6 @@ +* { + --embedded-preflight-marker: 1; + margin: 0; + padding: 0; + border: 0 solid; +} diff --git a/e2e/react-start/dev-ssr-styles/src/styles/embedded-theme.css b/e2e/react-start/dev-ssr-styles/src/styles/embedded-theme.css new file mode 100644 index 0000000000..171ed5e174 --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/styles/embedded-theme.css @@ -0,0 +1,3 @@ +:root { + --embedded-theme-marker: 1; +} diff --git a/e2e/react-start/dev-ssr-styles/src/styles/embedded-utilities.css b/e2e/react-start/dev-ssr-styles/src/styles/embedded-utilities.css new file mode 100644 index 0000000000..01f81c3b86 --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/styles/embedded-utilities.css @@ -0,0 +1,3 @@ +.embedded-utility { + --embedded-utilities-marker: 1; +} diff --git a/e2e/react-start/dev-ssr-styles/src/styles/embedded.css b/e2e/react-start/dev-ssr-styles/src/styles/embedded.css new file mode 100644 index 0000000000..7b6b68c48d --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/styles/embedded.css @@ -0,0 +1,3 @@ +@import './embedded-theme.css' layer(theme); +@import './embedded-preflight.css' layer(base); +@import './embedded-utilities.css' layer(utilities); diff --git a/e2e/react-start/dev-ssr-styles/src/styles/ssr-background.svg b/e2e/react-start/dev-ssr-styles/src/styles/ssr-background.svg new file mode 100644 index 0000000000..7916b3ef16 --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/src/styles/ssr-background.svg @@ -0,0 +1 @@ + diff --git a/e2e/react-start/dev-ssr-styles/tests/app.spec.ts b/e2e/react-start/dev-ssr-styles/tests/app.spec.ts index cb1ba0b29b..f5b72a1bca 100644 --- a/e2e/react-start/dev-ssr-styles/tests/app.spec.ts +++ b/e2e/react-start/dev-ssr-styles/tests/app.spec.ts @@ -1,6 +1,6 @@ import { expect } from '@playwright/test' import { DEV_STYLES_ATTR } from '@tanstack/router-core' -import { test } from '@tanstack/router-e2e-utils' +import { createHmrFileEditor, test } from '@tanstack/router-e2e-utils' import { ssrStylesMode } from '../env' // Whitelist errors that can occur in CI: @@ -14,14 +14,60 @@ const whitelistErrors = [ test.describe(`dev.ssrStyles (mode=${ssrStylesMode})`, () => { test.use({ whitelistErrors }) + test('unchanged SSR requests reuse evaluated modules', async ({ + request, + }) => { + const first = await request.get('/module-state') + const second = await request.get('/module-state') + expect(first.ok()).toBeTruthy() + expect(second.ok()).toBeTruthy() + expect(await second.text()).toBe(await first.text()) + }) + test('page renders correctly', async ({ page }) => { + const runtimeErrors: Array = [] + page.on('pageerror', (error) => { + runtimeErrors.push(error.message) + }) await page.goto('/') await expect(page.getByTestId('home-heading')).toHaveText( 'Dev SSR Styles Test', ) + expect(runtimeErrors).toEqual([]) }) if (ssrStylesMode === 'default') { + test('dev CSS order is stable after client modules load', async ({ + page, + }) => { + const cssBodies: Array> = [] + page.on('response', (response) => { + if ( + new URL(response.url()).pathname.endsWith( + '/@tanstack-start/styles.css', + ) + ) { + cssBodies.push(response.text()) + } + }) + + await page.goto('/css-import-order') + await expect(page.getByTestId('css-import-order')).toBeVisible() + await expect.poll(() => cssBodies.length).toBeGreaterThanOrEqual(1) + + await page.reload() + await expect(page.getByTestId('css-import-order')).toBeVisible() + await expect.poll(() => cssBodies.length).toBeGreaterThanOrEqual(2) + + const [initialCss, reloadedCss] = await Promise.all(cssBodies.slice(0, 2)) + expect(reloadedCss).toBe(initialCss) + expect(initialCss).toContain('/* /src/styles/app.css */') + expect(initialCss).toContain('/* /src/styles/css-import-order.css */') + expect(initialCss.indexOf('/* /src/styles/app.css */')).toBeLessThan( + initialCss.indexOf('/* /src/styles/css-import-order.css */'), + ) + }) + test.describe('default (enabled, basepath = vite base)', () => { test.use({ javaScriptEnabled: false, whitelistErrors }) @@ -52,7 +98,9 @@ test.describe(`dev.ssrStyles (mode=${ssrStylesMode})`, () => { expect(href).toMatch(/^\/@tanstack-start\/styles\.css/) }) - test('CSS is applied on initial page load (SSR)', async ({ page }) => { + test('CSS from a code-split route component is applied during SSR', async ({ + page, + }) => { await page.goto('/') const element = page.getByTestId('styled-box') @@ -64,6 +112,81 @@ test.describe(`dev.ssrStyles (mode=${ssrStylesMode})`, () => { ) expect(backgroundColor).toBe('rgb(59, 130, 246)') }) + + test('SSR CSS updates after a stylesheet edit', async ({ page }) => { + const editor = createHmrFileEditor({ + rootDir: import.meta.dirname, + files: { css: '../src/styles/code-split-route.module.css' }, + }) + await editor.capturePromise + const expectSsrColor = async (color: string) => { + await expect(async () => { + await page.reload() + await expect(page.getByTestId('styled-box')).toHaveCSS( + 'background-color', + color, + ) + }).toPass({ timeout: 20_000 }) + } + try { + await page.goto('/') + await expect(page.getByTestId('styled-box')).toHaveCSS( + 'background-color', + 'rgb(59, 130, 246)', + ) + await editor.replaceText('css', '#3b82f6', '#ef4444') + await expectSsrColor('rgb(239, 68, 68)') + } finally { + await editor.restoreFiles() + // Finish the restore before another test reads the SSR stylesheet. + await expectSsrColor('rgb(59, 130, 246)') + } + }) + + test('assets referenced by SSR CSS are available before hydration', async ({ + page, + }) => { + await page.goto('/') + const backgroundImage = await page + .getByTestId('styled-box') + .evaluate((element) => getComputedStyle(element).backgroundImage) + const assetUrl = backgroundImage.match(/^url\("(.+)"\)$/)?.[1] + expect(assetUrl).toBeDefined() + const response = await page.request.get(assetUrl!) + expect(response.ok()).toBeTruthy() + expect(response.headers()['content-type']).toContain('image/svg+xml') + expect(await response.text()).toContain(' { + await page.goto('/css-import-order') + + const element = page.getByTestId('css-import-order') + await expect(element).toBeVisible() + + // css-import-order.css imports a white base rule, then overrides it + // with this dark background. Collecting the imported file separately + // appends the white rule and reverses the intended cascade. + const backgroundColor = await element.evaluate( + (el) => getComputedStyle(el).backgroundColor, + ) + expect(backgroundColor).toBe('rgb(17, 24, 39)') + + const devStylesHref = await page + .locator(`link[${DEV_STYLES_ATTR}]`) + .getAttribute('href') + expect(devStylesHref).toBeTruthy() + + const cssResponse = await page.request.get( + new URL(devStylesHref!, page.url()).href, + ) + expect(cssResponse.ok()).toBeTruthy() + + const css = await cssResponse.text() + expect(css.match(/--css-import-base-marker/g)).toHaveLength(1) + }) }) } diff --git a/e2e/react-start/dev-ssr-styles/tests/inline-css.spec.ts b/e2e/react-start/dev-ssr-styles/tests/inline-css.spec.ts new file mode 100644 index 0000000000..c564a9977a --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/tests/inline-css.spec.ts @@ -0,0 +1,35 @@ +import { expect } from '@playwright/test' +import { DEV_STYLES_ATTR } from '@tanstack/router-core' +import { test } from '@tanstack/router-e2e-utils' +import { ssrStylesMode } from '../env' + +test.describe('server inline CSS with layered imports', () => { + test.skip(ssrStylesMode !== 'default', 'Requires the default dev stylesheet') + test.use({ javaScriptEnabled: false }) + + test('keeps layered inline imports out of the global dev stylesheet', async ({ + page, + }) => { + await page.goto('/inline-css') + const embeddedCss = await page.getByTestId('embedded-css').textContent() + for (const layer of ['theme', 'base', 'utilities']) { + expect(embeddedCss).toContain(`@layer ${layer}`) + } + for (const marker of ['theme', 'preflight', 'utilities']) { + expect(embeddedCss).toContain(`--embedded-${marker}-marker`) + } + + const href = await page + .locator(`link[${DEV_STYLES_ATTR}]`) + .getAttribute('href') + expect(href).toBeTruthy() + const response = await page.request.get(new URL(href!, page.url()).href) + expect(response.ok()).toBeTruthy() + expect(await response.text()).not.toContain('--embedded-') + + const layout = page.getByTestId('inline-css-layout') + await expect(layout).toHaveCSS('padding-top', '24px') + await expect(layout).toHaveCSS('margin-top', '12px') + await expect(layout).toHaveCSS('border-top-width', '3px') + }) +}) diff --git a/e2e/react-start/dev-ssr-styles/tests/setup/global.setup.ts b/e2e/react-start/dev-ssr-styles/tests/setup/global.setup.ts index 2bfd33163d..43fad46254 100644 --- a/e2e/react-start/dev-ssr-styles/tests/setup/global.setup.ts +++ b/e2e/react-start/dev-ssr-styles/tests/setup/global.setup.ts @@ -1,39 +1,45 @@ -import { - e2eStartDummyServer, - getTestServerPort, - preOptimizeDevServer, - waitForServer, -} from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } -import { ssrStylesMode, useNitro, viteBundledDev } from '../../env' - -function getPortKey() { - let key = packageJson.name - if (ssrStylesMode !== 'default') { - key += `-${ssrStylesMode}` - } - if (useNitro) { - key += '-nitro' - } - if (viteBundledDev) { - key += '-bundled-dev' - } - return key -} +import { chromium, expect } from '@playwright/test' +import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' +import { ssrStylesMode } from '../../env' export default async function setup() { - const portKey = getPortKey() + if (process.env.MODE !== 'dev') { + return + } - await e2eStartDummyServer(portKey) - - if (process.env.MODE !== 'dev') return - - const port = await getTestServerPort(portKey) + const port = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${port}` await waitForServer(baseURL) - await preOptimizeDevServer({ - baseURL, - readyTestId: 'home-heading', - }) + + // Check cold SSR before the browser warmup can populate the client graph. + const browser = await chromium.launch() + try { + const page = await browser.newPage({ javaScriptEnabled: false }) + const backgroundAsset = + ssrStylesMode !== 'disabled' + ? page.waitForResponse( + (response) => + new URL(response.url()).pathname.includes('ssr-background'), + { timeout: 60_000 }, + ) + : undefined + await page.goto(baseURL, { timeout: 60_000 }) + await expect(page.getByTestId('home-heading')).toHaveText( + 'Dev SSR Styles Test', + { timeout: 30_000 }, + ) + if (ssrStylesMode !== 'disabled') { + expect((await backgroundAsset!).ok()).toBeTruthy() + await expect(page.getByTestId('styled-box')).toHaveCSS( + 'background-color', + 'rgb(59, 130, 246)', + { timeout: 30_000 }, + ) + } + } finally { + await browser.close() + } + + await preOptimizeDevServer({ baseURL, readyTestId: 'home-heading' }) } diff --git a/e2e/react-start/dev-ssr-styles/tests/setup/global.teardown.ts b/e2e/react-start/dev-ssr-styles/tests/setup/global.teardown.ts deleted file mode 100644 index 0e44fca325..0000000000 --- a/e2e/react-start/dev-ssr-styles/tests/setup/global.teardown.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } -import { ssrStylesMode, useNitro, viteBundledDev } from '../../env' - -function getPortKey() { - let key = packageJson.name - if (ssrStylesMode !== 'default') { - key += `-${ssrStylesMode}` - } - if (useNitro) { - key += '-nitro' - } - if (viteBundledDev) { - key += '-bundled-dev' - } - return key -} - -export default async function teardown() { - await e2eStopDummyServer(getPortKey()) -} diff --git a/e2e/react-start/dev-ssr-styles/vite.config.ts b/e2e/react-start/dev-ssr-styles/vite.config.ts index 555137b543..df5ea34504 100644 --- a/e2e/react-start/dev-ssr-styles/vite.config.ts +++ b/e2e/react-start/dev-ssr-styles/vite.config.ts @@ -20,7 +20,7 @@ export default defineConfig(async () => { return { resolve: { tsconfigPaths: true }, - experimental: viteBundledDev ? { bundledDev: true } : undefined, + experimental: { bundledDev: viteBundledDev }, server: { port: 3000, }, diff --git a/e2e/react-start/early-hints/package.json b/e2e/react-start/early-hints/package.json index a1a0efbd37..1615b99430 100644 --- a/e2e/react-start/early-hints/package.json +++ b/e2e/react-start/early-hints/package.json @@ -10,7 +10,7 @@ "preview": "vite preview", "gen-certs": "node --import tsx tests/gen-certs.ts", "start": "pnpm gen-certs && srvx --prod --tls --cert=tests/.tmp/tls/server.crt --key=tests/.tmp/tls/server.key -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -27,9 +27,20 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "node-forge": "^1.3.1", - "srvx": "0.11.15", + "srvx": "^1.0.0", "tsx": "4.20.3", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" + }, + "nx": { + "targets": { + "test:e2e": { + "outputs": [ + "...", + "{projectRoot}/tests/.tmp/tls" + ] + } + } } } diff --git a/e2e/react-start/early-hints/playwright.config.ts b/e2e/react-start/early-hints/playwright.config.ts index a2435bcf7b..b3606d5586 100644 --- a/e2e/react-start/early-hints/playwright.config.ts +++ b/e2e/react-start/early-hints/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `https://localhost:${PORT}` export default defineConfig({ @@ -17,8 +16,8 @@ export default defineConfig({ webServer: { command: `pnpm build && pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', ignoreHTTPSErrors: true, env: { diff --git a/e2e/react-start/early-hints/src/routeTree.gen.ts b/e2e/react-start/early-hints/src/routeTree.gen.ts index 14e2fd341e..5196090061 100644 --- a/e2e/react-start/early-hints/src/routeTree.gen.ts +++ b/e2e/react-start/early-hints/src/routeTree.gen.ts @@ -9,22 +9,17 @@ // 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 RedirectRouteImport } from './routes/redirect' -import { Route as ParentRouteImport } from './routes/parent' -import { Route as OtherRouteImport } from './routes/other' import { Route as IndexRouteImport } from './routes/index' -import { Route as ParentChildRouteImport } from './routes/parent/child' +import { Route as OtherRouteImport } from './routes/other' +import { Route as ParentRouteImport } from './routes/parent' +import { Route as RedirectRouteImport } from './routes/redirect' import { Route as OtherNestedRouteImport } from './routes/other/nested' +import { Route as ParentChildRouteImport } from './routes/parent/child' import { Route as ParentChildGrandchildRouteImport } from './routes/parent/child/grandchild' -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const ParentRoute = ParentRouteImport.update({ - id: '/parent', - path: '/parent', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const OtherRoute = OtherRouteImport.update({ @@ -32,21 +27,26 @@ const OtherRoute = OtherRouteImport.update({ path: '/other', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ParentRoute = ParentRouteImport.update({ + id: '/parent', + path: '/parent', getParentRoute: () => rootRouteImport, } as any) -const ParentChildRoute = ParentChildRouteImport.update({ - id: '/child', - path: '/child', - getParentRoute: () => ParentRoute, +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', + getParentRoute: () => rootRouteImport, } as any) const OtherNestedRoute = OtherNestedRouteImport.update({ id: '/nested', path: '/nested', getParentRoute: () => OtherRoute, } as any) +const ParentChildRoute = ParentChildRouteImport.update({ + id: '/child', + path: '/child', + getParentRoute: () => ParentRoute, +} as any) const ParentChildGrandchildRoute = ParentChildGrandchildRouteImport.update({ id: '/grandchild', path: '/grandchild', @@ -120,18 +120,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/parent': { - id: '/parent' - path: '/parent' - fullPath: '/parent' - preLoaderRoute: typeof ParentRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/other': { @@ -141,19 +134,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof OtherRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/parent': { + id: '/parent' + path: '/parent' + fullPath: '/parent' + preLoaderRoute: typeof ParentRouteImport parentRoute: typeof rootRouteImport } - '/parent/child': { - id: '/parent/child' - path: '/child' - fullPath: '/parent/child' - preLoaderRoute: typeof ParentChildRouteImport - parentRoute: typeof ParentRoute + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport } '/other/nested': { id: '/other/nested' @@ -162,6 +155,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof OtherNestedRouteImport parentRoute: typeof OtherRoute } + '/parent/child': { + id: '/parent/child' + path: '/child' + fullPath: '/parent/child' + preLoaderRoute: typeof ParentChildRouteImport + parentRoute: typeof ParentRoute + } '/parent/child/grandchild': { id: '/parent/child/grandchild' path: '/grandchild' diff --git a/e2e/react-start/early-hints/tests/early-hints-protocol.spec.ts b/e2e/react-start/early-hints/tests/early-hints-protocol.spec.ts index df0984079e..6d2d31d836 100644 --- a/e2e/react-start/early-hints/tests/early-hints-protocol.spec.ts +++ b/e2e/react-start/early-hints/tests/early-hints-protocol.spec.ts @@ -1,7 +1,5 @@ -import { expect, test } from '@playwright/test' import { connect } from 'node:http2' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from '../package.json' with { type: 'json' } +import { expect, test } from '@playwright/test' import type { IncomingHttpHeaders } from 'node:http2' type Http2Response = { @@ -48,14 +46,14 @@ function linkHeader(headers: IncomingHttpHeaders): string { function earlyHintsLinkHeader(response: Http2Response): string { expect(response.earlyHints.length).toBe(1) - return linkHeader(response.earlyHints[0]!) + return linkHeader(response.earlyHints[0]) } test.describe('Early Hints - HTTP/2 Protocol', () => { let baseURL: string test.beforeAll(async () => { - const PORT = await getTestServerPort(packageJson.name) + const PORT = Number(process.env.E2E_APP_PORT ?? 0) baseURL = `https://localhost:${PORT}` }) @@ -105,7 +103,9 @@ test.describe('Early Hints - HTTP/2 Protocol', () => { const response = await makeRequest(baseURL, '/') const link = earlyHintsLinkHeader(response) - expect(link).toMatch(/<[^>]+>;\s*rel=modulepreload;\s*as=script/) + expect(link).toMatch( + /<[^>]+>;\s*rel=modulepreload;\s*as=script;\s*fetchpriority=low/, + ) }) test('CSS module assets are included in early hints', async () => { @@ -137,7 +137,7 @@ test.describe('Early Hints - HTTP/2 Protocol', () => { expect(response.earlyHints.length).toBe(1) - const link = linkHeader(response.earlyHints[0]!) + const link = linkHeader(response.earlyHints[0]) expect(link).toContain('rel=modulepreload; as=script') expect(link).toContain('; rel=preconnect') @@ -147,7 +147,7 @@ test.describe('Early Hints - HTTP/2 Protocol', () => { const response = await makeRequest(baseURL, '/') const link = linkHeader(response.finalHeaders) - expect(link).toContain('rel=modulepreload; as=script') + expect(link).toContain('rel=modulepreload; as=script; fetchpriority=low') expect(link).toContain('; rel=preconnect') }) diff --git a/e2e/react-start/flamegraph-bench/package.json b/e2e/react-start/flamegraph-bench/package.json index 768c5f05b8..72410b13e1 100644 --- a/e2e/react-start/flamegraph-bench/package.json +++ b/e2e/react-start/flamegraph-bench/package.json @@ -14,15 +14,16 @@ "@tanstack/react-start": "workspace:*", "react": "^19.0.0", "react-dom": "^19.0.0", - "srvx": "^0.11.9" + "srvx": "^1.0.0" }, "devDependencies": { "@platformatic/flame": "latest", "@vitejs/plugin-react": "^6.0.1", - "nitro": "^3.0.260311-beta", + "nitro": "^3.0.260903-beta", "autocannon": "^8.0.0", "concurrently": "9.2.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/e2e/react-start/flamegraph-bench/src/routeTree.gen.ts b/e2e/react-start/flamegraph-bench/src/routeTree.gen.ts index 198d538cd1..cac5558477 100644 --- a/e2e/react-start/flamegraph-bench/src/routeTree.gen.ts +++ b/e2e/react-start/flamegraph-bench/src/routeTree.gen.ts @@ -9,10 +9,10 @@ // 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 SearchRouteImport } from './routes/search' import { Route as IndexRouteImport } from './routes/index' -import { Route as PageIdRouteImport } from './routes/page.$id' +import { Route as SearchRouteImport } from './routes/search' import { Route as NestedARouteImport } from './routes/nested/$a' +import { Route as PageIdRouteImport } from './routes/page.$id' import { Route as NestedABRouteImport } from './routes/nested/$a.$b' import { Route as NestedABCRouteImport } from './routes/nested/$a.$b.$c' import { Route as NestedABCDRouteImport } from './routes/nested/$a.$b.$c.$d' @@ -39,19 +39,14 @@ import { Route as NestedABCDEFGHIJKLMNOPQRSTUVWXRouteImport } from './routes/nes import { Route as NestedABCDEFGHIJKLMNOPQRSTUVWXYRouteImport } from './routes/nested/$a.$b.$c.$d.$e.$f.$g.$h.$i.$j.$k.$l.$m.$n.$o.$p.$q.$r.$s.$t.$u.$v.$w.$x.$y' import { Route as NestedABCDEFGHIJKLMNOPQRSTUVWXYZRouteImport } from './routes/nested/$a.$b.$c.$d.$e.$f.$g.$h.$i.$j.$k.$l.$m.$n.$o.$p.$q.$r.$s.$t.$u.$v.$w.$x.$y.$z' -const SearchRoute = SearchRouteImport.update({ - id: '/search', - path: '/search', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const PageIdRoute = PageIdRouteImport.update({ - id: '/page/$id', - path: '/page/$id', +const SearchRoute = SearchRouteImport.update({ + id: '/search', + path: '/search', getParentRoute: () => rootRouteImport, } as any) const NestedARoute = NestedARouteImport.update({ @@ -59,6 +54,11 @@ const NestedARoute = NestedARouteImport.update({ path: '/nested/$a', getParentRoute: () => rootRouteImport, } as any) +const PageIdRoute = PageIdRouteImport.update({ + id: '/page/$id', + path: '/page/$id', + getParentRoute: () => rootRouteImport, +} as any) const NestedABRoute = NestedABRouteImport.update({ id: '/$b', path: '/$b', @@ -393,13 +393,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/search': { - id: '/search' - path: '/search' - fullPath: '/search' - preLoaderRoute: typeof SearchRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -407,11 +400,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/page/$id': { - id: '/page/$id' - path: '/page/$id' - fullPath: '/page/$id' - preLoaderRoute: typeof PageIdRouteImport + '/search': { + id: '/search' + path: '/search' + fullPath: '/search' + preLoaderRoute: typeof SearchRouteImport parentRoute: typeof rootRouteImport } '/nested/$a': { @@ -421,6 +414,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof NestedARouteImport parentRoute: typeof rootRouteImport } + '/page/$id': { + id: '/page/$id' + path: '/page/$id' + fullPath: '/page/$id' + preLoaderRoute: typeof PageIdRouteImport + parentRoute: typeof rootRouteImport + } '/nested/$a/$b': { id: '/nested/$a/$b' path: '/$b' diff --git a/e2e/react-start/hmr/package.json b/e2e/react-start/hmr/package.json index 7c5b6133c1..76a5d86b1f 100644 --- a/e2e/react-start/hmr/package.json +++ b/e2e/react-start/hmr/package.json @@ -21,7 +21,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.0.11", + "@rsbuild/core": "^2.3.1", "@rsbuild/plugin-react": "^2.0.0", "@tailwindcss/postcss": "^4.2.2", "@tailwindcss/vite": "^4.2.2", @@ -31,7 +31,8 @@ "@types/react-dom": "^19.0.3", "tailwindcss": "^4.2.2", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" }, "nx": { diff --git a/e2e/react-start/hmr/playwright.config.ts b/e2e/react-start/hmr/playwright.config.ts index c159aad328..5840ec157a 100644 --- a/e2e/react-start/hmr/playwright.config.ts +++ b/e2e/react-start/hmr/playwright.config.ts @@ -1,13 +1,11 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' -const e2ePortKey = - process.env.E2E_PORT_KEY ?? `${packageJson.name}-${toolchain}` + const distDir = process.env.E2E_DIST_DIR ?? 'dist' const viteBundledDev = process.env.E2E_VITE_BUNDLED_DEV === 'true' -const PORT = await getTestServerPort(e2ePortKey) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` const devCommand = toolchain === 'rsbuild' ? 'pnpm dev:rsbuild' : 'pnpm dev:vite' @@ -18,7 +16,6 @@ export default defineConfig({ reporter: [['line']], globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', use: { baseURL, @@ -26,15 +23,14 @@ export default defineConfig({ webServer: { command: `${devCommand} --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', env: { VITE_NODE_ENV: 'test', PORT: String(PORT), E2E_TOOLCHAIN: toolchain, E2E_DIST_DIR: distDir, - E2E_PORT_KEY: e2ePortKey, E2E_VITE_BUNDLED_DEV: String(viteBundledDev), }, }, diff --git a/e2e/react-start/hmr/rsbuild.config.ts b/e2e/react-start/hmr/rsbuild.config.ts index 126e7d9888..2f3829f661 100644 --- a/e2e/react-start/hmr/rsbuild.config.ts +++ b/e2e/react-start/hmr/rsbuild.config.ts @@ -5,7 +5,7 @@ import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' const outDir = process.env.E2E_DIST_DIR ?? 'dist' export default defineConfig({ - plugins: [pluginReact({ splitChunks: false }), tanstackStart()], + plugins: [pluginReact(), tanstackStart()], output: { distPath: { root: outDir, diff --git a/e2e/react-start/hmr/src/routeTree.gen.ts b/e2e/react-start/hmr/src/routeTree.gen.ts index 53c89f8eb5..73d8bd14f5 100644 --- a/e2e/react-start/hmr/src/routeTree.gen.ts +++ b/e2e/react-start/hmr/src/routeTree.gen.ts @@ -9,39 +9,57 @@ // 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 ServerFnHmrRouteImport } from './routes/server-fn-hmr' -import { Route as InputsRouteImport } from './routes/inputs' -import { Route as ComponentHmrNamedSplitRouteImport } from './routes/component-hmr-named-split' -import { Route as ComponentHmrNamedNosplitRouteImport } from './routes/component-hmr-named-nosplit' -import { Route as ComponentHmrNamedErrorSplitRouteImport } from './routes/component-hmr-named-error-split' -import { Route as ComponentHmrInlineSplitRouteImport } from './routes/component-hmr-inline-split' -import { Route as ComponentHmrInlineNosplitRouteImport } from './routes/component-hmr-inline-nosplit' -import { Route as ComponentHmrInlineErrorSplitRouteImport } from './routes/component-hmr-inline-error-split' -import { Route as ComponentHmrRouteImport } from './routes/component-hmr' -import { Route as ChildRouteImport } from './routes/child' import { Route as IndexRouteImport } from './routes/index' +import { Route as ChildRouteImport } from './routes/child' +import { Route as ComponentHmrRouteImport } from './routes/component-hmr' +import { Route as ComponentHmrInlineErrorSplitRouteImport } from './routes/component-hmr-inline-error-split' +import { Route as ComponentHmrInlineNosplitRouteImport } from './routes/component-hmr-inline-nosplit' +import { Route as ComponentHmrInlineSplitRouteImport } from './routes/component-hmr-inline-split' +import { Route as ComponentHmrLowercaseNamedSplitRouteImport } from './routes/component-hmr-lowercase-named-split' +import { Route as ComponentHmrNamedErrorSplitRouteImport } from './routes/component-hmr-named-error-split' +import { Route as ComponentHmrNamedNosplitRouteImport } from './routes/component-hmr-named-nosplit' +import { Route as ComponentHmrNamedSplitRouteImport } from './routes/component-hmr-named-split' +import { Route as InputsRouteImport } from './routes/inputs' +import { Route as ServerFnHmrRouteImport } from './routes/server-fn-hmr' import { Route as AliasedRouteImportsIdRouteImport } from './routes/aliased-route-imports.$id' import { Route as AliasedRouteImportsIdChildRouteImport } from './routes/aliased-route-imports.$id.child' -const ServerFnHmrRoute = ServerFnHmrRouteImport.update({ - id: '/server-fn-hmr', - path: '/server-fn-hmr', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const InputsRoute = InputsRouteImport.update({ - id: '/inputs', - path: '/inputs', +const ChildRoute = ChildRouteImport.update({ + id: '/child', + path: '/child', getParentRoute: () => rootRouteImport, } as any) -const ComponentHmrNamedSplitRoute = ComponentHmrNamedSplitRouteImport.update({ - id: '/component-hmr-named-split', - path: '/component-hmr-named-split', +const ComponentHmrRoute = ComponentHmrRouteImport.update({ + id: '/component-hmr', + path: '/component-hmr', getParentRoute: () => rootRouteImport, } as any) -const ComponentHmrNamedNosplitRoute = - ComponentHmrNamedNosplitRouteImport.update({ - id: '/component-hmr-named-nosplit', - path: '/component-hmr-named-nosplit', +const ComponentHmrInlineErrorSplitRoute = + ComponentHmrInlineErrorSplitRouteImport.update({ + id: '/component-hmr-inline-error-split', + path: '/component-hmr-inline-error-split', + getParentRoute: () => rootRouteImport, + } as any) +const ComponentHmrInlineNosplitRoute = + ComponentHmrInlineNosplitRouteImport.update({ + id: '/component-hmr-inline-nosplit', + path: '/component-hmr-inline-nosplit', + getParentRoute: () => rootRouteImport, + } as any) +const ComponentHmrInlineSplitRoute = ComponentHmrInlineSplitRouteImport.update({ + id: '/component-hmr-inline-split', + path: '/component-hmr-inline-split', + getParentRoute: () => rootRouteImport, +} as any) +const ComponentHmrLowercaseNamedSplitRoute = + ComponentHmrLowercaseNamedSplitRouteImport.update({ + id: '/component-hmr-lowercase-named-split', + path: '/component-hmr-lowercase-named-split', getParentRoute: () => rootRouteImport, } as any) const ComponentHmrNamedErrorSplitRoute = @@ -50,36 +68,25 @@ const ComponentHmrNamedErrorSplitRoute = path: '/component-hmr-named-error-split', getParentRoute: () => rootRouteImport, } as any) -const ComponentHmrInlineSplitRoute = ComponentHmrInlineSplitRouteImport.update({ - id: '/component-hmr-inline-split', - path: '/component-hmr-inline-split', - getParentRoute: () => rootRouteImport, -} as any) -const ComponentHmrInlineNosplitRoute = - ComponentHmrInlineNosplitRouteImport.update({ - id: '/component-hmr-inline-nosplit', - path: '/component-hmr-inline-nosplit', +const ComponentHmrNamedNosplitRoute = + ComponentHmrNamedNosplitRouteImport.update({ + id: '/component-hmr-named-nosplit', + path: '/component-hmr-named-nosplit', getParentRoute: () => rootRouteImport, } as any) -const ComponentHmrInlineErrorSplitRoute = - ComponentHmrInlineErrorSplitRouteImport.update({ - id: '/component-hmr-inline-error-split', - path: '/component-hmr-inline-error-split', - getParentRoute: () => rootRouteImport, - } as any) -const ComponentHmrRoute = ComponentHmrRouteImport.update({ - id: '/component-hmr', - path: '/component-hmr', +const ComponentHmrNamedSplitRoute = ComponentHmrNamedSplitRouteImport.update({ + id: '/component-hmr-named-split', + path: '/component-hmr-named-split', getParentRoute: () => rootRouteImport, } as any) -const ChildRoute = ChildRouteImport.update({ - id: '/child', - path: '/child', +const InputsRoute = InputsRouteImport.update({ + id: '/inputs', + path: '/inputs', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ServerFnHmrRoute = ServerFnHmrRouteImport.update({ + id: '/server-fn-hmr', + path: '/server-fn-hmr', getParentRoute: () => rootRouteImport, } as any) const AliasedRouteImportsIdRoute = AliasedRouteImportsIdRouteImport.update({ @@ -101,6 +108,7 @@ export interface FileRoutesByFullPath { '/component-hmr-inline-error-split': typeof ComponentHmrInlineErrorSplitRoute '/component-hmr-inline-nosplit': typeof ComponentHmrInlineNosplitRoute '/component-hmr-inline-split': typeof ComponentHmrInlineSplitRoute + '/component-hmr-lowercase-named-split': typeof ComponentHmrLowercaseNamedSplitRoute '/component-hmr-named-error-split': typeof ComponentHmrNamedErrorSplitRoute '/component-hmr-named-nosplit': typeof ComponentHmrNamedNosplitRoute '/component-hmr-named-split': typeof ComponentHmrNamedSplitRoute @@ -116,6 +124,7 @@ export interface FileRoutesByTo { '/component-hmr-inline-error-split': typeof ComponentHmrInlineErrorSplitRoute '/component-hmr-inline-nosplit': typeof ComponentHmrInlineNosplitRoute '/component-hmr-inline-split': typeof ComponentHmrInlineSplitRoute + '/component-hmr-lowercase-named-split': typeof ComponentHmrLowercaseNamedSplitRoute '/component-hmr-named-error-split': typeof ComponentHmrNamedErrorSplitRoute '/component-hmr-named-nosplit': typeof ComponentHmrNamedNosplitRoute '/component-hmr-named-split': typeof ComponentHmrNamedSplitRoute @@ -132,6 +141,7 @@ export interface FileRoutesById { '/component-hmr-inline-error-split': typeof ComponentHmrInlineErrorSplitRoute '/component-hmr-inline-nosplit': typeof ComponentHmrInlineNosplitRoute '/component-hmr-inline-split': typeof ComponentHmrInlineSplitRoute + '/component-hmr-lowercase-named-split': typeof ComponentHmrLowercaseNamedSplitRoute '/component-hmr-named-error-split': typeof ComponentHmrNamedErrorSplitRoute '/component-hmr-named-nosplit': typeof ComponentHmrNamedNosplitRoute '/component-hmr-named-split': typeof ComponentHmrNamedSplitRoute @@ -149,6 +159,7 @@ export interface FileRouteTypes { | '/component-hmr-inline-error-split' | '/component-hmr-inline-nosplit' | '/component-hmr-inline-split' + | '/component-hmr-lowercase-named-split' | '/component-hmr-named-error-split' | '/component-hmr-named-nosplit' | '/component-hmr-named-split' @@ -164,6 +175,7 @@ export interface FileRouteTypes { | '/component-hmr-inline-error-split' | '/component-hmr-inline-nosplit' | '/component-hmr-inline-split' + | '/component-hmr-lowercase-named-split' | '/component-hmr-named-error-split' | '/component-hmr-named-nosplit' | '/component-hmr-named-split' @@ -179,6 +191,7 @@ export interface FileRouteTypes { | '/component-hmr-inline-error-split' | '/component-hmr-inline-nosplit' | '/component-hmr-inline-split' + | '/component-hmr-lowercase-named-split' | '/component-hmr-named-error-split' | '/component-hmr-named-nosplit' | '/component-hmr-named-split' @@ -195,6 +208,7 @@ export interface RootRouteChildren { ComponentHmrInlineErrorSplitRoute: typeof ComponentHmrInlineErrorSplitRoute ComponentHmrInlineNosplitRoute: typeof ComponentHmrInlineNosplitRoute ComponentHmrInlineSplitRoute: typeof ComponentHmrInlineSplitRoute + ComponentHmrLowercaseNamedSplitRoute: typeof ComponentHmrLowercaseNamedSplitRoute ComponentHmrNamedErrorSplitRoute: typeof ComponentHmrNamedErrorSplitRoute ComponentHmrNamedNosplitRoute: typeof ComponentHmrNamedNosplitRoute ComponentHmrNamedSplitRoute: typeof ComponentHmrNamedSplitRoute @@ -205,67 +219,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/server-fn-hmr': { - id: '/server-fn-hmr' - path: '/server-fn-hmr' - fullPath: '/server-fn-hmr' - preLoaderRoute: typeof ServerFnHmrRouteImport - parentRoute: typeof rootRouteImport - } - '/inputs': { - id: '/inputs' - path: '/inputs' - fullPath: '/inputs' - preLoaderRoute: typeof InputsRouteImport - parentRoute: typeof rootRouteImport - } - '/component-hmr-named-split': { - id: '/component-hmr-named-split' - path: '/component-hmr-named-split' - fullPath: '/component-hmr-named-split' - preLoaderRoute: typeof ComponentHmrNamedSplitRouteImport - parentRoute: typeof rootRouteImport - } - '/component-hmr-named-nosplit': { - id: '/component-hmr-named-nosplit' - path: '/component-hmr-named-nosplit' - fullPath: '/component-hmr-named-nosplit' - preLoaderRoute: typeof ComponentHmrNamedNosplitRouteImport - parentRoute: typeof rootRouteImport - } - '/component-hmr-named-error-split': { - id: '/component-hmr-named-error-split' - path: '/component-hmr-named-error-split' - fullPath: '/component-hmr-named-error-split' - preLoaderRoute: typeof ComponentHmrNamedErrorSplitRouteImport - parentRoute: typeof rootRouteImport - } - '/component-hmr-inline-split': { - id: '/component-hmr-inline-split' - path: '/component-hmr-inline-split' - fullPath: '/component-hmr-inline-split' - preLoaderRoute: typeof ComponentHmrInlineSplitRouteImport - parentRoute: typeof rootRouteImport - } - '/component-hmr-inline-nosplit': { - id: '/component-hmr-inline-nosplit' - path: '/component-hmr-inline-nosplit' - fullPath: '/component-hmr-inline-nosplit' - preLoaderRoute: typeof ComponentHmrInlineNosplitRouteImport - parentRoute: typeof rootRouteImport - } - '/component-hmr-inline-error-split': { - id: '/component-hmr-inline-error-split' - path: '/component-hmr-inline-error-split' - fullPath: '/component-hmr-inline-error-split' - preLoaderRoute: typeof ComponentHmrInlineErrorSplitRouteImport - parentRoute: typeof rootRouteImport - } - '/component-hmr': { - id: '/component-hmr' - path: '/component-hmr' - fullPath: '/component-hmr' - preLoaderRoute: typeof ComponentHmrRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/child': { @@ -275,11 +233,74 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ChildRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/component-hmr': { + id: '/component-hmr' + path: '/component-hmr' + fullPath: '/component-hmr' + preLoaderRoute: typeof ComponentHmrRouteImport + parentRoute: typeof rootRouteImport + } + '/component-hmr-inline-error-split': { + id: '/component-hmr-inline-error-split' + path: '/component-hmr-inline-error-split' + fullPath: '/component-hmr-inline-error-split' + preLoaderRoute: typeof ComponentHmrInlineErrorSplitRouteImport + parentRoute: typeof rootRouteImport + } + '/component-hmr-inline-nosplit': { + id: '/component-hmr-inline-nosplit' + path: '/component-hmr-inline-nosplit' + fullPath: '/component-hmr-inline-nosplit' + preLoaderRoute: typeof ComponentHmrInlineNosplitRouteImport + parentRoute: typeof rootRouteImport + } + '/component-hmr-inline-split': { + id: '/component-hmr-inline-split' + path: '/component-hmr-inline-split' + fullPath: '/component-hmr-inline-split' + preLoaderRoute: typeof ComponentHmrInlineSplitRouteImport + parentRoute: typeof rootRouteImport + } + '/component-hmr-lowercase-named-split': { + id: '/component-hmr-lowercase-named-split' + path: '/component-hmr-lowercase-named-split' + fullPath: '/component-hmr-lowercase-named-split' + preLoaderRoute: typeof ComponentHmrLowercaseNamedSplitRouteImport + parentRoute: typeof rootRouteImport + } + '/component-hmr-named-error-split': { + id: '/component-hmr-named-error-split' + path: '/component-hmr-named-error-split' + fullPath: '/component-hmr-named-error-split' + preLoaderRoute: typeof ComponentHmrNamedErrorSplitRouteImport + parentRoute: typeof rootRouteImport + } + '/component-hmr-named-nosplit': { + id: '/component-hmr-named-nosplit' + path: '/component-hmr-named-nosplit' + fullPath: '/component-hmr-named-nosplit' + preLoaderRoute: typeof ComponentHmrNamedNosplitRouteImport + parentRoute: typeof rootRouteImport + } + '/component-hmr-named-split': { + id: '/component-hmr-named-split' + path: '/component-hmr-named-split' + fullPath: '/component-hmr-named-split' + preLoaderRoute: typeof ComponentHmrNamedSplitRouteImport + parentRoute: typeof rootRouteImport + } + '/inputs': { + id: '/inputs' + path: '/inputs' + fullPath: '/inputs' + preLoaderRoute: typeof InputsRouteImport + parentRoute: typeof rootRouteImport + } + '/server-fn-hmr': { + id: '/server-fn-hmr' + path: '/server-fn-hmr' + fullPath: '/server-fn-hmr' + preLoaderRoute: typeof ServerFnHmrRouteImport parentRoute: typeof rootRouteImport } '/aliased-route-imports/$id': { @@ -319,6 +340,7 @@ const rootRouteChildren: RootRouteChildren = { ComponentHmrInlineErrorSplitRoute: ComponentHmrInlineErrorSplitRoute, ComponentHmrInlineNosplitRoute: ComponentHmrInlineNosplitRoute, ComponentHmrInlineSplitRoute: ComponentHmrInlineSplitRoute, + ComponentHmrLowercaseNamedSplitRoute: ComponentHmrLowercaseNamedSplitRoute, ComponentHmrNamedErrorSplitRoute: ComponentHmrNamedErrorSplitRoute, ComponentHmrNamedNosplitRoute: ComponentHmrNamedNosplitRoute, ComponentHmrNamedSplitRoute: ComponentHmrNamedSplitRoute, diff --git a/e2e/react-start/hmr/src/routes/__root.tsx b/e2e/react-start/hmr/src/routes/__root.tsx index b2ec48fb70..22dddf1b3c 100644 --- a/e2e/react-start/hmr/src/routes/__root.tsx +++ b/e2e/react-start/hmr/src/routes/__root.tsx @@ -164,6 +164,12 @@ function RootContent() { label: 'Named Split', detail: 'Named component with default splitting', }, + { + testId: 'component-hmr-lowercase-named-split-link', + to: '/component-hmr-lowercase-named-split', + label: 'Lowercase Named Split', + detail: 'Lowercase named component with default splitting', + }, { testId: 'component-hmr-named-nosplit-link', to: '/component-hmr-named-nosplit', diff --git a/e2e/react-start/hmr/src/routes/component-hmr-lowercase-named-split.tsx b/e2e/react-start/hmr/src/routes/component-hmr-lowercase-named-split.tsx new file mode 100644 index 0000000000..957e14d7a4 --- /dev/null +++ b/e2e/react-start/hmr/src/routes/component-hmr-lowercase-named-split.tsx @@ -0,0 +1,26 @@ +import { createFileRoute } from '@tanstack/react-router' +import { useState } from 'react' + +export const Route = createFileRoute('/component-hmr-lowercase-named-split')({ + component, +}) + +function component() { + const [count, setCount] = useState(0) + + return ( +
+

+ component-hmr-lowercase-named-split-baseline +

+

Count: {count}

+ + +
+ ) +} diff --git a/e2e/react-start/hmr/tests/app.spec.ts b/e2e/react-start/hmr/tests/app.spec.ts index 10499e4b88..645c9b06f3 100644 --- a/e2e/react-start/hmr/tests/app.spec.ts +++ b/e2e/react-start/hmr/tests/app.spec.ts @@ -11,6 +11,7 @@ import type { Page } from '@playwright/test' const whitelistErrors = [ 'Failed to load resource: net::ERR_NAME_NOT_RESOLVED', 'Failed to load resource: the server responded with a status of 504', + 'root loader error', ] const hmrExpect = expect.configure({ timeout: 20_000 }) @@ -24,6 +25,8 @@ const routeFilePaths = { componentHmrInlineSplit: 'routes/component-hmr-inline-split.tsx', componentHmrInlineNosplit: 'routes/component-hmr-inline-nosplit.tsx', componentHmrNamedSplit: 'routes/component-hmr-named-split.tsx', + componentHmrLowercaseNamedSplit: + 'routes/component-hmr-lowercase-named-split.tsx', componentHmrNamedNosplit: 'routes/component-hmr-named-nosplit.tsx', componentHmrInlineErrorSplit: 'routes/component-hmr-inline-error-split.tsx', componentHmrNamedErrorSplit: 'routes/component-hmr-named-error-split.tsx', @@ -35,6 +38,21 @@ const routeFilePaths = { type RouteFileKey = keyof typeof routeFilePaths +const rootLoaderBlock = " loader: () => ({\n crumb: 'Home',\n }),\n" +const redirectRootLoaderBlock = + " staleTime: Infinity,\n loader: () => ({\n crumb:\n typeof window === 'undefined'\n ? 'Home Armed'\n : (window.sessionStorage.getItem('hmr-root-crumb') ?? 'Home Armed'),\n }),\n" +const childBeforeLoadBlock = + " beforeLoad: () => ({\n greeting: 'Hello',\n }),\n" +const childLoaderBlock = " loader: () => ({\n crumb: 'Child',\n }),\n" +const failingChildOnStayBlock = + " onStay: () => {\n ;(window as any).__TSR_HMR_FAILURE_RAN__ = true\n throw new Error('intentional HMR lifecycle failure')\n },\n" +const pendingNavigationChildLoaderBlock = + " loader: async () => {\n if (typeof window !== 'undefined') {\n const gate = (window as any).__TSR_HMR_PENDING_NAV_GATE__\n if (gate) {\n ;(window as any).__TSR_HMR_PENDING_NAV_GATE__ = undefined\n ;(window as any).__TSR_HMR_PENDING_NAV_EVENTS__.push('loader-start')\n await gate\n ;(window as any).__TSR_HMR_PENDING_NAV_EVENTS__.push('loader-end')\n }\n }\n return { crumb: 'Child' }\n },\n" +const pendingNavigationChildOnStayBlock = + " onStay: () => {\n ;(window as any).__TSR_HMR_PENDING_NAV_EVENTS__.push('onStay')\n throw new Error('intentional HMR failure after pending navigation')\n },\n" +const redirectChildBeforeLoadBlock = + " beforeLoad: () => {\n throw redirect({ to: '/' })\n },\n" + const routeFiles = Object.fromEntries( Object.entries(routeFilePaths).map(([key, relativePath]) => [ key, @@ -99,6 +117,11 @@ const routeFileRestoreChecks: Partial< testId: 'component-hmr-marker', text: 'component-hmr-named-split-baseline', }, + componentHmrLowercaseNamedSplit: { + url: '/component-hmr-lowercase-named-split', + testId: 'component-hmr-marker', + text: 'component-hmr-lowercase-named-split-baseline', + }, componentHmrNamedNosplit: { url: '/component-hmr-named-nosplit', testId: 'component-hmr-marker', @@ -133,6 +156,8 @@ function normalizeRouteSource(routeFileKey: RouteFileKey, source: string) { } if (routeFileKey === 'root') { + next = next.replace(redirectRootLoaderBlock, rootLoaderBlock) + for (const marker of [ 'root-component-inline-baseline', 'root-component-inline-updated', @@ -158,6 +183,16 @@ function normalizeRouteSource(routeFileKey: RouteFileKey, source: string) { ' component: RootComponent,', ) + next = next.replace( + ' shellComponent: shellComponent,\n component: RootContent,', + ' component: RootComponent,', + ) + + next = next.replace( + " loader: () => {\n throw new Error('root loader error')\n },\n errorComponent: errorComponent,\n component: RootComponent,", + " loader: () => ({\n crumb: 'Home',\n }),\n component: RootComponent,", + ) + for (const marker of ['root-shell-baseline', 'root-shell-updated']) { next = next.replace( `function RootShell({ children }: { children: ReactNode }) {\n return {children}\n}\n\nfunction Breadcrumbs() {`, @@ -165,36 +200,62 @@ function normalizeRouteSource(routeFileKey: RouteFileKey, source: string) { ) } + for (const marker of [ + 'root-shell-lowercase-baseline', + 'root-shell-lowercase-updated', + ]) { + next = next.replace( + `function shellComponent({ children }: { children: ReactNode }) {\n return {children}\n}\n\nfunction Breadcrumbs() {`, + 'function Breadcrumbs() {', + ) + } + + for (const marker of [ + 'root-error-lowercase-baseline', + 'root-error-lowercase-updated', + ]) { + next = next.replace( + `function errorComponent() {\n return (\n \n

${marker}

\n
\n )\n}\n\nfunction Breadcrumbs() {`, + 'function Breadcrumbs() {', + ) + } + next = replaceAll(next, "crumb: 'Home Updated'", "crumb: 'Home'") next = replaceAll(next, 'root-component-updated', 'root-component-baseline') next = replaceAll(next, 'root-shell-updated', 'root-shell-baseline') } if (routeFileKey === 'child') { - const beforeLoadBlock = - " beforeLoad: () => ({\n greeting: 'Hello',\n }),\n" - const loaderBlock = " loader: () => ({\n crumb: 'Child',\n }),\n" - next = replaceAll(next, "greeting: 'Hi'", "greeting: 'Hello'") + next = next.replace(failingChildOnStayBlock, '') + next = next.replace(pendingNavigationChildOnStayBlock, '') + next = next.replace(pendingNavigationChildLoaderBlock, childLoaderBlock) + next = next.replace(redirectChildBeforeLoadBlock, childBeforeLoadBlock) + next = next.replace( + "import { createFileRoute, redirect } from '@tanstack/react-router'", + "import { createFileRoute } from '@tanstack/react-router'", + ) + next = replaceAll(next, "crumb: 'Child Recovered'", "crumb: 'Child'") + next = replaceAll(next, "crumb: 'Child Failed'", "crumb: 'Child'") next = replaceAll(next, "crumb: 'Child Updated Again'", "crumb: 'Child'") next = replaceAll(next, "crumb: 'Child Updated'", "crumb: 'Child'") - if (!next.includes(beforeLoadBlock)) { + if (!next.includes(childBeforeLoadBlock)) { next = next.replace( ' component: Child,\n', - `${beforeLoadBlock} component: Child,\n`, + `${childBeforeLoadBlock} component: Child,\n`, ) } - if (!next.includes(loaderBlock)) { + if (!next.includes(childLoaderBlock)) { const withLoaderAfterBeforeLoad = next.replace( - `${beforeLoadBlock} component: Child,\n`, - `${beforeLoadBlock}${loaderBlock} component: Child,\n`, + `${childBeforeLoadBlock} component: Child,\n`, + `${childBeforeLoadBlock}${childLoaderBlock} component: Child,\n`, ) next = withLoaderAfterBeforeLoad === next ? next.replace( ' component: Child,\n', - `${loaderBlock} component: Child,\n`, + `${childLoaderBlock} component: Child,\n`, ) : withLoaderAfterBeforeLoad } @@ -214,6 +275,10 @@ function normalizeRouteSource(routeFileKey: RouteFileKey, source: string) { 'component-hmr-named-split-updated', 'component-hmr-named-split-baseline', ], + componentHmrLowercaseNamedSplit: [ + 'component-hmr-lowercase-named-split-updated', + 'component-hmr-lowercase-named-split-baseline', + ], componentHmrNamedNosplit: [ 'component-hmr-named-nosplit-updated', 'component-hmr-named-nosplit-baseline', @@ -542,8 +607,18 @@ test.describe('react-start hmr', () => { test('preserves local state for code-split route component HMR', async ({ page, }) => { + // Hydration can finish before Vite connects its HMR socket. + const hmrReady = + (process.env.E2E_TOOLCHAIN ?? 'vite') === 'vite' + ? page.waitForEvent('websocket').then((socket) => { + return socket.waitForEvent('framereceived', ({ payload }) => { + return JSON.parse(String(payload)).type === 'connected' + }) + }) + : Promise.resolve() await page.goto('/') await page.getByTestId('hydrated').waitFor({ state: 'visible' }) + await hmrReady await page.getByTestId('increment').click() await page.getByTestId('message').fill('hmr state') @@ -619,6 +694,178 @@ test.describe('react-start hmr', () => { await expect(page.getByTestId('child')).toHaveText('child') }) + test('publishes a failed route refresh and accepts the next HMR update', async ({ + page, + }) => { + await page.goto('/child') + await page.getByTestId('hydrated').waitFor({ state: 'visible' }) + await page.getByTestId('root-message').fill('preserved through failure') + await expect(page.getByTestId('crumb-/child')).toHaveText('Child') + + await page.evaluate(() => { + ;(window as any).__TSR_HMR_FAILURE_RAN__ = false + }) + + await rewriteRouteFile( + page, + 'child', + (source) => + source.replace( + childLoaderBlock, + `${failingChildOnStayBlock} loader: () => ({\n crumb: 'Child Failed',\n }),\n`, + ), + async () => { + await waitForRouteModuleUpdate(page, '/child', 'Child Failed') + await page.waitForFunction( + () => (window as any).__TSR_HMR_FAILURE_RAN__ === true, + ) + }, + ) + + await expect(page.getByTestId('crumb-/child')).toHaveText('Child Failed') + await expect(page.getByTestId('root-message')).toHaveValue( + 'preserved through failure', + ) + + await rewriteRouteFile( + page, + 'child', + (source) => + source + .replace(failingChildOnStayBlock, '') + .replace("crumb: 'Child Failed'", "crumb: 'Child Recovered'"), + async () => { + await waitForRouteModuleUpdate(page, '/child', 'Child Recovered') + await hmrExpect(page.getByTestId('crumb-/child')).toHaveText( + 'Child Recovered', + ) + }, + ) + + await expect(page.getByTestId('root-message')).toHaveValue( + 'preserved through failure', + ) + }) + + test('rematerializes retained routes when an HMR update redirects', async ({ + page, + }) => { + await page.goto('/child') + await page.getByTestId('hydrated').waitFor({ state: 'visible' }) + await page.getByTestId('root-message').fill('preserved through redirect') + + await rewriteRouteFile( + page, + 'root', + (source) => source.replace(rootLoaderBlock, redirectRootLoaderBlock), + async () => { + await waitForRouteModuleUpdate(page, '__root__', 'Home Armed') + await hmrExpect(page.getByTestId('crumb-__root__')).toHaveText( + 'Home Armed', + ) + }, + ) + + await page.evaluate(() => { + window.sessionStorage.setItem('hmr-root-crumb', 'Home Redirected') + }) + + await rewriteRouteFile( + page, + 'child', + (source) => + source + .replace( + "import { createFileRoute } from '@tanstack/react-router'", + "import { createFileRoute, redirect } from '@tanstack/react-router'", + ) + .replace(childBeforeLoadBlock, redirectChildBeforeLoadBlock), + async () => { + await hmrExpect(page).toHaveURL((url) => url.pathname === '/') + await hmrExpect(page.getByTestId('crumb-__root__')).toHaveText( + 'Home Redirected', + ) + }, + ) + + await expect(page.getByTestId('root-message')).toHaveValue( + 'preserved through redirect', + ) + }) + + test('waits for a pending navigation before applying an HMR refresh', async ({ + page, + }) => { + await page.goto('/') + await page.getByTestId('hydrated').waitFor({ state: 'visible' }) + await page.getByTestId('root-message').fill('preserved while pending') + + await page.evaluate(() => { + let release!: () => void + const gate = new Promise((resolve) => { + release = resolve + }) + ;(window as any).__TSR_HMR_PENDING_NAV_EVENTS__ = [] + ;(window as any).__TSR_HMR_PENDING_NAV_GATE__ = gate + ;(window as any).__TSR_HMR_RELEASE_PENDING_NAV__ = release + }) + + await rewriteRouteFile( + page, + 'child', + (source) => + source.replace(childLoaderBlock, pendingNavigationChildLoaderBlock), + async () => { + await page.waitForFunction(() => { + const loader = (window as any).__TSR_ROUTER__?.routesById?.['/child'] + ?.options?.loader + return String(loader).includes('__TSR_HMR_PENDING_NAV_GATE__') + }) + }, + ) + + await page.getByTestId('child-link').click() + await page.waitForFunction( + () => + (window as any).__TSR_HMR_PENDING_NAV_EVENTS__?.[0] === 'loader-start', + ) + + await rewriteRouteFile( + page, + 'child', + (source) => + source.replace( + pendingNavigationChildLoaderBlock, + `${pendingNavigationChildOnStayBlock}${pendingNavigationChildLoaderBlock}`, + ), + async () => { + await page.waitForFunction(() => { + const onStay = (window as any).__TSR_ROUTER__?.routesById?.['/child'] + ?.options?.onStay + return String(onStay).includes( + 'intentional HMR failure after pending navigation', + ) + }) + }, + ) + + await page.evaluate(() => { + ;(window as any).__TSR_HMR_RELEASE_PENDING_NAV__() + }) + + await page.waitForFunction(() => + (window as any).__TSR_HMR_PENDING_NAV_EVENTS__?.includes('onStay'), + ) + await hmrExpect(page.getByTestId('child')).toHaveText('child') + await hmrExpect(page.getByTestId('crumb-/child')).toHaveText('Child') + expect( + await page.evaluate(() => (window as any).__TSR_HMR_PENDING_NAV_EVENTS__), + ).toEqual(['loader-start', 'loader-end', 'onStay']) + await expect(page.getByTestId('root-message')).toHaveValue( + 'preserved while pending', + ) + }) + test('adds a createFileRoute property during HMR', async ({ page }) => { await page.goto('/') await page.getByTestId('hydrated').waitFor({ state: 'visible' }) @@ -685,6 +932,7 @@ test.describe('react-start hmr', () => { await waitForRouteModuleUpdate(page, '/child', 'Child Updated') }, ) + await waitForHydrationSafeReload(page, '/child', 'Child Updated') // Second edit: change child loader again while still on / await replaceRouteTextAndWait( @@ -1032,6 +1280,89 @@ test.describe('react-start hmr', () => { ) }) + test('updates root route shellComponent during HMR when its function name is lowercase', async ({ + page, + }) => { + await rewriteRouteFile( + page, + 'root', + (source) => + source + .replace( + ' component: RootComponent,', + ' shellComponent: shellComponent,\n component: RootContent,', + ) + .replace( + 'function Breadcrumbs() {', + 'function shellComponent({ children }: { children: ReactNode }) {\n return {children}\n}\n\nfunction Breadcrumbs() {', + ), + async () => {}, + ) + await page.waitForTimeout(300) + + await reloadPageAndWaitForText( + page, + '/', + 'root-shell-marker', + 'root-shell-lowercase-baseline', + ) + await page.getByTestId('increment').click() + await page.getByTestId('message').fill('index preserved') + await page.getByTestId('root-message').fill('root preserved') + + await replaceRouteTextAndWait( + page, + 'root', + 'root-shell-lowercase-baseline', + 'root-shell-lowercase-updated', + async () => { + await hmrExpect(page.getByTestId('root-shell-marker')).toHaveText( + 'root-shell-lowercase-updated', + ) + }, + ) + + await expectHomeStatePreserved(page) + }) + + test('updates root route errorComponent during HMR when its function name is lowercase', async ({ + page, + }) => { + await seedHomeState(page) + + await rewriteRouteFile( + page, + 'root', + (source) => + source + .replace( + " loader: () => ({\n crumb: 'Home',\n }),\n component: RootComponent,", + " loader: () => {\n throw new Error('root loader error')\n },\n errorComponent: errorComponent,\n component: RootComponent,", + ) + .replace( + 'function Breadcrumbs() {', + 'function errorComponent() {\n return (\n \n

root-error-lowercase-baseline

\n
\n )\n}\n\nfunction Breadcrumbs() {', + ), + async () => { + await hmrExpect(page.getByTestId('root-error-marker')).toHaveText( + 'root-error-lowercase-baseline', + ) + }, + ) + + await replaceRouteTextAndWait( + page, + 'root', + 'root-error-lowercase-baseline', + 'root-error-lowercase-updated', + async () => { + await hmrExpect(page.getByTestId('root-error-marker')).toHaveText( + 'root-error-lowercase-updated', + ) + }, + ) + }) + test('updates non-root route component during HMR when component is defined inline and codeSplitGroupings is undefined', async ({ page, }) => { @@ -1092,6 +1423,26 @@ test.describe('react-start hmr', () => { await expectComponentHmrStatePreserved(page) }) + test('updates a code-split route component whose function name is lowercase', async ({ + page, + }) => { + await seedComponentHmrState(page, '/component-hmr-lowercase-named-split') + + await replaceRouteTextAndWait( + page, + 'componentHmrLowercaseNamedSplit', + 'component-hmr-lowercase-named-split-baseline', + 'component-hmr-lowercase-named-split-updated', + async () => { + await hmrExpect(page.getByTestId('component-hmr-marker')).toHaveText( + 'component-hmr-lowercase-named-split-updated', + ) + }, + ) + + await expectComponentHmrStatePreserved(page) + }) + test('updates non-root route component during HMR when component is not defined inline and codeSplitGroupings disables code splitting', async ({ page, }) => { diff --git a/e2e/react-start/hmr/tests/setup/global.setup.ts b/e2e/react-start/hmr/tests/setup/global.setup.ts index fb9aad22ae..32207ab79f 100644 --- a/e2e/react-start/hmr/tests/setup/global.setup.ts +++ b/e2e/react-start/hmr/tests/setup/global.setup.ts @@ -1,22 +1,7 @@ -import { - e2eStartDummyServer, - getTestServerPort, - preOptimizeDevServer, - waitForServer, -} from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -function getE2EPortKey() { - const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' - return process.env.E2E_PORT_KEY ?? `${packageJson.name}-${toolchain}` -} +import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' export default async function setup() { - const e2ePortKey = getE2EPortKey() - - await e2eStartDummyServer(e2ePortKey) - - const port = await getTestServerPort(e2ePortKey) + const port = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${port}` await waitForServer(baseURL) diff --git a/e2e/react-start/hmr/tests/setup/global.teardown.ts b/e2e/react-start/hmr/tests/setup/global.teardown.ts deleted file mode 100644 index e17856dd82..0000000000 --- a/e2e/react-start/hmr/tests/setup/global.teardown.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -function getE2EPortKey() { - const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' - return process.env.E2E_PORT_KEY ?? `${packageJson.name}-${toolchain}` -} - -export default async function teardown() { - await e2eStopDummyServer(getE2EPortKey()) -} diff --git a/e2e/react-start/i18n-paraglide/package.json b/e2e/react-start/i18n-paraglide/package.json index 39e5d3e137..ca65ead76d 100644 --- a/e2e/react-start/i18n-paraglide/package.json +++ b/e2e/react-start/i18n-paraglide/package.json @@ -8,7 +8,7 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js", "build": "vite build && tsc --noEmit", "preview": "vite preview", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -27,7 +27,26 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" + }, + "nx": { + "targets": { + "build": { + "outputs": [ + "...", + "{projectRoot}/src/paraglide", + "{projectRoot}/project.inlang/cache" + ] + }, + "test:e2e": { + "outputs": [ + "...", + "{projectRoot}/src/paraglide", + "{projectRoot}/project.inlang/cache" + ] + } + } } } diff --git a/e2e/react-start/i18n-paraglide/playwright.config.ts b/e2e/react-start/i18n-paraglide/playwright.config.ts index 38690f09d8..972522350e 100644 --- a/e2e/react-start/i18n-paraglide/playwright.config.ts +++ b/e2e/react-start/i18n-paraglide/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-start/i18n-paraglide/src/routeTree.gen.ts b/e2e/react-start/i18n-paraglide/src/routeTree.gen.ts index 421daf2790..d89758e684 100644 --- a/e2e/react-start/i18n-paraglide/src/routeTree.gen.ts +++ b/e2e/react-start/i18n-paraglide/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/e2e/react-start/import-protection-custom-config/package.json b/e2e/react-start/import-protection-custom-config/package.json index ff0e9e7bdf..c088eff106 100644 --- a/e2e/react-start/import-protection-custom-config/package.json +++ b/e2e/react-start/import-protection-custom-config/package.json @@ -8,8 +8,8 @@ "dev:e2e": "vite dev", "build": "vite build && tsc --noEmit", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e:mockMode": "rm -rf port*.txt; playwright test --project=chromium", - "test:e2e:errorMode": "rm -rf port*.txt; BEHAVIOR=error playwright test --project=chromium", + "test:e2e:mockMode": "playwright test --project=chromium", + "test:e2e:errorMode": "BEHAVIOR=error playwright test --project=chromium", "test:e2e": "pnpm run test:e2e:mockMode && pnpm run test:e2e:errorMode" }, "dependencies": { @@ -25,8 +25,23 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^0.11.9", - "typescript": "^6.0.2", + "srvx": "^1.0.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" + }, + "nx": { + "targets": { + "test:e2e": { + "outputs": [ + "{projectRoot}/dist", + "{projectRoot}/test-results", + "{projectRoot}/webserver-build.log", + "{projectRoot}/violations.*.json", + "{projectRoot}/error-build.log", + "{projectRoot}/error-*-result.json" + ] + } + } } } diff --git a/e2e/react-start/import-protection-custom-config/playwright.config.ts b/e2e/react-start/import-protection-custom-config/playwright.config.ts index 31a55ba3bc..ab90f2911f 100644 --- a/e2e/react-start/import-protection-custom-config/playwright.config.ts +++ b/e2e/react-start/import-protection-custom-config/playwright.config.ts @@ -1,9 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' +import { appServerReady } from '@tanstack/router-e2e-utils' import { isErrorMode } from './tests/utils/isErrorMode' -import packageJson from './package.json' with { type: 'json' } -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` console.log('running in error mode:', isErrorMode.toString()) @@ -27,8 +26,8 @@ export default defineConfig({ : { webServer: { command: `rm -f webserver-build.log violations.build.json violations.dev.json && VITE_SERVER_PORT=${PORT} pnpm build > webserver-build.log 2>&1 && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', cwd: import.meta.dirname, }, diff --git a/e2e/react-start/import-protection-custom-config/src/routeTree.gen.ts b/e2e/react-start/import-protection-custom-config/src/routeTree.gen.ts index 44861559e3..6a2acc53ef 100644 --- a/e2e/react-start/import-protection-custom-config/src/routeTree.gen.ts +++ b/e2e/react-start/import-protection-custom-config/src/routeTree.gen.ts @@ -9,13 +9,13 @@ // 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 FrontendLeakRouteImport } from './routes/frontend-leak' -import { Route as BackendLeakRouteImport } from './routes/backend-leak' import { Route as IndexRouteImport } from './routes/index' +import { Route as BackendLeakRouteImport } from './routes/backend-leak' +import { Route as FrontendLeakRouteImport } from './routes/frontend-leak' -const FrontendLeakRoute = FrontendLeakRouteImport.update({ - id: '/frontend-leak', - path: '/frontend-leak', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const BackendLeakRoute = BackendLeakRouteImport.update({ @@ -23,9 +23,9 @@ const BackendLeakRoute = BackendLeakRouteImport.update({ path: '/backend-leak', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const FrontendLeakRoute = FrontendLeakRouteImport.update({ + id: '/frontend-leak', + path: '/frontend-leak', getParentRoute: () => rootRouteImport, } as any) @@ -61,11 +61,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/frontend-leak': { - id: '/frontend-leak' - path: '/frontend-leak' - fullPath: '/frontend-leak' - preLoaderRoute: typeof FrontendLeakRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/backend-leak': { @@ -75,11 +75,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof BackendLeakRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/frontend-leak': { + id: '/frontend-leak' + path: '/frontend-leak' + fullPath: '/frontend-leak' + preLoaderRoute: typeof FrontendLeakRouteImport parentRoute: typeof rootRouteImport } } diff --git a/e2e/react-start/import-protection-custom-config/tests/error-mode.setup.ts b/e2e/react-start/import-protection-custom-config/tests/error-mode.setup.ts index 3e666ca1df..5032988d0c 100644 --- a/e2e/react-start/import-protection-custom-config/tests/error-mode.setup.ts +++ b/e2e/react-start/import-protection-custom-config/tests/error-mode.setup.ts @@ -1,14 +1,14 @@ +import { execSync, spawn } from 'node:child_process' import fs from 'node:fs' import path from 'node:path' -import { execSync, spawn } from 'node:child_process' -import { chromium } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from '../package.json' with { type: 'json' } +import { stripVTControlCharacters } from 'node:util' +import { appServerReadyPattern } from '@tanstack/router-e2e-utils' +import { chromium, expect } from '@playwright/test' import type { FullConfig } from '@playwright/test' async function waitForHttpOk(url: string, timeoutMs: number): Promise { const start = Date.now() - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + while (true) { if (Date.now() - start > timeoutMs) { throw new Error(`Timed out waiting for ${url}`) @@ -84,8 +84,7 @@ function captureBuild(cwd: string): void { } async function captureDevErrors(cwd: string): Promise { - const port = await getTestServerPort(`${packageJson.name}_error_dev`) - const baseURL = `http://localhost:${port}` + const port = 0 const logChunks: Array = [] const child = spawn('pnpm', ['exec', 'vite', 'dev', '--port', String(port)], { @@ -99,10 +98,23 @@ async function captureDevErrors(cwd: string): Promise { stdio: ['ignore', 'pipe', 'pipe'], }) - child.stdout?.on('data', (d: Buffer) => logChunks.push(d.toString())) - child.stderr?.on('data', (d: Buffer) => logChunks.push(d.toString())) + child.stdout.on('data', (d: Buffer) => logChunks.push(d.toString())) + child.stderr.on('data', (d: Buffer) => logChunks.push(d.toString())) try { + await expect + .poll( + () => + appServerReadyPattern.exec( + stripVTControlCharacters(logChunks.join('')), + )?.groups?.E2E_APP_PORT, + { timeout: 30_000 }, + ) + .toBeTruthy() + const port = appServerReadyPattern.exec( + stripVTControlCharacters(logChunks.join('')), + )!.groups!.E2E_APP_PORT + const baseURL = `http://localhost:${port}` await waitForHttpOk(baseURL, 30_000) const browser = await chromium.launch() diff --git a/e2e/react-start/import-protection-custom-config/tests/violations.setup.ts b/e2e/react-start/import-protection-custom-config/tests/violations.setup.ts index c5187fe074..89c8bb2b9a 100644 --- a/e2e/react-start/import-protection-custom-config/tests/violations.setup.ts +++ b/e2e/react-start/import-protection-custom-config/tests/violations.setup.ts @@ -1,9 +1,9 @@ +import { spawn } from 'node:child_process' import fs from 'node:fs' import path from 'node:path' -import { spawn } from 'node:child_process' -import { chromium } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from '../package.json' with { type: 'json' } +import { stripVTControlCharacters } from 'node:util' +import { chromium, expect } from '@playwright/test' +import { appServerReadyPattern } from '@tanstack/router-e2e-utils' import { extractViolationsFromLog } from './violations.utils' import type { FullConfig } from '@playwright/test' @@ -12,7 +12,6 @@ import type { Violation } from './violations.utils' async function waitForHttpOk(url: string, timeoutMs: number): Promise { const start = Date.now() - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (true) { if (Date.now() - start > timeoutMs) { throw new Error(`Timed out waiting for ${url}`) @@ -119,7 +118,6 @@ async function runDevPass( cwd: string, port: number, ): Promise> { - const baseURL = `http://localhost:${port}` const logChunks: Array = [] const child = startDevServer(cwd, port) @@ -127,6 +125,19 @@ async function runDevPass( child.stderr?.on('data', (d: Buffer) => logChunks.push(d.toString())) try { + await expect + .poll( + () => + appServerReadyPattern.exec( + stripVTControlCharacters(logChunks.join('')), + )?.groups?.E2E_APP_PORT, + { timeout: 30_000 }, + ) + .toBeTruthy() + const port = appServerReadyPattern.exec( + stripVTControlCharacters(logChunks.join('')), + )!.groups!.E2E_APP_PORT + const baseURL = `http://localhost:${port}` await waitForHttpOk(baseURL, 30_000) const browser = await chromium.launch() @@ -146,7 +157,7 @@ async function runDevPass( } async function captureDevViolations(cwd: string): Promise { - const port = await getTestServerPort(`${packageJson.name}_dev`) + const port = 0 const coldViolations = await runDevPass(cwd, port) diff --git a/e2e/react-start/import-protection/package.json b/e2e/react-start/import-protection/package.json index 0efd1c2048..ad06ba41ea 100644 --- a/e2e/react-start/import-protection/package.json +++ b/e2e/react-start/import-protection/package.json @@ -11,10 +11,7 @@ "build": "pnpm build:vite", "build:vite": "vite build && tsc --noEmit", "build:rsbuild": "rsbuild build && tsc --noEmit", - "start": "node server.js", - "test:e2e:mockMode": "rm -rf node_modules/.vite; rm -rf port*.txt; playwright test --project=chromium", - "test:e2e:errorMode": "rm -rf node_modules/.vite; rm -rf port*.txt; BEHAVIOR=error playwright test --project=chromium", - "test:e2e": "pnpm run test:e2e:mockMode && pnpm run test:e2e:errorMode" + "start": "node server.js" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -25,15 +22,16 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.0.11", + "@rsbuild/core": "^2.3.1", "@rsbuild/plugin-react": "^2.0.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^0.11.9", - "typescript": "^6.0.2", + "srvx": "^1.0.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" }, "nx": { @@ -57,6 +55,7 @@ "toolchain": "vite", "mode": "ssr", "env": { + "E2E_BUILD_LOG": "webserver-build.vite-ssr.log", "E2E_VITE_BUNDLED_DEV": "false" } }, @@ -65,12 +64,16 @@ "mode": "ssr", "name": "bundled-dev", "env": { + "E2E_BUILD_LOG": "webserver-build.vite-ssr-bundled-dev.log", "E2E_VITE_BUNDLED_DEV": "true" } }, { "toolchain": "rsbuild", - "mode": "ssr" + "mode": "ssr", + "env": { + "E2E_BUILD_LOG": "webserver-build.rsbuild-ssr.log" + } } ] } diff --git a/e2e/react-start/import-protection/playwright.config.ts b/e2e/react-start/import-protection/playwright.config.ts index ac239f36fe..6a3df630c3 100644 --- a/e2e/react-start/import-protection/playwright.config.ts +++ b/e2e/react-start/import-protection/playwright.config.ts @@ -1,18 +1,19 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' +import { appServerReady } from '@tanstack/router-e2e-utils' import { isErrorMode } from './tests/utils/isErrorMode' -import packageJson from './package.json' with { type: 'json' } +import { getViolationArtifactName } from './tests/violations.utils' -const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' const viteBundledDev = process.env.E2E_VITE_BUNDLED_DEV === 'true' -const e2ePortKey = - process.env.E2E_PORT_KEY ?? - `${packageJson.name}-${toolchain}${viteBundledDev ? '-bundled-dev' : ''}` + const distDir = process.env.E2E_DIST_DIR ?? 'dist' -const PORT = await getTestServerPort(e2ePortKey) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` -const buildCommand = - toolchain === 'rsbuild' ? 'pnpm build:rsbuild' : 'pnpm build:vite' +const violationArtifacts = [ + getViolationArtifactName('build'), + getViolationArtifactName('dev'), + getViolationArtifactName('dev.cold'), + getViolationArtifactName('dev.warm'), +].join(' ') console.log('running in error mode:', isErrorMode.toString()) @@ -36,16 +37,15 @@ export default defineConfig({ ? {} : { webServer: { - command: `rm -f webserver-build.log webserver-dev.log violations.build.json violations.dev.json && VITE_SERVER_PORT=${PORT} PORT=${PORT} ${buildCommand} > webserver-build.log 2>&1 && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `rm -f webserver-dev.log ${violationArtifacts} && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', cwd: import.meta.dirname, env: { PORT: String(PORT), VITE_SERVER_PORT: String(PORT), E2E_DIST_DIR: distDir, - E2E_PORT_KEY: e2ePortKey, E2E_VITE_BUNDLED_DEV: String(viteBundledDev), }, }, diff --git a/e2e/react-start/import-protection/src/routes/index.tsx b/e2e/react-start/import-protection/src/routes/index.tsx index c05ed1a7e3..ef8544dc3c 100644 --- a/e2e/react-start/import-protection/src/routes/index.tsx +++ b/e2e/react-start/import-protection/src/routes/index.tsx @@ -1,4 +1,4 @@ -import { createFileRoute } from '@tanstack/react-router' +import { createFileRoute, useHydrated } from '@tanstack/react-router' // This import chain triggers a file-based violation in the CLIENT env: // index.tsx -> violations/edge-a.ts -> violations/secret.server.ts import { getWrappedSecret } from '../violations/edge-a' @@ -25,10 +25,12 @@ export const Route = createFileRoute('/')({ }) function Home() { + const hydrated = useHydrated() return (

Import Protection E2E

App loaded successfully with mock mode

+

{hydrated ? 'hydrated' : 'ssr'}

{getWrappedSecret()}

{getWrappedSecret1()}

{getServerOnlyDataViaEdge()}

diff --git a/e2e/react-start/import-protection/src/routes/issue-7725.tsx b/e2e/react-start/import-protection/src/routes/issue-7725.tsx new file mode 100644 index 0000000000..ef0152dd13 --- /dev/null +++ b/e2e/react-start/import-protection/src/routes/issue-7725.tsx @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/react-router' +import { issue7725ServerFnFactory } from '../violations/issue-7725-server-fn-factory' + +const getIssue7725Data = issue7725ServerFnFactory.handler(async () => { + return 'issue 7725 server function' +}) + +export const Route = createFileRoute('/issue-7725')({ + loader: () => getIssue7725Data(), + component: Issue7725, +}) + +function Issue7725() { + return

Issue 7725

+} diff --git a/e2e/react-start/import-protection/src/violations/cross-boundary-safe/session-util.ts b/e2e/react-start/import-protection/src/violations/cross-boundary-safe/session-util.ts index ab44237539..d74bc6430b 100644 --- a/e2e/react-start/import-protection/src/violations/cross-boundary-safe/session-util.ts +++ b/e2e/react-start/import-protection/src/violations/cross-boundary-safe/session-util.ts @@ -6,7 +6,7 @@ import { getRequest } from '@tanstack/react-start/server' // so the compiler should prune this import from the client bundle. // // This mirrors the real-world pattern of a session utility that wraps -// `useSession` from `@tanstack/react-start/server`. +// `getCookie` from `@tanstack/react-start/server`. export function getSessionData() { const req = getRequest() return { method: req.method } diff --git a/e2e/react-start/import-protection/src/violations/issue-7725-server-fn-factory.ts b/e2e/react-start/import-protection/src/violations/issue-7725-server-fn-factory.ts new file mode 100644 index 0000000000..45be765b1b --- /dev/null +++ b/e2e/react-start/import-protection/src/violations/issue-7725-server-fn-factory.ts @@ -0,0 +1,3 @@ +import { createServerFn } from '@tanstack/react-start' + +export const issue7725ServerFnFactory = createServerFn() diff --git a/e2e/react-start/import-protection/tests/error-mode.setup.ts b/e2e/react-start/import-protection/tests/error-mode.setup.ts index c844d59e73..e562128eea 100644 --- a/e2e/react-start/import-protection/tests/error-mode.setup.ts +++ b/e2e/react-start/import-protection/tests/error-mode.setup.ts @@ -1,9 +1,9 @@ +import { execSync, spawn } from 'node:child_process' import fs from 'node:fs' import path from 'node:path' -import { execSync, spawn } from 'node:child_process' -import { chromium } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from '../package.json' with { type: 'json' } +import { stripVTControlCharacters } from 'node:util' +import { appServerReadyPattern } from '@tanstack/router-e2e-utils' +import { chromium, expect } from '@playwright/test' import type { FullConfig } from '@playwright/test' /** @@ -20,14 +20,10 @@ import type { FullConfig } from '@playwright/test' */ const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' -const viteBundledDev = process.env.E2E_VITE_BUNDLED_DEV === 'true' -const e2ePortKey = - process.env.E2E_PORT_KEY ?? - `${packageJson.name}-${toolchain}${viteBundledDev ? '-bundled-dev' : ''}` async function waitForHttpOk(url: string, timeoutMs: number): Promise { const start = Date.now() - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + while (true) { if (Date.now() - start > timeoutMs) { throw new Error(`Timed out waiting for ${url}`) @@ -122,8 +118,7 @@ async function captureDev(cwd: string): Promise { if (fs.existsSync(p)) fs.unlinkSync(p) } - const port = await getTestServerPort(`${e2ePortKey}-error-dev`) - const baseURL = `http://localhost:${port}` + const port = 0 const logFile = path.resolve(cwd, 'error-dev.log') const out = fs.createWriteStream(logFile) @@ -145,10 +140,28 @@ async function captureDev(cwd: string): Promise { stdio: ['ignore', 'pipe', 'pipe'], }) - child.stdout?.on('data', (d: Buffer) => out.write(d)) - child.stderr?.on('data', (d: Buffer) => out.write(d)) + const logChunks: Array = [] + const record = (data: Buffer) => { + logChunks.push(data.toString()) + out.write(data) + } + child.stdout.on('data', record) + child.stderr.on('data', record) try { + await expect + .poll( + () => + appServerReadyPattern.exec( + stripVTControlCharacters(logChunks.join('')), + )?.groups?.E2E_APP_PORT, + { timeout: 30_000 }, + ) + .toBeTruthy() + const port = appServerReadyPattern.exec( + stripVTControlCharacters(logChunks.join('')), + )!.groups!.E2E_APP_PORT + const baseURL = `http://localhost:${port}` await waitForHttpOk(baseURL, 30_000) const browser = await chromium.launch() diff --git a/e2e/react-start/import-protection/tests/import-protection.spec.ts b/e2e/react-start/import-protection/tests/import-protection.spec.ts index cdc9aea32c..16b5b073eb 100644 --- a/e2e/react-start/import-protection/tests/import-protection.spec.ts +++ b/e2e/react-start/import-protection/tests/import-protection.spec.ts @@ -2,6 +2,7 @@ import path from 'node:path' import fs from 'node:fs' import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' +import { getViolationArtifactName } from './violations.utils' import type { Violation } from './violations.utils' import type { Page } from '@playwright/test' @@ -37,7 +38,7 @@ function normalizeKeyPath(value: string): string { async function readViolations( type: 'build' | 'dev' | 'dev.cold' | 'dev.warm', ): Promise> { - const filename = `violations.${type}.json` + const filename = getViolationArtifactName(type) const violationsPath = path.resolve(import.meta.dirname, '..', filename) const mod = await import(violationsPath, { with: { type: 'json' }, @@ -161,7 +162,8 @@ test('client-only violations route loads in mock mode', async ({ page }) => { }) for (const mode of ['build', 'dev'] as const) { - test(`violations.${mode}.json is written during ${mode}`, async () => { + const artifactName = getViolationArtifactName(mode) + test(`${artifactName} is written during ${mode}`, async () => { const violations = await readViolations(mode) expect(violations.length).toBeGreaterThan(0) }) @@ -204,7 +206,7 @@ test('build log does not contain mock-edge missing export warnings', () => { const buildLogPath = path.resolve( import.meta.dirname, '..', - 'webserver-build.log', + process.env.E2E_BUILD_LOG ?? 'webserver-build.log', ) if (!fs.existsSync(buildLogPath)) { diff --git a/e2e/react-start/import-protection/tests/violations.setup.ts b/e2e/react-start/import-protection/tests/violations.setup.ts index 02796227a7..d0f4f70d03 100644 --- a/e2e/react-start/import-protection/tests/violations.setup.ts +++ b/e2e/react-start/import-protection/tests/violations.setup.ts @@ -1,24 +1,22 @@ +import { spawn } from 'node:child_process' import fs from 'node:fs' import path from 'node:path' -import { spawn } from 'node:child_process' -import { chromium } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from '../package.json' with { type: 'json' } +import { stripVTControlCharacters } from 'node:util' +import { chromium, expect } from '@playwright/test' +import { appServerReadyPattern } from '@tanstack/router-e2e-utils' -import { extractViolationsFromLog } from './violations.utils' +import { + extractViolationsFromLog, + getViolationArtifactName, +} from './violations.utils' import type { FullConfig } from '@playwright/test' import type { Violation } from './violations.utils' -const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' const viteBundledDev = process.env.E2E_VITE_BUNDLED_DEV === 'true' -const e2ePortKey = - process.env.E2E_PORT_KEY ?? - `${packageJson.name}-${toolchain}${viteBundledDev ? '-bundled-dev' : ''}` async function waitForHttpOk(url: string, timeoutMs: number): Promise { const start = Date.now() - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition while (true) { if (Date.now() - start > timeoutMs) { throw new Error(`Timed out waiting for ${url}`) @@ -174,6 +172,20 @@ async function navigateAllRoutes( const context = await browser.newContext() const page = await context.newPage() + // Safe factory imports must actually compile and hydrate. A crashed lazy + // compiler must not pass simply because it emitted no violation diagnostics. + await page.goto(baseURL) + await expect(page.getByTestId('hydration-status')).toHaveText('hydrated', { + timeout: 30_000, + }) + for (const testId of [ + 'factory-safe', + 'cross-boundary-safe-sf', + 'cross-boundary-safe-mw', + ]) { + await expect(page.getByTestId(testId)).toHaveText('function') + } + for (const [route, testId, expectedViolation] of routeDefinitions) { try { // Prefer 'networkidle' (ensures route chunks are actually fetched), but @@ -211,7 +223,6 @@ async function runDevPass( cwd: string, port: number, ): Promise> { - const baseURL = `http://localhost:${port}` const logChunks: Array = [] const child = startDevServer(cwd, port) @@ -219,6 +230,19 @@ async function runDevPass( child.stderr?.on('data', (d: Buffer) => logChunks.push(d.toString())) try { + await expect + .poll( + () => + appServerReadyPattern.exec( + stripVTControlCharacters(logChunks.join('')), + )?.groups?.E2E_APP_PORT, + { timeout: 30_000 }, + ) + .toBeTruthy() + const port = appServerReadyPattern.exec( + stripVTControlCharacters(logChunks.join('')), + )!.groups!.E2E_APP_PORT + const baseURL = `http://localhost:${port}` await waitForHttpOk(baseURL, 30_000) const browser = await chromium.launch() @@ -244,28 +268,22 @@ async function runDevPass( * modules are pre-transformed so resolveId/transform paths differ. */ async function captureDevViolations(cwd: string): Promise { - const coldViolations = await runDevPass( - cwd, - await getTestServerPort(`${e2ePortKey}-violations-cold`), - ) + const coldViolations = await runDevPass(cwd, 0) fs.writeFileSync( - path.resolve(cwd, 'violations.dev.json'), + path.resolve(cwd, getViolationArtifactName('dev')), JSON.stringify(coldViolations, null, 2), ) fs.writeFileSync( - path.resolve(cwd, 'violations.dev.cold.json'), + path.resolve(cwd, getViolationArtifactName('dev.cold')), JSON.stringify(coldViolations, null, 2), ) // Warm pass: the .vite cache from the cold run is still on disk. - const warmViolations = await runDevPass( - cwd, - await getTestServerPort(`${e2ePortKey}-violations-warm`), - ) + const warmViolations = await runDevPass(cwd, 0) fs.writeFileSync( - path.resolve(cwd, 'violations.dev.warm.json'), + path.resolve(cwd, getViolationArtifactName('dev.warm')), JSON.stringify(warmViolations, null, 2), ) } @@ -275,19 +293,22 @@ export default async function globalSetup(config: FullConfig) { // This file lives in ./tests; fixture root is one directory up. const cwd = path.resolve(import.meta.dirname, '..') - // webServer.command writes build output to this file. - const logFile = path.resolve(cwd, 'webserver-build.log') + // The Nx build dependency writes build output to this file. + const logFile = path.resolve( + cwd, + process.env.E2E_BUILD_LOG ?? 'webserver-build.log', + ) if (!fs.existsSync(logFile)) { // If the log doesn't exist, leave an empty violations file. - fs.writeFileSync(path.resolve(cwd, 'violations.build.json'), '[]') + fs.writeFileSync(path.resolve(cwd, getViolationArtifactName('build')), '[]') return } const text = fs.readFileSync(logFile, 'utf-8') const violations = extractViolationsFromLog(text) fs.writeFileSync( - path.resolve(cwd, 'violations.build.json'), + path.resolve(cwd, getViolationArtifactName('build')), JSON.stringify(violations, null, 2), ) diff --git a/e2e/react-start/import-protection/tests/violations.utils.ts b/e2e/react-start/import-protection/tests/violations.utils.ts index c08a9b7a82..006c51543b 100644 --- a/e2e/react-start/import-protection/tests/violations.utils.ts +++ b/e2e/react-start/import-protection/tests/violations.utils.ts @@ -21,6 +21,15 @@ export type Violation = { message?: string } +export type ViolationArtifact = 'build' | 'dev' | 'dev.cold' | 'dev.warm' + +export function getViolationArtifactName(artifact: ViolationArtifact): string { + const modeKey = process.env.E2E_MODE_KEY + return modeKey + ? `violations.${modeKey}.${artifact}.json` + : `violations.${artifact}.json` +} + export function stripAnsi(input: string): string { // eslint-disable-next-line no-control-regex return input.replace(/\u001b\[[0-9;]*m/g, '') diff --git a/e2e/react-start/import-protection/vite.config.ts b/e2e/react-start/import-protection/vite.config.ts index 3163ded433..6a17f3a7cd 100644 --- a/e2e/react-start/import-protection/vite.config.ts +++ b/e2e/react-start/import-protection/vite.config.ts @@ -8,20 +8,43 @@ const outDir = process.env.E2E_DIST_DIR ?? 'dist' const startModeConfig = getStartModeConfig() const bundledDev = process.env.E2E_VITE_BUNDLED_DEV === 'true' -export default defineConfig({ - resolve: { tsconfigPaths: true }, - experimental: bundledDev ? { bundledDev: true } : undefined, - build: { - outDir, - }, - server: { - port: 3000, - }, - plugins: [tanstackStart(startModeConfig), viteReact()], - // react-tweet's package.json exports resolve to `index.client.js` which - // matches the default **/*.client.* deny pattern. Bundling it via - // noExternal must NOT trigger a false-positive import-protection violation. - ssr: { - noExternal: ['react-tweet'], - }, +const ISSUE_7725_DENIED_SPECIFIER = '../violations/issue-7725-server-fn-factory' + +export default defineConfig(({ command }) => { + const importProtection = + command === 'build' + ? { + ...startModeConfig.importProtection, + client: { + // Reproduce build-only issue #7725: resolving this imported + // server-fn builder must load import protection's mock virtual + // module, including its leading null-byte ID. + specifiers: [ISSUE_7725_DENIED_SPECIFIER], + }, + } + : startModeConfig.importProtection + + return { + resolve: { tsconfigPaths: true }, + experimental: bundledDev ? { bundledDev: true } : undefined, + build: { + outDir, + }, + server: { + port: 3000, + }, + plugins: [ + tanstackStart({ + ...startModeConfig, + importProtection, + }), + viteReact(), + ], + // react-tweet's package.json exports resolve to `index.client.js` which + // matches the default **/*.client.* deny pattern. Bundling it via + // noExternal must NOT trigger a false-positive import-protection violation. + ssr: { + noExternal: ['react-tweet'], + }, + } }) diff --git a/e2e/react-start/issue-8049/package.json b/e2e/react-start/issue-8049/package.json new file mode 100644 index 0000000000..be848d434c --- /dev/null +++ b/e2e/react-start/issue-8049/package.json @@ -0,0 +1,25 @@ +{ + "name": "tanstack-react-start-e2e-issue-8049", + "private": true, + "type": "module", + "scripts": { + "build": "vite build && tsc --noEmit", + "dev": "vite dev --port 3000", + "dev:e2e": "vite dev", + "test:e2e": "playwright test --project=chromium" + }, + "dependencies": { + "@tanstack/react-router": "workspace:^", + "@tanstack/react-start": "workspace:^", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@playwright/test": "^1.61.0", + "@tanstack/router-e2e-utils": "workspace:^", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^6.0.1", + "vite": "^8.0.14" + } +} diff --git a/e2e/react-start/issue-8049/playwright.config.ts b/e2e/react-start/issue-8049/playwright.config.ts new file mode 100644 index 0000000000..46bfbe552e --- /dev/null +++ b/e2e/react-start/issue-8049/playwright.config.ts @@ -0,0 +1,25 @@ +import { defineConfig, devices } from '@playwright/test' +import { appServerReady } from '@tanstack/router-e2e-utils' + +const PORT = + Number(process.env.VITE_SERVER_PORT) || Number(process.env.E2E_APP_PORT ?? 0) +const baseURL = `http://localhost:${PORT}` + +export default defineConfig({ + testDir: './tests', + workers: 1, + reporter: [['line']], + use: { baseURL }, + webServer: { + command: `VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/react-start/issue-8049/src/routeTree.gen.ts b/e2e/react-start/issue-8049/src/routeTree.gen.ts new file mode 100644 index 0000000000..9f42873a9b --- /dev/null +++ b/e2e/react-start/issue-8049/src/routeTree.gen.ts @@ -0,0 +1,86 @@ +/* eslint-disable */ + +// @ts-nocheck + +// 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 TestRouteImport } from './routes/test' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const TestRoute = TestRouteImport.update({ + id: '/test', + path: '/test', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/test': typeof TestRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/test': typeof TestRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/test': typeof TestRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/test' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/test' + id: '__root__' | '/' | '/test' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + TestRoute: typeof TestRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/test': { + id: '/test' + path: '/test' + fullPath: '/test' + preLoaderRoute: typeof TestRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + TestRoute: TestRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { createStart } from '@tanstack/react-start' +declare module '@tanstack/react-start' { + interface Register { + ssr: true + router: Awaited> + } +} diff --git a/e2e/react-start/issue-8049/src/router.tsx b/e2e/react-start/issue-8049/src/router.tsx new file mode 100644 index 0000000000..db215b280b --- /dev/null +++ b/e2e/react-start/issue-8049/src/router.tsx @@ -0,0 +1,19 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + defaultPreload: 'intent', + defaultPreloadStaleTime: 0, + defaultPendingMs: 0, + defaultPendingMinMs: 0, + defaultPendingComponent: () =>
Pending
, + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/e2e/react-start/issue-8049/src/routes/__root.tsx b/e2e/react-start/issue-8049/src/routes/__root.tsx new file mode 100644 index 0000000000..d04f508640 --- /dev/null +++ b/e2e/react-start/issue-8049/src/routes/__root.tsx @@ -0,0 +1,37 @@ +import { + HeadContent, + Link, + Scripts, + createRootRoute, +} from '@tanstack/react-router' +import type { ReactNode } from 'react' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + ], + }), + shellComponent: RootDocument, +}) + +function RootDocument({ children }: { children: ReactNode }) { + return ( + + + + + +
+ + {children} +
+ + + + ) +} diff --git a/e2e/react-start/issue-8049/src/routes/index.tsx b/e2e/react-start/issue-8049/src/routes/index.tsx new file mode 100644 index 0000000000..be54bce8de --- /dev/null +++ b/e2e/react-start/issue-8049/src/routes/index.tsx @@ -0,0 +1,5 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: () =>
Home Page
, +}) diff --git a/e2e/react-start/issue-8049/src/routes/test.tsx b/e2e/react-start/issue-8049/src/routes/test.tsx new file mode 100644 index 0000000000..cca03da69f --- /dev/null +++ b/e2e/react-start/issue-8049/src/routes/test.tsx @@ -0,0 +1,5 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/test')({ + component: () =>
Test Page
, +}) diff --git a/e2e/react-start/issue-8049/tests/issue-8049.spec.ts b/e2e/react-start/issue-8049/tests/issue-8049.spec.ts new file mode 100644 index 0000000000..2560267109 --- /dev/null +++ b/e2e/react-start/issue-8049/tests/issue-8049.spec.ts @@ -0,0 +1,75 @@ +import { expect, test } from '@playwright/test' + +test('#8049: revisiting loaded split routes transitions without pending or blank paint', async ({ + page, +}) => { + await page.addInitScript(() => { + const scope = globalThis as typeof globalThis & { + __paintStates: Array + __recordPaintStates: boolean + } + scope.__paintStates = [] + scope.__recordPaintStates = false + + function recordPaintState() { + if (scope.__recordPaintStates) { + const state = document.querySelector('[data-state="home"]') + ? 'home' + : document.querySelector('[data-state="test"]') + ? 'test' + : document.querySelector('[data-state="pending"]') + ? 'pending' + : document.querySelector('[data-state="shell"]') + ? 'shell' + : 'empty' + scope.__paintStates.push(state) + } + requestAnimationFrame(recordPaintState) + } + + requestAnimationFrame(recordPaintState) + }) + await page.goto('/') + await expect(page.getByText('Home Page')).toBeVisible() + await page.waitForTimeout(1_000) + + await page.getByRole('link', { name: 'Test' }).click() + await expect(page.getByText('Test Page')).toBeVisible() + await page.getByRole('link', { name: 'Home' }).click() + await expect(page.getByText('Home Page')).toBeVisible() + + await page.evaluate( + () => + new Promise((resolve) => { + const scope = globalThis as typeof globalThis & { + __paintStates: Array + __recordPaintStates: boolean + } + scope.__paintStates = [] + scope.__recordPaintStates = true + requestAnimationFrame(() => resolve()) + }), + ) + + await page.getByRole('link', { name: 'Test' }).click() + await expect(page.getByText('Test Page')).toBeVisible() + const paintStates = await page.evaluate( + () => + new Promise>((resolve) => { + requestAnimationFrame(() => { + const scope = globalThis as typeof globalThis & { + __paintStates: Array + __recordPaintStates: boolean + } + scope.__recordPaintStates = false + resolve(scope.__paintStates) + }) + }), + ) + + expect(paintStates[0]).toBe('home') + expect(paintStates).toContain('test') + expect(paintStates).not.toContain('pending') + expect(paintStates).not.toContain('shell') + expect(paintStates).not.toContain('empty') +}) diff --git a/e2e/react-start/issue-8049/tsconfig.json b/e2e/react-start/issue-8049/tsconfig.json new file mode 100644 index 0000000000..0a82952b9a --- /dev/null +++ b/e2e/react-start/issue-8049/tsconfig.json @@ -0,0 +1,13 @@ +{ + "include": ["**/*.ts", "**/*.tsx"], + "compilerOptions": { + "strict": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "resolveJsonModule": true, + "skipLibCheck": true, + "noEmit": true + } +} diff --git a/e2e/react-start/issue-8049/vite.config.ts b/e2e/react-start/issue-8049/vite.config.ts new file mode 100644 index 0000000000..f13cf79861 --- /dev/null +++ b/e2e/react-start/issue-8049/vite.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'vite' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' + +export default defineConfig({ + plugins: [tanstackStart(), viteReact()], +}) diff --git a/e2e/react-start/query-integration/package.json b/e2e/react-start/query-integration/package.json index a2a325f9c8..694289ccc2 100644 --- a/e2e/react-start/query-integration/package.json +++ b/e2e/react-start/query-integration/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/react-query": "^5.90.0", @@ -32,7 +32,8 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/e2e/react-start/query-integration/playwright.config.ts b/e2e/react-start/query-integration/playwright.config.ts index 4d86a1dbe7..82678ac00b 100644 --- a/e2e/react-start/query-integration/playwright.config.ts +++ b/e2e/react-start/query-integration/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { derivePort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await derivePort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/react-start/query-integration/src/routeTree.gen.ts b/e2e/react-start/query-integration/src/routeTree.gen.ts index 22c6f3293d..ee7ef43f26 100644 --- a/e2e/react-start/query-integration/src/routeTree.gen.ts +++ b/e2e/react-start/query-integration/src/routeTree.gen.ts @@ -9,14 +9,14 @@ // 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 UseSuspenseQueryRouteImport } from './routes/useSuspenseQuery' -import { Route as UseQueryRouteImport } from './routes/useQuery' import { Route as IndexRouteImport } from './routes/index' +import { Route as UseQueryRouteImport } from './routes/useQuery' +import { Route as UseSuspenseQueryRouteImport } from './routes/useSuspenseQuery' import { Route as LoaderFetchQueryTypeRouteImport } from './routes/loader-fetchQuery/$type' -const UseSuspenseQueryRoute = UseSuspenseQueryRouteImport.update({ - id: '/useSuspenseQuery', - path: '/useSuspenseQuery', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const UseQueryRoute = UseQueryRouteImport.update({ @@ -24,9 +24,9 @@ const UseQueryRoute = UseQueryRouteImport.update({ path: '/useQuery', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const UseSuspenseQueryRoute = UseSuspenseQueryRouteImport.update({ + id: '/useSuspenseQuery', + path: '/useSuspenseQuery', getParentRoute: () => rootRouteImport, } as any) const LoaderFetchQueryTypeRoute = LoaderFetchQueryTypeRouteImport.update({ @@ -80,11 +80,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/useSuspenseQuery': { - id: '/useSuspenseQuery' - path: '/useSuspenseQuery' - fullPath: '/useSuspenseQuery' - preLoaderRoute: typeof UseSuspenseQueryRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/useQuery': { @@ -94,11 +94,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof UseQueryRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/useSuspenseQuery': { + id: '/useSuspenseQuery' + path: '/useSuspenseQuery' + fullPath: '/useSuspenseQuery' + preLoaderRoute: typeof UseSuspenseQueryRouteImport parentRoute: typeof rootRouteImport } '/loader-fetchQuery/$type': { diff --git a/e2e/react-start/response-reconciliation/.gitignore b/e2e/react-start/response-reconciliation/.gitignore new file mode 100644 index 0000000000..16187ac1de --- /dev/null +++ b/e2e/react-start/response-reconciliation/.gitignore @@ -0,0 +1,24 @@ +node_modules +package-lock.json +yarn.lock + +.DS_Store +.cache +.tanstack +.env +.vercel +.output +/build/ +/api/ +/server/build +/public/build + +# Sentry Config File +.env.sentry-build-plugin +/test-results/ +/playwright-report/ +/blob-report/ +/playwright/.cache/ +/dist/ +/dist-*/ +/port-*.txt diff --git a/e2e/react-start/response-reconciliation/.prettierignore b/e2e/react-start/response-reconciliation/.prettierignore new file mode 100644 index 0000000000..40a96e8819 --- /dev/null +++ b/e2e/react-start/response-reconciliation/.prettierignore @@ -0,0 +1,4 @@ +**/build +**/public +pnpm-lock.yaml +routeTree.gen.ts diff --git a/e2e/react-start/response-reconciliation/package.json b/e2e/react-start/response-reconciliation/package.json new file mode 100644 index 0000000000..7ba0224962 --- /dev/null +++ b/e2e/react-start/response-reconciliation/package.json @@ -0,0 +1,84 @@ +{ + "name": "tanstack-react-start-e2e-response-reconciliation", + "private": true, + "sideEffects": false, + "type": "module", + "scripts": { + "dev": "pnpm dev:vite --port 3000", + "dev:e2e": "pnpm dev:vite", + "dev:vite": "vite dev", + "dev:rsbuild": "rsbuild dev", + "build": "pnpm build:vite", + "build:vite": "vite build && tsc --noEmit", + "build:rsbuild": "rsbuild build && tsc --noEmit", + "preview": "vite preview", + "start": "node server.js", + "test:e2e:local": "pnpm build && playwright test --project=chromium" + }, + "dependencies": { + "@tanstack/react-router": "workspace:*", + "@tanstack/react-start": "workspace:*", + "react": "^19.2.3", + "react-dom": "^19.2.3" + }, + "devDependencies": { + "@playwright/test": "^1.57.0", + "@rsbuild/core": "^2.3.1", + "@rsbuild/plugin-react": "^2.0.0", + "@tanstack/router-e2e-utils": "workspace:^", + "@types/node": "25.0.9", + "@types/react": "^19.2.8", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^6.0.1", + "srvx": "^1.0.0", + "typescript": "^6.0.2", + "vite": "^8.0.14" + }, + "nx": { + "targets": { + "test:e2e": { + "parallelism": false + }, + "test:e2e--vite-ssr": { + "parallelism": false + }, + "test:e2e--vite-ssr--custom-entry": { + "parallelism": false + }, + "test:e2e--rsbuild-ssr": { + "parallelism": false + }, + "test:e2e--rsbuild-ssr--custom-entry": { + "parallelism": false + } + }, + "metadata": { + "playwrightModes": [ + { + "toolchain": "vite", + "mode": "ssr" + }, + { + "toolchain": "vite", + "mode": "ssr", + "name": "custom-entry", + "env": { + "TSS_E2E_SERVER_ENTRY": "server-entry" + } + }, + { + "toolchain": "rsbuild", + "mode": "ssr" + }, + { + "toolchain": "rsbuild", + "mode": "ssr", + "name": "custom-entry", + "env": { + "TSS_E2E_SERVER_ENTRY": "server-entry" + } + } + ] + } + } +} diff --git a/e2e/react-start/response-reconciliation/playwright.config.ts b/e2e/react-start/response-reconciliation/playwright.config.ts new file mode 100644 index 0000000000..d4c9c58f43 --- /dev/null +++ b/e2e/react-start/response-reconciliation/playwright.config.ts @@ -0,0 +1,37 @@ +import { defineConfig, devices } from '@playwright/test' +import { appServerReady } from '@tanstack/router-e2e-utils' + +const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' +const distDir = process.env.E2E_DIST_DIR ?? 'dist' +const serverEntry = process.env.TSS_E2E_SERVER_ENTRY ?? '' + +export const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const baseURL = `http://localhost:${PORT}` + +export default defineConfig({ + testDir: './tests', + workers: 1, + reporter: [['line']], + use: { + baseURL, + }, + webServer: { + command: `pnpm start`, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + env: { + PORT: String(PORT), + VITE_SERVER_PORT: String(PORT), + E2E_DIST_DIR: distDir, + E2E_TOOLCHAIN: toolchain, + TSS_E2E_SERVER_ENTRY: serverEntry, + }, + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/react-start/response-reconciliation/rsbuild.config.ts b/e2e/react-start/response-reconciliation/rsbuild.config.ts new file mode 100644 index 0000000000..38f44ef9fb --- /dev/null +++ b/e2e/react-start/response-reconciliation/rsbuild.config.ts @@ -0,0 +1,20 @@ +import { defineConfig } from '@rsbuild/core' +import { pluginReact } from '@rsbuild/plugin-react' +import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' + +const serverEntry = process.env.TSS_E2E_SERVER_ENTRY +const outDir = process.env.E2E_DIST_DIR ?? 'dist' + +export default defineConfig({ + plugins: [ + pluginReact(), + tanstackStart({ + server: serverEntry ? { entry: serverEntry } : undefined, + }), + ], + output: { + distPath: { + root: outDir, + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/server.js b/e2e/react-start/response-reconciliation/server.js new file mode 100644 index 0000000000..324a462bec --- /dev/null +++ b/e2e/react-start/response-reconciliation/server.js @@ -0,0 +1,62 @@ +import fs from 'node:fs' +import path from 'node:path' +import { spawn } from 'node:child_process' +import { pathToFileURL } from 'node:url' + +const distDir = process.env.E2E_DIST_DIR || 'dist' + +function resolveDistClientDir() { + return path.resolve(distDir, 'client') +} + +function resolveDistServerEntryPath() { + if (process.env.TSS_E2E_SERVER_ENTRY) { + const customEntryPath = path.resolve( + distDir, + 'server', + `${process.env.TSS_E2E_SERVER_ENTRY}.js`, + ) + if (fs.existsSync(customEntryPath)) { + return customEntryPath + } + } + + const serverJsPath = path.resolve(distDir, 'server', 'server.js') + if (fs.existsSync(serverJsPath)) { + return serverJsPath + } + + const indexJsPath = path.resolve(distDir, 'server', 'index.js') + if (fs.existsSync(indexJsPath)) { + return indexJsPath + } + + return serverJsPath +} + +export function start() { + const child = spawn( + 'srvx', + ['--prod', '-s', resolveDistClientDir(), resolveDistServerEntryPath()], + { + stdio: 'inherit', + shell: process.platform === 'win32', + }, + ) + + child.on('exit', (code, signal) => { + if (signal) { + process.kill(process.pid, signal) + return + } + + process.exit(code ?? 0) + }) +} + +if ( + process.argv[1] && + import.meta.url === pathToFileURL(process.argv[1]).href +) { + start() +} diff --git a/e2e/react-start/response-reconciliation/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/response-reconciliation/src/components/DefaultCatchBoundary.tsx new file mode 100644 index 0000000000..f3d691814f --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/components/DefaultCatchBoundary.tsx @@ -0,0 +1,20 @@ +import { ErrorComponent, Link, useRouter } from '@tanstack/react-router' +import type { ErrorComponentProps } from '@tanstack/react-router' + +export function DefaultCatchBoundary({ error }: ErrorComponentProps) { + const router = useRouter() + + return ( +
+ + + Home +
+ ) +} diff --git a/e2e/react-start/response-reconciliation/src/components/NotFound.tsx b/e2e/react-start/response-reconciliation/src/components/NotFound.tsx new file mode 100644 index 0000000000..0b720f0e37 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/components/NotFound.tsx @@ -0,0 +1,10 @@ +import { Link } from '@tanstack/react-router' + +export function NotFound({ children }: { children?: React.ReactNode }) { + return ( +
+ {children ||

The page you are looking for does not exist.

} + Start Over +
+ ) +} diff --git a/e2e/react-start/response-reconciliation/src/response-wrapper.ts b/e2e/react-start/response-reconciliation/src/response-wrapper.ts new file mode 100644 index 0000000000..db9733d5e6 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/response-wrapper.ts @@ -0,0 +1,33 @@ +import { getRequestHeader } from '@tanstack/react-start/server' + +let installed = false + +/** + * Stand-in for libraries that wrap the global Response and pipe stream bodies, + * such as varlock's leak prevention: afterwards `new Response(stream).body` is + * a new stream that reads `stream`. Only requests that send + * `x-wrap-response: true` are affected. + */ +export function installResponseWrapper() { + if (installed) { + return + } + installed = true + globalThis.Response = new Proxy(globalThis.Response, { + construct(target, [body, init], newTarget) { + if (body instanceof ReadableStream && wrapsResponses()) { + body = body.pipeThrough(new TransformStream()) + } + return Reflect.construct(target, [body, init], newTarget) + }, + }) +} + +function wrapsResponses() { + try { + return getRequestHeader('x-wrap-response') === 'true' + } catch { + // Responses created outside a request are never wrapped. + return false + } +} diff --git a/e2e/react-start/response-reconciliation/src/routeTree.gen.ts b/e2e/react-start/response-reconciliation/src/routeTree.gen.ts new file mode 100644 index 0000000000..3dbb6301c3 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routeTree.gen.ts @@ -0,0 +1,625 @@ +/* eslint-disable */ + +// @ts-nocheck + +// 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 ServerFunctionsRouteImport } from './routes/server-functions' +import { Route as SsrRouteImport } from './routes/ssr' +import { Route as StreamedRouteImport } from './routes/streamed' +import { Route as ApiBaseRouteImport } from './routes/api/base' +import { Route as ApiBulkHeadersRouteImport } from './routes/api/bulk-headers' +import { Route as ApiClearReturnedHeadersRouteImport } from './routes/api/clear-returned-headers' +import { Route as ApiDirectMutationVisibleRouteImport } from './routes/api/direct-mutation-visible' +import { Route as ApiExplicitSetCookieHeaderRouteImport } from './routes/api/explicit-set-cookie-header' +import { Route as ApiFramingErrorRouteImport } from './routes/api/framing-error' +import { Route as ApiGetResponseHeaderHelperRouteImport } from './routes/api/get-response-header-helper' +import { Route as ApiGetResponseHeadersHelperRouteImport } from './routes/api/get-response-headers-helper' +import { Route as ApiMultipleCookiesRouteImport } from './routes/api/multiple-cookies' +import { Route as ApiNullBodyStatusRouteImport } from './routes/api/null-body-status' +import { Route as ApiReadonlyAfterNextRouteImport } from './routes/api/readonly-after-next' +import { Route as ApiRedirectWithCookiesRouteImport } from './routes/api/redirect-with-cookies' +import { Route as ApiRemoveReturnedHeaderRouteImport } from './routes/api/remove-returned-header' +import { Route as ApiReplaceAfterDirectMutationRouteImport } from './routes/api/replace-after-direct-mutation' +import { Route as ApiReplaceExplicitSetCookieRouteImport } from './routes/api/replace-explicit-set-cookie' +import { Route as ApiRouteAfterNextRouteImport } from './routes/api/route-after-next' +import { Route as ApiRouteBeforeNextRouteImport } from './routes/api/route-before-next' +import { Route as ApiSameBoundaryConflictRouteImport } from './routes/api/same-boundary-conflict' +import { Route as ApiStatusContractsRouteImport } from './routes/api/status-contracts' +import { Route as ApiThrowAfterStatusRouteImport } from './routes/api/throw-after-status' +import { Route as ApiTrackedStreamRouteImport } from './routes/api/tracked-stream' +import { Route as ApiTrackedStreamStatusRouteImport } from './routes/api/tracked-stream-status' +import { Route as ApiTwoReturnedResponsesRouteImport } from './routes/api/two-returned-responses' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ServerFunctionsRoute = ServerFunctionsRouteImport.update({ + id: '/server-functions', + path: '/server-functions', + getParentRoute: () => rootRouteImport, +} as any) +const SsrRoute = SsrRouteImport.update({ + id: '/ssr', + path: '/ssr', + getParentRoute: () => rootRouteImport, +} as any) +const StreamedRoute = StreamedRouteImport.update({ + id: '/streamed', + path: '/streamed', + getParentRoute: () => rootRouteImport, +} as any) +const ApiBaseRoute = ApiBaseRouteImport.update({ + id: '/api/base', + path: '/api/base', + getParentRoute: () => rootRouteImport, +} as any) +const ApiBulkHeadersRoute = ApiBulkHeadersRouteImport.update({ + id: '/api/bulk-headers', + path: '/api/bulk-headers', + getParentRoute: () => rootRouteImport, +} as any) +const ApiClearReturnedHeadersRoute = ApiClearReturnedHeadersRouteImport.update({ + id: '/api/clear-returned-headers', + path: '/api/clear-returned-headers', + getParentRoute: () => rootRouteImport, +} as any) +const ApiDirectMutationVisibleRoute = + ApiDirectMutationVisibleRouteImport.update({ + id: '/api/direct-mutation-visible', + path: '/api/direct-mutation-visible', + getParentRoute: () => rootRouteImport, + } as any) +const ApiExplicitSetCookieHeaderRoute = + ApiExplicitSetCookieHeaderRouteImport.update({ + id: '/api/explicit-set-cookie-header', + path: '/api/explicit-set-cookie-header', + getParentRoute: () => rootRouteImport, + } as any) +const ApiFramingErrorRoute = ApiFramingErrorRouteImport.update({ + id: '/api/framing-error', + path: '/api/framing-error', + getParentRoute: () => rootRouteImport, +} as any) +const ApiGetResponseHeaderHelperRoute = + ApiGetResponseHeaderHelperRouteImport.update({ + id: '/api/get-response-header-helper', + path: '/api/get-response-header-helper', + getParentRoute: () => rootRouteImport, + } as any) +const ApiGetResponseHeadersHelperRoute = + ApiGetResponseHeadersHelperRouteImport.update({ + id: '/api/get-response-headers-helper', + path: '/api/get-response-headers-helper', + getParentRoute: () => rootRouteImport, + } as any) +const ApiMultipleCookiesRoute = ApiMultipleCookiesRouteImport.update({ + id: '/api/multiple-cookies', + path: '/api/multiple-cookies', + getParentRoute: () => rootRouteImport, +} as any) +const ApiNullBodyStatusRoute = ApiNullBodyStatusRouteImport.update({ + id: '/api/null-body-status', + path: '/api/null-body-status', + getParentRoute: () => rootRouteImport, +} as any) +const ApiReadonlyAfterNextRoute = ApiReadonlyAfterNextRouteImport.update({ + id: '/api/readonly-after-next', + path: '/api/readonly-after-next', + getParentRoute: () => rootRouteImport, +} as any) +const ApiRedirectWithCookiesRoute = ApiRedirectWithCookiesRouteImport.update({ + id: '/api/redirect-with-cookies', + path: '/api/redirect-with-cookies', + getParentRoute: () => rootRouteImport, +} as any) +const ApiRemoveReturnedHeaderRoute = ApiRemoveReturnedHeaderRouteImport.update({ + id: '/api/remove-returned-header', + path: '/api/remove-returned-header', + getParentRoute: () => rootRouteImport, +} as any) +const ApiReplaceAfterDirectMutationRoute = + ApiReplaceAfterDirectMutationRouteImport.update({ + id: '/api/replace-after-direct-mutation', + path: '/api/replace-after-direct-mutation', + getParentRoute: () => rootRouteImport, + } as any) +const ApiReplaceExplicitSetCookieRoute = + ApiReplaceExplicitSetCookieRouteImport.update({ + id: '/api/replace-explicit-set-cookie', + path: '/api/replace-explicit-set-cookie', + getParentRoute: () => rootRouteImport, + } as any) +const ApiRouteAfterNextRoute = ApiRouteAfterNextRouteImport.update({ + id: '/api/route-after-next', + path: '/api/route-after-next', + getParentRoute: () => rootRouteImport, +} as any) +const ApiRouteBeforeNextRoute = ApiRouteBeforeNextRouteImport.update({ + id: '/api/route-before-next', + path: '/api/route-before-next', + getParentRoute: () => rootRouteImport, +} as any) +const ApiSameBoundaryConflictRoute = ApiSameBoundaryConflictRouteImport.update({ + id: '/api/same-boundary-conflict', + path: '/api/same-boundary-conflict', + getParentRoute: () => rootRouteImport, +} as any) +const ApiStatusContractsRoute = ApiStatusContractsRouteImport.update({ + id: '/api/status-contracts', + path: '/api/status-contracts', + getParentRoute: () => rootRouteImport, +} as any) +const ApiThrowAfterStatusRoute = ApiThrowAfterStatusRouteImport.update({ + id: '/api/throw-after-status', + path: '/api/throw-after-status', + getParentRoute: () => rootRouteImport, +} as any) +const ApiTrackedStreamRoute = ApiTrackedStreamRouteImport.update({ + id: '/api/tracked-stream', + path: '/api/tracked-stream', + getParentRoute: () => rootRouteImport, +} as any) +const ApiTrackedStreamStatusRoute = ApiTrackedStreamStatusRouteImport.update({ + id: '/api/tracked-stream-status', + path: '/api/tracked-stream-status', + getParentRoute: () => rootRouteImport, +} as any) +const ApiTwoReturnedResponsesRoute = ApiTwoReturnedResponsesRouteImport.update({ + id: '/api/two-returned-responses', + path: '/api/two-returned-responses', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/server-functions': typeof ServerFunctionsRoute + '/ssr': typeof SsrRoute + '/streamed': typeof StreamedRoute + '/api/base': typeof ApiBaseRoute + '/api/bulk-headers': typeof ApiBulkHeadersRoute + '/api/clear-returned-headers': typeof ApiClearReturnedHeadersRoute + '/api/direct-mutation-visible': typeof ApiDirectMutationVisibleRoute + '/api/explicit-set-cookie-header': typeof ApiExplicitSetCookieHeaderRoute + '/api/framing-error': typeof ApiFramingErrorRoute + '/api/get-response-header-helper': typeof ApiGetResponseHeaderHelperRoute + '/api/get-response-headers-helper': typeof ApiGetResponseHeadersHelperRoute + '/api/multiple-cookies': typeof ApiMultipleCookiesRoute + '/api/null-body-status': typeof ApiNullBodyStatusRoute + '/api/readonly-after-next': typeof ApiReadonlyAfterNextRoute + '/api/redirect-with-cookies': typeof ApiRedirectWithCookiesRoute + '/api/remove-returned-header': typeof ApiRemoveReturnedHeaderRoute + '/api/replace-after-direct-mutation': typeof ApiReplaceAfterDirectMutationRoute + '/api/replace-explicit-set-cookie': typeof ApiReplaceExplicitSetCookieRoute + '/api/route-after-next': typeof ApiRouteAfterNextRoute + '/api/route-before-next': typeof ApiRouteBeforeNextRoute + '/api/same-boundary-conflict': typeof ApiSameBoundaryConflictRoute + '/api/status-contracts': typeof ApiStatusContractsRoute + '/api/throw-after-status': typeof ApiThrowAfterStatusRoute + '/api/tracked-stream': typeof ApiTrackedStreamRoute + '/api/tracked-stream-status': typeof ApiTrackedStreamStatusRoute + '/api/two-returned-responses': typeof ApiTwoReturnedResponsesRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/server-functions': typeof ServerFunctionsRoute + '/ssr': typeof SsrRoute + '/streamed': typeof StreamedRoute + '/api/base': typeof ApiBaseRoute + '/api/bulk-headers': typeof ApiBulkHeadersRoute + '/api/clear-returned-headers': typeof ApiClearReturnedHeadersRoute + '/api/direct-mutation-visible': typeof ApiDirectMutationVisibleRoute + '/api/explicit-set-cookie-header': typeof ApiExplicitSetCookieHeaderRoute + '/api/framing-error': typeof ApiFramingErrorRoute + '/api/get-response-header-helper': typeof ApiGetResponseHeaderHelperRoute + '/api/get-response-headers-helper': typeof ApiGetResponseHeadersHelperRoute + '/api/multiple-cookies': typeof ApiMultipleCookiesRoute + '/api/null-body-status': typeof ApiNullBodyStatusRoute + '/api/readonly-after-next': typeof ApiReadonlyAfterNextRoute + '/api/redirect-with-cookies': typeof ApiRedirectWithCookiesRoute + '/api/remove-returned-header': typeof ApiRemoveReturnedHeaderRoute + '/api/replace-after-direct-mutation': typeof ApiReplaceAfterDirectMutationRoute + '/api/replace-explicit-set-cookie': typeof ApiReplaceExplicitSetCookieRoute + '/api/route-after-next': typeof ApiRouteAfterNextRoute + '/api/route-before-next': typeof ApiRouteBeforeNextRoute + '/api/same-boundary-conflict': typeof ApiSameBoundaryConflictRoute + '/api/status-contracts': typeof ApiStatusContractsRoute + '/api/throw-after-status': typeof ApiThrowAfterStatusRoute + '/api/tracked-stream': typeof ApiTrackedStreamRoute + '/api/tracked-stream-status': typeof ApiTrackedStreamStatusRoute + '/api/two-returned-responses': typeof ApiTwoReturnedResponsesRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/server-functions': typeof ServerFunctionsRoute + '/ssr': typeof SsrRoute + '/streamed': typeof StreamedRoute + '/api/base': typeof ApiBaseRoute + '/api/bulk-headers': typeof ApiBulkHeadersRoute + '/api/clear-returned-headers': typeof ApiClearReturnedHeadersRoute + '/api/direct-mutation-visible': typeof ApiDirectMutationVisibleRoute + '/api/explicit-set-cookie-header': typeof ApiExplicitSetCookieHeaderRoute + '/api/framing-error': typeof ApiFramingErrorRoute + '/api/get-response-header-helper': typeof ApiGetResponseHeaderHelperRoute + '/api/get-response-headers-helper': typeof ApiGetResponseHeadersHelperRoute + '/api/multiple-cookies': typeof ApiMultipleCookiesRoute + '/api/null-body-status': typeof ApiNullBodyStatusRoute + '/api/readonly-after-next': typeof ApiReadonlyAfterNextRoute + '/api/redirect-with-cookies': typeof ApiRedirectWithCookiesRoute + '/api/remove-returned-header': typeof ApiRemoveReturnedHeaderRoute + '/api/replace-after-direct-mutation': typeof ApiReplaceAfterDirectMutationRoute + '/api/replace-explicit-set-cookie': typeof ApiReplaceExplicitSetCookieRoute + '/api/route-after-next': typeof ApiRouteAfterNextRoute + '/api/route-before-next': typeof ApiRouteBeforeNextRoute + '/api/same-boundary-conflict': typeof ApiSameBoundaryConflictRoute + '/api/status-contracts': typeof ApiStatusContractsRoute + '/api/throw-after-status': typeof ApiThrowAfterStatusRoute + '/api/tracked-stream': typeof ApiTrackedStreamRoute + '/api/tracked-stream-status': typeof ApiTrackedStreamStatusRoute + '/api/two-returned-responses': typeof ApiTwoReturnedResponsesRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/server-functions' + | '/ssr' + | '/streamed' + | '/api/base' + | '/api/bulk-headers' + | '/api/clear-returned-headers' + | '/api/direct-mutation-visible' + | '/api/explicit-set-cookie-header' + | '/api/framing-error' + | '/api/get-response-header-helper' + | '/api/get-response-headers-helper' + | '/api/multiple-cookies' + | '/api/null-body-status' + | '/api/readonly-after-next' + | '/api/redirect-with-cookies' + | '/api/remove-returned-header' + | '/api/replace-after-direct-mutation' + | '/api/replace-explicit-set-cookie' + | '/api/route-after-next' + | '/api/route-before-next' + | '/api/same-boundary-conflict' + | '/api/status-contracts' + | '/api/throw-after-status' + | '/api/tracked-stream' + | '/api/tracked-stream-status' + | '/api/two-returned-responses' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/server-functions' + | '/ssr' + | '/streamed' + | '/api/base' + | '/api/bulk-headers' + | '/api/clear-returned-headers' + | '/api/direct-mutation-visible' + | '/api/explicit-set-cookie-header' + | '/api/framing-error' + | '/api/get-response-header-helper' + | '/api/get-response-headers-helper' + | '/api/multiple-cookies' + | '/api/null-body-status' + | '/api/readonly-after-next' + | '/api/redirect-with-cookies' + | '/api/remove-returned-header' + | '/api/replace-after-direct-mutation' + | '/api/replace-explicit-set-cookie' + | '/api/route-after-next' + | '/api/route-before-next' + | '/api/same-boundary-conflict' + | '/api/status-contracts' + | '/api/throw-after-status' + | '/api/tracked-stream' + | '/api/tracked-stream-status' + | '/api/two-returned-responses' + id: + | '__root__' + | '/' + | '/server-functions' + | '/ssr' + | '/streamed' + | '/api/base' + | '/api/bulk-headers' + | '/api/clear-returned-headers' + | '/api/direct-mutation-visible' + | '/api/explicit-set-cookie-header' + | '/api/framing-error' + | '/api/get-response-header-helper' + | '/api/get-response-headers-helper' + | '/api/multiple-cookies' + | '/api/null-body-status' + | '/api/readonly-after-next' + | '/api/redirect-with-cookies' + | '/api/remove-returned-header' + | '/api/replace-after-direct-mutation' + | '/api/replace-explicit-set-cookie' + | '/api/route-after-next' + | '/api/route-before-next' + | '/api/same-boundary-conflict' + | '/api/status-contracts' + | '/api/throw-after-status' + | '/api/tracked-stream' + | '/api/tracked-stream-status' + | '/api/two-returned-responses' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ServerFunctionsRoute: typeof ServerFunctionsRoute + SsrRoute: typeof SsrRoute + StreamedRoute: typeof StreamedRoute + ApiBaseRoute: typeof ApiBaseRoute + ApiBulkHeadersRoute: typeof ApiBulkHeadersRoute + ApiClearReturnedHeadersRoute: typeof ApiClearReturnedHeadersRoute + ApiDirectMutationVisibleRoute: typeof ApiDirectMutationVisibleRoute + ApiExplicitSetCookieHeaderRoute: typeof ApiExplicitSetCookieHeaderRoute + ApiFramingErrorRoute: typeof ApiFramingErrorRoute + ApiGetResponseHeaderHelperRoute: typeof ApiGetResponseHeaderHelperRoute + ApiGetResponseHeadersHelperRoute: typeof ApiGetResponseHeadersHelperRoute + ApiMultipleCookiesRoute: typeof ApiMultipleCookiesRoute + ApiNullBodyStatusRoute: typeof ApiNullBodyStatusRoute + ApiReadonlyAfterNextRoute: typeof ApiReadonlyAfterNextRoute + ApiRedirectWithCookiesRoute: typeof ApiRedirectWithCookiesRoute + ApiRemoveReturnedHeaderRoute: typeof ApiRemoveReturnedHeaderRoute + ApiReplaceAfterDirectMutationRoute: typeof ApiReplaceAfterDirectMutationRoute + ApiReplaceExplicitSetCookieRoute: typeof ApiReplaceExplicitSetCookieRoute + ApiRouteAfterNextRoute: typeof ApiRouteAfterNextRoute + ApiRouteBeforeNextRoute: typeof ApiRouteBeforeNextRoute + ApiSameBoundaryConflictRoute: typeof ApiSameBoundaryConflictRoute + ApiStatusContractsRoute: typeof ApiStatusContractsRoute + ApiThrowAfterStatusRoute: typeof ApiThrowAfterStatusRoute + ApiTrackedStreamRoute: typeof ApiTrackedStreamRoute + ApiTrackedStreamStatusRoute: typeof ApiTrackedStreamStatusRoute + ApiTwoReturnedResponsesRoute: typeof ApiTwoReturnedResponsesRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/server-functions': { + id: '/server-functions' + path: '/server-functions' + fullPath: '/server-functions' + preLoaderRoute: typeof ServerFunctionsRouteImport + parentRoute: typeof rootRouteImport + } + '/ssr': { + id: '/ssr' + path: '/ssr' + fullPath: '/ssr' + preLoaderRoute: typeof SsrRouteImport + parentRoute: typeof rootRouteImport + } + '/streamed': { + id: '/streamed' + path: '/streamed' + fullPath: '/streamed' + preLoaderRoute: typeof StreamedRouteImport + parentRoute: typeof rootRouteImport + } + '/api/base': { + id: '/api/base' + path: '/api/base' + fullPath: '/api/base' + preLoaderRoute: typeof ApiBaseRouteImport + parentRoute: typeof rootRouteImport + } + '/api/bulk-headers': { + id: '/api/bulk-headers' + path: '/api/bulk-headers' + fullPath: '/api/bulk-headers' + preLoaderRoute: typeof ApiBulkHeadersRouteImport + parentRoute: typeof rootRouteImport + } + '/api/clear-returned-headers': { + id: '/api/clear-returned-headers' + path: '/api/clear-returned-headers' + fullPath: '/api/clear-returned-headers' + preLoaderRoute: typeof ApiClearReturnedHeadersRouteImport + parentRoute: typeof rootRouteImport + } + '/api/direct-mutation-visible': { + id: '/api/direct-mutation-visible' + path: '/api/direct-mutation-visible' + fullPath: '/api/direct-mutation-visible' + preLoaderRoute: typeof ApiDirectMutationVisibleRouteImport + parentRoute: typeof rootRouteImport + } + '/api/explicit-set-cookie-header': { + id: '/api/explicit-set-cookie-header' + path: '/api/explicit-set-cookie-header' + fullPath: '/api/explicit-set-cookie-header' + preLoaderRoute: typeof ApiExplicitSetCookieHeaderRouteImport + parentRoute: typeof rootRouteImport + } + '/api/framing-error': { + id: '/api/framing-error' + path: '/api/framing-error' + fullPath: '/api/framing-error' + preLoaderRoute: typeof ApiFramingErrorRouteImport + parentRoute: typeof rootRouteImport + } + '/api/get-response-header-helper': { + id: '/api/get-response-header-helper' + path: '/api/get-response-header-helper' + fullPath: '/api/get-response-header-helper' + preLoaderRoute: typeof ApiGetResponseHeaderHelperRouteImport + parentRoute: typeof rootRouteImport + } + '/api/get-response-headers-helper': { + id: '/api/get-response-headers-helper' + path: '/api/get-response-headers-helper' + fullPath: '/api/get-response-headers-helper' + preLoaderRoute: typeof ApiGetResponseHeadersHelperRouteImport + parentRoute: typeof rootRouteImport + } + '/api/multiple-cookies': { + id: '/api/multiple-cookies' + path: '/api/multiple-cookies' + fullPath: '/api/multiple-cookies' + preLoaderRoute: typeof ApiMultipleCookiesRouteImport + parentRoute: typeof rootRouteImport + } + '/api/null-body-status': { + id: '/api/null-body-status' + path: '/api/null-body-status' + fullPath: '/api/null-body-status' + preLoaderRoute: typeof ApiNullBodyStatusRouteImport + parentRoute: typeof rootRouteImport + } + '/api/readonly-after-next': { + id: '/api/readonly-after-next' + path: '/api/readonly-after-next' + fullPath: '/api/readonly-after-next' + preLoaderRoute: typeof ApiReadonlyAfterNextRouteImport + parentRoute: typeof rootRouteImport + } + '/api/redirect-with-cookies': { + id: '/api/redirect-with-cookies' + path: '/api/redirect-with-cookies' + fullPath: '/api/redirect-with-cookies' + preLoaderRoute: typeof ApiRedirectWithCookiesRouteImport + parentRoute: typeof rootRouteImport + } + '/api/remove-returned-header': { + id: '/api/remove-returned-header' + path: '/api/remove-returned-header' + fullPath: '/api/remove-returned-header' + preLoaderRoute: typeof ApiRemoveReturnedHeaderRouteImport + parentRoute: typeof rootRouteImport + } + '/api/replace-after-direct-mutation': { + id: '/api/replace-after-direct-mutation' + path: '/api/replace-after-direct-mutation' + fullPath: '/api/replace-after-direct-mutation' + preLoaderRoute: typeof ApiReplaceAfterDirectMutationRouteImport + parentRoute: typeof rootRouteImport + } + '/api/replace-explicit-set-cookie': { + id: '/api/replace-explicit-set-cookie' + path: '/api/replace-explicit-set-cookie' + fullPath: '/api/replace-explicit-set-cookie' + preLoaderRoute: typeof ApiReplaceExplicitSetCookieRouteImport + parentRoute: typeof rootRouteImport + } + '/api/route-after-next': { + id: '/api/route-after-next' + path: '/api/route-after-next' + fullPath: '/api/route-after-next' + preLoaderRoute: typeof ApiRouteAfterNextRouteImport + parentRoute: typeof rootRouteImport + } + '/api/route-before-next': { + id: '/api/route-before-next' + path: '/api/route-before-next' + fullPath: '/api/route-before-next' + preLoaderRoute: typeof ApiRouteBeforeNextRouteImport + parentRoute: typeof rootRouteImport + } + '/api/same-boundary-conflict': { + id: '/api/same-boundary-conflict' + path: '/api/same-boundary-conflict' + fullPath: '/api/same-boundary-conflict' + preLoaderRoute: typeof ApiSameBoundaryConflictRouteImport + parentRoute: typeof rootRouteImport + } + '/api/status-contracts': { + id: '/api/status-contracts' + path: '/api/status-contracts' + fullPath: '/api/status-contracts' + preLoaderRoute: typeof ApiStatusContractsRouteImport + parentRoute: typeof rootRouteImport + } + '/api/throw-after-status': { + id: '/api/throw-after-status' + path: '/api/throw-after-status' + fullPath: '/api/throw-after-status' + preLoaderRoute: typeof ApiThrowAfterStatusRouteImport + parentRoute: typeof rootRouteImport + } + '/api/tracked-stream': { + id: '/api/tracked-stream' + path: '/api/tracked-stream' + fullPath: '/api/tracked-stream' + preLoaderRoute: typeof ApiTrackedStreamRouteImport + parentRoute: typeof rootRouteImport + } + '/api/tracked-stream-status': { + id: '/api/tracked-stream-status' + path: '/api/tracked-stream-status' + fullPath: '/api/tracked-stream-status' + preLoaderRoute: typeof ApiTrackedStreamStatusRouteImport + parentRoute: typeof rootRouteImport + } + '/api/two-returned-responses': { + id: '/api/two-returned-responses' + path: '/api/two-returned-responses' + fullPath: '/api/two-returned-responses' + preLoaderRoute: typeof ApiTwoReturnedResponsesRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ServerFunctionsRoute: ServerFunctionsRoute, + SsrRoute: SsrRoute, + StreamedRoute: StreamedRoute, + ApiBaseRoute: ApiBaseRoute, + ApiBulkHeadersRoute: ApiBulkHeadersRoute, + ApiClearReturnedHeadersRoute: ApiClearReturnedHeadersRoute, + ApiDirectMutationVisibleRoute: ApiDirectMutationVisibleRoute, + ApiExplicitSetCookieHeaderRoute: ApiExplicitSetCookieHeaderRoute, + ApiFramingErrorRoute: ApiFramingErrorRoute, + ApiGetResponseHeaderHelperRoute: ApiGetResponseHeaderHelperRoute, + ApiGetResponseHeadersHelperRoute: ApiGetResponseHeadersHelperRoute, + ApiMultipleCookiesRoute: ApiMultipleCookiesRoute, + ApiNullBodyStatusRoute: ApiNullBodyStatusRoute, + ApiReadonlyAfterNextRoute: ApiReadonlyAfterNextRoute, + ApiRedirectWithCookiesRoute: ApiRedirectWithCookiesRoute, + ApiRemoveReturnedHeaderRoute: ApiRemoveReturnedHeaderRoute, + ApiReplaceAfterDirectMutationRoute: ApiReplaceAfterDirectMutationRoute, + ApiReplaceExplicitSetCookieRoute: ApiReplaceExplicitSetCookieRoute, + ApiRouteAfterNextRoute: ApiRouteAfterNextRoute, + ApiRouteBeforeNextRoute: ApiRouteBeforeNextRoute, + ApiSameBoundaryConflictRoute: ApiSameBoundaryConflictRoute, + ApiStatusContractsRoute: ApiStatusContractsRoute, + ApiThrowAfterStatusRoute: ApiThrowAfterStatusRoute, + ApiTrackedStreamRoute: ApiTrackedStreamRoute, + ApiTrackedStreamStatusRoute: ApiTrackedStreamStatusRoute, + ApiTwoReturnedResponsesRoute: ApiTwoReturnedResponsesRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +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> + } +} diff --git a/e2e/react-start/response-reconciliation/src/router.tsx b/e2e/react-start/response-reconciliation/src/router.tsx new file mode 100644 index 0000000000..c5c2209e5a --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/router.tsx @@ -0,0 +1,13 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' +import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' +import { NotFound } from './components/NotFound' + +export function getRouter() { + return createRouter({ + routeTree, + defaultErrorComponent: DefaultCatchBoundary, + defaultNotFoundComponent: () => , + scrollRestoration: true, + }) +} diff --git a/e2e/react-start/response-reconciliation/src/routes/__root.tsx b/e2e/react-start/response-reconciliation/src/routes/__root.tsx new file mode 100644 index 0000000000..a562991887 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/__root.tsx @@ -0,0 +1,57 @@ +/// +import * as React from 'react' +import { + HeadContent, + Link, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' +import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' +import { NotFound } from '~/components/NotFound' +import '~/styles/app.css' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + ], + }), + errorComponent: (props) => { + return ( + + + + ) + }, + notFoundComponent: () => , + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + ) +} + +function RootDocument({ children }: { children: React.ReactNode }) { + return ( + + + + + + + {children} + + + + ) +} diff --git a/e2e/react-start/response-reconciliation/src/routes/api/-response.ts b/e2e/react-start/response-reconciliation/src/routes/api/-response.ts new file mode 100644 index 0000000000..54082c10f6 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/-response.ts @@ -0,0 +1,85 @@ +import { createMiddleware } from '@tanstack/react-start' +import { + getResponseHeader, + setResponseHeader, + setResponseStatus, +} from '@tanstack/react-start/server' + +function getScenario(request: Request) { + const url = new URL(request.url) + return url.pathname.split('/').pop() || '' +} + +export function baseResponse(scenario: string) { + return new Response(scenario, { + headers: { 'x-handler': scenario, 'x-base': 'yes' }, + }) +} + +export const routeBoundaryMiddleware = createMiddleware().server( + async ({ next, request }) => { + const scenario = getScenario(request) + + if (scenario === 'route-before-next') { + setResponseHeader('x-route-before', 'yes') + setResponseStatus(234, 'route-before') + return next() + } + + if (scenario === 'route-after-next') { + const result = await next() + setResponseHeader('x-route-after', 'yes') + setResponseStatus(233, 'route-after') + return result + } + + if (scenario === 'direct-mutation-visible') { + const result = await next() + result.response.headers.set('x-direct-visible', 'yes') + setResponseHeader( + 'x-direct-read', + getResponseHeader('x-direct-visible') || 'missing', + ) + return result + } + + if (scenario === 'replace-after-direct-mutation') { + const result = await next() + result.response.headers.set('x-direct-a', 'yes') + setResponseHeader('x-helper-delta', 'yes') + return new Response('replacement', { + status: 202, + headers: { 'x-response-b': 'yes' }, + }) + } + + if (scenario === 'two-returned-responses') { + await next() + setResponseHeader('x-helper-after-a', 'yes') + return new Response('response-b', { + headers: { 'x-response-b': 'yes' }, + }) + } + + if (scenario === 'readonly-after-next') { + const result = await next() + setResponseHeader('x-readonly-after', 'yes') + return result + } + + return next() + }, +) + +export const returnedResponseMiddleware = createMiddleware().server( + async ({ next, request }) => { + if (getScenario(request) === 'two-returned-responses') { + await next() + return new Response('response-a', { + headers: { 'x-response-a': 'yes' }, + }) + } + + return next() + }, +) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/-tracked-streams.ts b/e2e/react-start/response-reconciliation/src/routes/api/-tracked-streams.ts new file mode 100644 index 0000000000..1ccde76367 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/-tracked-streams.ts @@ -0,0 +1,2 @@ +// Ids of tracked response streams that were cancelled, kept by the server. +export const cancelledStreams = new Set() diff --git a/e2e/react-start/response-reconciliation/src/routes/api/-upstream.ts b/e2e/react-start/response-reconciliation/src/routes/api/-upstream.ts new file mode 100644 index 0000000000..0018376035 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/-upstream.ts @@ -0,0 +1,14 @@ +// An upstream reply whose headers describe its own body and client. Start must +// not copy them onto the error body it generates for this failure. +export function createUpstreamFailure() { + return new Response('

upstream

', { + status: 502, + headers: { + 'content-encoding': 'gzip', + 'content-length': '999', + 'content-type': 'text/html', + 'set-cookie': 'upstream-session=leaked; Path=/', + 'x-upstream': 'yes', + }, + }) +} diff --git a/e2e/react-start/response-reconciliation/src/routes/api/base.ts b/e2e/react-start/response-reconciliation/src/routes/api/base.ts new file mode 100644 index 0000000000..62f706a9f1 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/base.ts @@ -0,0 +1,10 @@ +import { createFileRoute } from '@tanstack/react-router' +import { baseResponse } from './-response' + +export const Route = createFileRoute('/api/base')({ + server: { + handlers: { + GET: () => baseResponse('base'), + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/bulk-headers.ts b/e2e/react-start/response-reconciliation/src/routes/api/bulk-headers.ts new file mode 100644 index 0000000000..db7ded6c54 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/bulk-headers.ts @@ -0,0 +1,19 @@ +import { createFileRoute } from '@tanstack/react-router' +import { setResponseHeaders } from '@tanstack/react-start/server' + +export const Route = createFileRoute('/api/bulk-headers')({ + server: { + handlers: { + GET: () => { + const headers = new Headers({ + 'x-bulk-one': '1', + 'x-bulk-two': '2', + }) + headers.append('set-cookie', 'bulk-one=1; Path=/') + headers.append('set-cookie', 'bulk-two=2; Path=/') + setResponseHeaders(headers) + return new Response('bulk', { headers: { 'x-keep': 'yes' } }) + }, + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/clear-returned-headers.ts b/e2e/react-start/response-reconciliation/src/routes/api/clear-returned-headers.ts new file mode 100644 index 0000000000..fd3b88c172 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/clear-returned-headers.ts @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/react-router' +import { clearResponseHeaders } from '@tanstack/react-start/server' + +export const Route = createFileRoute('/api/clear-returned-headers')({ + server: { + handlers: { + GET: () => { + clearResponseHeaders() + return new Response('clear', { + headers: { 'x-clear-one': '1', 'x-clear-two': '2' }, + }) + }, + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/direct-mutation-visible.ts b/e2e/react-start/response-reconciliation/src/routes/api/direct-mutation-visible.ts new file mode 100644 index 0000000000..96823887e5 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/direct-mutation-visible.ts @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' +import { baseResponse, routeBoundaryMiddleware } from './-response' + +export const Route = createFileRoute('/api/direct-mutation-visible')({ + server: { + middleware: [routeBoundaryMiddleware], + handlers: { + GET: () => baseResponse('direct-mutation-visible'), + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/explicit-set-cookie-header.ts b/e2e/react-start/response-reconciliation/src/routes/api/explicit-set-cookie-header.ts new file mode 100644 index 0000000000..3ea2bc6d75 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/explicit-set-cookie-header.ts @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/react-router' +import { setResponseHeader } from '@tanstack/react-start/server' + +export const Route = createFileRoute('/api/explicit-set-cookie-header')({ + server: { + handlers: { + GET: () => { + setResponseHeader('set-cookie', [ + 'explicit-one=1; Path=/', + 'explicit-two=2; Path=/', + ]) + return new Response('explicit') + }, + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/framing-error.ts b/e2e/react-start/response-reconciliation/src/routes/api/framing-error.ts new file mode 100644 index 0000000000..baeab15780 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/framing-error.ts @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/react-router' +import { setResponseHeader } from '@tanstack/react-start/server' + +export const Route = createFileRoute('/api/framing-error')({ + server: { + handlers: { + GET: async () => { + // Headers for a compressed file whose read then fails. + setResponseHeader('content-encoding', 'gzip') + setResponseHeader('content-length', '2') + await Promise.resolve() + throw new Error('File read failed') + }, + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/get-response-header-helper.ts b/e2e/react-start/response-reconciliation/src/routes/api/get-response-header-helper.ts new file mode 100644 index 0000000000..b597882ff6 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/get-response-header-helper.ts @@ -0,0 +1,17 @@ +import { createFileRoute } from '@tanstack/react-router' +import { + getResponseHeader, + setResponseHeader, +} from '@tanstack/react-start/server' + +export const Route = createFileRoute('/api/get-response-header-helper')({ + server: { + handlers: { + GET: () => { + setResponseHeader('x-helper-visible', 'yes') + const value = getResponseHeader('x-helper-visible') || 'missing' + return new Response(value, { headers: { 'x-read-after-set': value } }) + }, + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/get-response-headers-helper.ts b/e2e/react-start/response-reconciliation/src/routes/api/get-response-headers-helper.ts new file mode 100644 index 0000000000..168d38bad4 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/get-response-headers-helper.ts @@ -0,0 +1,20 @@ +import { createFileRoute } from '@tanstack/react-router' +import { + getResponseHeaders, + setResponseHeader, +} from '@tanstack/react-start/server' + +export const Route = createFileRoute('/api/get-response-headers-helper')({ + server: { + handlers: { + GET: () => { + setResponseHeader('x-headers-helper-visible', 'yes') + // Exercise an untyped caller mutating its detached snapshot. + const headers = getResponseHeaders() as Headers + const value = headers.get('x-headers-helper-visible') || 'missing' + headers.set('x-headers-snapshot-write', 'ignored') + return new Response(value, { headers: { 'x-headers-read': value } }) + }, + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/multiple-cookies.ts b/e2e/react-start/response-reconciliation/src/routes/api/multiple-cookies.ts new file mode 100644 index 0000000000..eebf7a167e --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/multiple-cookies.ts @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/react-router' +import { setCookie } from '@tanstack/react-start/server' + +export const Route = createFileRoute('/api/multiple-cookies')({ + server: { + handlers: { + GET: () => { + setCookie('route-one', '1', { path: '/' }) + setCookie('route-two', '2', { path: '/' }) + return new Response('cookies') + }, + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/null-body-status.ts b/e2e/react-start/response-reconciliation/src/routes/api/null-body-status.ts new file mode 100644 index 0000000000..d11056e7a8 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/null-body-status.ts @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/react-router' +import { setResponseStatus } from '@tanstack/react-start/server' + +export const Route = createFileRoute('/api/null-body-status')({ + server: { + handlers: { + GET: ({ request }) => { + const statusParam = new URL(request.url).searchParams.get('status') + const status = + statusParam === '205' ? 205 : statusParam === '304' ? 304 : 204 + setResponseStatus(status) + return new Response('should-drop', { + headers: { 'x-null-body': 'yes' }, + }) + }, + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/readonly-after-next.ts b/e2e/react-start/response-reconciliation/src/routes/api/readonly-after-next.ts new file mode 100644 index 0000000000..7b42955052 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/readonly-after-next.ts @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' +import { routeBoundaryMiddleware } from './-response' + +export const Route = createFileRoute('/api/readonly-after-next')({ + server: { + middleware: [routeBoundaryMiddleware], + handlers: { + GET: () => fetch('data:text/plain,readonly'), + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/redirect-with-cookies.ts b/e2e/react-start/response-reconciliation/src/routes/api/redirect-with-cookies.ts new file mode 100644 index 0000000000..5b0072f35a --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/redirect-with-cookies.ts @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/react-router' +import { setCookie } from '@tanstack/react-start/server' + +export const Route = createFileRoute('/api/redirect-with-cookies')({ + server: { + handlers: { + GET: () => { + setCookie('redirect-one', '1', { path: '/' }) + setCookie('redirect-two', '2', { path: '/' }) + setCookie('redirect-three', '3', { path: '/' }) + return new Response(null, { + status: 307, + headers: { Location: '/api/base' }, + }) + }, + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/remove-returned-header.ts b/e2e/react-start/response-reconciliation/src/routes/api/remove-returned-header.ts new file mode 100644 index 0000000000..96f82bf98d --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/remove-returned-header.ts @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/react-router' +import { removeResponseHeader } from '@tanstack/react-start/server' + +export const Route = createFileRoute('/api/remove-returned-header')({ + server: { + handlers: { + GET: () => { + removeResponseHeader('x-remove-me') + return new Response('remove', { + headers: { 'x-remove-me': 'response', 'x-keep': 'yes' }, + }) + }, + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/replace-after-direct-mutation.ts b/e2e/react-start/response-reconciliation/src/routes/api/replace-after-direct-mutation.ts new file mode 100644 index 0000000000..890280483d --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/replace-after-direct-mutation.ts @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' +import { baseResponse, routeBoundaryMiddleware } from './-response' + +export const Route = createFileRoute('/api/replace-after-direct-mutation')({ + server: { + middleware: [routeBoundaryMiddleware], + handlers: { + GET: () => baseResponse('replace-after-direct-mutation'), + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/replace-explicit-set-cookie.ts b/e2e/react-start/response-reconciliation/src/routes/api/replace-explicit-set-cookie.ts new file mode 100644 index 0000000000..97df27d915 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/replace-explicit-set-cookie.ts @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/react-router' +import { setResponseHeader } from '@tanstack/react-start/server' + +export const Route = createFileRoute('/api/replace-explicit-set-cookie')({ + server: { + handlers: { + GET: () => { + setResponseHeader('set-cookie', 'explicit-new=1; Path=/') + return new Response('explicit', { + headers: { 'set-cookie': 'explicit-old=1; Path=/' }, + }) + }, + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/route-after-next.ts b/e2e/react-start/response-reconciliation/src/routes/api/route-after-next.ts new file mode 100644 index 0000000000..7d3650147f --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/route-after-next.ts @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' +import { baseResponse, routeBoundaryMiddleware } from './-response' + +export const Route = createFileRoute('/api/route-after-next')({ + server: { + middleware: [routeBoundaryMiddleware], + handlers: { + GET: () => baseResponse('route-after-next'), + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/route-before-next.ts b/e2e/react-start/response-reconciliation/src/routes/api/route-before-next.ts new file mode 100644 index 0000000000..b52c7642af --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/route-before-next.ts @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' +import { baseResponse, routeBoundaryMiddleware } from './-response' + +export const Route = createFileRoute('/api/route-before-next')({ + server: { + middleware: [routeBoundaryMiddleware], + handlers: { + GET: () => baseResponse('route-before-next'), + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/same-boundary-conflict.ts b/e2e/react-start/response-reconciliation/src/routes/api/same-boundary-conflict.ts new file mode 100644 index 0000000000..7ac086d652 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/same-boundary-conflict.ts @@ -0,0 +1,21 @@ +import { createFileRoute } from '@tanstack/react-router' +import { + setResponseHeader, + setResponseStatus, +} from '@tanstack/react-start/server' + +export const Route = createFileRoute('/api/same-boundary-conflict')({ + server: { + handlers: { + GET: () => { + setResponseStatus(235, 'same-boundary') + setResponseHeader('x-conflict', 'helper') + return new Response('conflict', { + status: 201, + statusText: 'response-status', + headers: { 'x-conflict': 'response' }, + }) + }, + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/status-contracts.ts b/e2e/react-start/response-reconciliation/src/routes/api/status-contracts.ts new file mode 100644 index 0000000000..43fd72ec07 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/status-contracts.ts @@ -0,0 +1,42 @@ +import { createFileRoute } from '@tanstack/react-router' +import { setResponseStatus } from '@tanstack/react-start/server' +import { createUpstreamFailure } from './-upstream' + +export const Route = createFileRoute('/api/status-contracts')({ + server: { + handlers: { + GET: async ({ request }) => { + const scenario = new URL(request.url).searchParams.get('scenario') + + if (scenario === 'invalid-status-return') { + setResponseStatus(999, 'Ignored') + return new Response('missing', { + status: 404, + statusText: 'Not Found', + }) + } + + if (scenario === 'invalid-status-throw') { + setResponseStatus(101) + throw new Error('Unexpected status contract failure') + } + + if (scenario === 'slow') { + await new Promise((resolve) => setTimeout(resolve, 150)) + return new Response('slow result') + } + + if (scenario === 'helper-success-crash') { + setResponseStatus(201, 'Created') + throw new Error('Crash after a success status') + } + + if (scenario === 'upstream-error-cause') { + throw new Error('Upstream failed', { cause: createUpstreamFailure() }) + } + + return new Response(`Unknown scenario: ${scenario}`, { status: 400 }) + }, + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/throw-after-status.ts b/e2e/react-start/response-reconciliation/src/routes/api/throw-after-status.ts new file mode 100644 index 0000000000..9d93d75b61 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/throw-after-status.ts @@ -0,0 +1,26 @@ +import { createFileRoute } from '@tanstack/react-router' +import { + setCookie, + setResponseHeader, + setResponseStatus, +} from '@tanstack/react-start/server' + +export const Route = createFileRoute('/api/throw-after-status')({ + server: { + handlers: { + GET: ({ request }) => { + const url = new URL(request.url) + setResponseStatus(401, 'Unauthorized') + setResponseHeader('x-error-helper', 'yes') + setCookie('throw-after-status', '1', { path: '/' }) + if (url.searchParams.get('throw') === 'response') { + throw new Response('Unauthorized response', { + status: 200, + headers: { 'x-thrown-response': 'yes' }, + }) + } + throw new Error('Unauthorized route') + }, + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/tracked-stream-status.ts b/e2e/react-start/response-reconciliation/src/routes/api/tracked-stream-status.ts new file mode 100644 index 0000000000..1aaffd8d36 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/tracked-stream-status.ts @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/react-router' +import { cancelledStreams } from './-tracked-streams' + +export const Route = createFileRoute('/api/tracked-stream-status')({ + server: { + handlers: { + GET: ({ request }) => { + const id = new URL(request.url).searchParams.get('id') ?? '' + return Response.json({ cancelled: cancelledStreams.has(id) }) + }, + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/tracked-stream.ts b/e2e/react-start/response-reconciliation/src/routes/api/tracked-stream.ts new file mode 100644 index 0000000000..640074a035 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/tracked-stream.ts @@ -0,0 +1,23 @@ +import { createFileRoute } from '@tanstack/react-router' +import { cancelledStreams } from './-tracked-streams' + +export const Route = createFileRoute('/api/tracked-stream')({ + server: { + handlers: { + // A body that never ends, like a live feed. Only cancellation stops it. + GET: ({ request }) => { + const id = new URL(request.url).searchParams.get('id') ?? '' + return new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('tracked')) + }, + cancel() { + cancelledStreams.add(id) + }, + }), + ) + }, + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/api/two-returned-responses.ts b/e2e/react-start/response-reconciliation/src/routes/api/two-returned-responses.ts new file mode 100644 index 0000000000..f433778fd8 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/api/two-returned-responses.ts @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/react-router' +import { + baseResponse, + returnedResponseMiddleware, + routeBoundaryMiddleware, +} from './-response' + +export const Route = createFileRoute('/api/two-returned-responses')({ + server: { + middleware: [routeBoundaryMiddleware, returnedResponseMiddleware], + handlers: { + GET: () => baseResponse('two-returned-responses'), + }, + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/routes/index.tsx b/e2e/react-start/response-reconciliation/src/routes/index.tsx new file mode 100644 index 0000000000..ab938397e9 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/index.tsx @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + headers: () => ({ 'x-route-header': 'present' }), + component: Home, +}) + +function Home() { + return ( +
+

Response Reconciliation E2E

+

This app contains HTTP-level regression tests.

+
+ ) +} diff --git a/e2e/react-start/response-reconciliation/src/routes/server-functions.tsx b/e2e/react-start/response-reconciliation/src/routes/server-functions.tsx new file mode 100644 index 0000000000..580309b31e --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/server-functions.tsx @@ -0,0 +1,285 @@ +import { ClientOnly, createFileRoute, redirect } from '@tanstack/react-router' +import { + createMiddleware, + createServerFn, + useServerFn, +} from '@tanstack/react-start' +import * as React from 'react' +import { + getResponseHeader, + setCookie, + setResponseHeader, + setResponseHeaders, + setResponseStatus, +} from '@tanstack/react-start/server' + +const functionAfterNextMiddleware = createMiddleware({ + type: 'function', +}).server(async ({ next }) => { + const result = await next() + setResponseHeader('x-function-after', 'yes') + setResponseStatus(236, 'function-after') + return result +}) + +const rawResponseAfterNextMiddleware = createMiddleware({ + type: 'function', +}).server(async ({ next }) => { + const result = await next() + setResponseHeader('x-function-raw-after', 'yes') + setResponseStatus(237, 'function-raw-after') + return result +}) + +const throwStatusMiddleware = createMiddleware({ + type: 'function', +}).server(() => { + setResponseStatus(401, 'Unauthorized') + setResponseHeader('x-function-error-middleware', 'yes') + throw new Error('Unauthorized function middleware') +}) + +const replacementMiddleware = createMiddleware({ + type: 'function', +}).server(async ({ next }) => { + const result = await next() + const resultWithResponse = result as typeof result & { result?: unknown } + if (!(resultWithResponse.result instanceof Response)) { + throw new Error('Expected replacement test to observe a Response') + } + resultWithResponse.result.headers.set('x-function-a', 'yes') + setResponseHeader('x-function-helper-delta', 'yes') + // Function middleware types don't model raw Response replacement, but the + // middleware executor supports it; this fixture deliberately exercises that + // runtime path. + return new Response('function-b', { + headers: { 'x-function-b': 'yes' }, + }) as never +}) + +const globalSerializedFn = createServerFn().handler(() => { + return { ok: true } +}) + +const functionAfterNextFn = createServerFn() + .middleware([functionAfterNextMiddleware]) + .handler(() => { + return { ok: true } + }) + +const rawResponseAfterNextFn = createServerFn() + .middleware([rawResponseAfterNextMiddleware]) + .handler(() => { + return new Response('raw function body', { + headers: { 'x-function-raw': 'yes' }, + }) + }) + +const replacementFn = createServerFn() + .middleware([replacementMiddleware]) + .handler(() => { + return new Response('function-a') + }) + +const multipleCookiesFn = createServerFn().handler(() => { + setCookie('fn-one', '1', { path: '/' }) + setCookie('fn-two', '2', { path: '/' }) + return { ok: true } +}) + +const rawMultipleCookiesFn = createServerFn().handler(() => { + setCookie('fn-raw-helper-one', '1', { path: '/' }) + setCookie('fn-raw-helper-two', '2', { path: '/' }) + const headers = new Headers() + headers.append('set-cookie', 'fn-raw-returned-one=1; Path=/') + headers.append('set-cookie', 'fn-raw-returned-two=2; Path=/') + return new Response('raw cookie body', { headers }) +}) + +const explicitCookieHeaderFn = createServerFn().handler(() => { + setResponseHeader('set-cookie', [ + 'fn-explicit-one=1; Path=/', + 'fn-explicit-two=2; Path=/', + ]) + return { ok: true } +}) + +const throwAfterStatusFn = createServerFn().handler(() => { + setResponseStatus(401, 'Unauthorized') + setResponseHeader('x-function-error', 'yes') + throw new Error('Unauthorized function') +}) + +const throwAfterFramingFn = createServerFn().handler(async () => { + // Headers for a compressed file whose read then fails. + setResponseHeader('content-encoding', 'gzip') + setResponseHeader('content-length', '2') + await Promise.resolve() + throw new Error('File read failed') +}) + +const throwAfterMiddlewareStatusFn = createServerFn() + .middleware([throwStatusMiddleware]) + .handler(() => { + return { ok: true } + }) + +const transportProtectedFn = createServerFn().handler(() => { + setResponseHeaders( + new Headers({ + 'content-type': 'text/plain', + 'x-tss-serialized': 'false', + 'x-user-header': 'yes', + }), + ) + return { ok: true } +}) + +const readAfterSetFn = createServerFn().handler(() => { + setResponseHeader('x-read-after-set', 'yes') + setResponseHeader( + 'x-read-after-set-value', + getResponseHeader('x-read-after-set') || 'missing', + ) + return { ok: true } +}) + +const returnRedirectFn = createServerFn().handler(() => { + setResponseStatus(302, 'Continue') + setResponseHeaders( + new Headers({ + 'content-type': 'text/plain', + 'x-tss-raw': 'true', + 'x-tss-serialized': 'true', + location: '/middleware-target', + }), + ) + setCookie('rpc-redirect', 'committed', { path: '/' }) + return redirect({ to: '/' }) +}) + +const throwRedirectFn = createServerFn().handler(() => { + setResponseStatus(302, 'Continue') + setResponseHeaders( + new Headers({ + 'content-type': 'text/plain', + 'x-tss-raw': 'true', + 'x-tss-serialized': 'true', + location: '/middleware-target', + }), + ) + setCookie('rpc-redirect', 'committed', { path: '/' }) + throw redirect({ to: '/' }) +}) + +const bodylessStatusFn = createServerFn().handler(() => { + setResponseStatus(204, 'No Content') + setResponseHeader('x-bodyless-status', 'ignored') + return { ok: true } +}) + +const throwZeroFn = createServerFn().handler(() => { + throw 0 +}) + +const throwResponseFn = createServerFn().handler(() => { + throw new Response('teapot', { status: 418 }) +}) + +const helperLocationFn = createServerFn().handler(() => { + setResponseStatus(302) + setResponseHeader('location', '/api/base') + return { ok: true } +}) + +export const Route = createFileRoute('/server-functions')({ + component: ServerFunctions, +}) + +function ServerFunctions() { + return ( +
+

Server Functions

+ + + + + + + + + + + + + + + + + + + + +
+ ) +} + +function ServerFunctionButton({ + name, + fn, +}: { + name: string + fn: (...args: Array) => Promise +}) { + const serverFn = useServerFn(fn) + const [result, setResult] = React.useState('idle') + + return ( +
+ + {result} +
+ ) +} diff --git a/e2e/react-start/response-reconciliation/src/routes/ssr.tsx b/e2e/react-start/response-reconciliation/src/routes/ssr.tsx new file mode 100644 index 0000000000..c0cb69c8ec --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/ssr.tsx @@ -0,0 +1,29 @@ +import { createFileRoute } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' +import { + setCookie, + setResponseHeader, + setResponseStatus, +} from '@tanstack/react-start/server' + +const setSsrResponseFn = createServerFn().handler(() => { + setResponseStatus(238, 'ssr-loader') + setResponseHeader('x-ssr-loader', 'yes') + setCookie('ssr-one', '1', { path: '/' }) + setCookie('ssr-two', '2', { path: '/' }) + return { message: 'ssr response' } +}) + +export const Route = createFileRoute('/ssr')({ + loader: () => setSsrResponseFn(), + component: SsrRoute, +}) + +function SsrRoute() { + const data = Route.useLoaderData() + return ( +
+

{data.message}

+
+ ) +} diff --git a/e2e/react-start/response-reconciliation/src/routes/streamed.tsx b/e2e/react-start/response-reconciliation/src/routes/streamed.tsx new file mode 100644 index 0000000000..8d6a6227cd --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/routes/streamed.tsx @@ -0,0 +1,25 @@ +import { Await, createFileRoute } from '@tanstack/react-router' +import { Suspense } from 'react' + +export const Route = createFileRoute('/streamed')({ + loader: () => ({ + deferred: new Promise((resolve) => + setTimeout(() => resolve('streamed after the shell'), 100), + ), + }), + component: StreamedRoute, +}) + +function StreamedRoute() { + const { deferred } = Route.useLoaderData() + return ( +
+

Streamed document

+ loading

}> + + {(value) =>

{value}

} +
+
+
+ ) +} diff --git a/e2e/react-start/response-reconciliation/src/server-entry.ts b/e2e/react-start/response-reconciliation/src/server-entry.ts new file mode 100644 index 0000000000..cbee8ad31a --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/server-entry.ts @@ -0,0 +1,84 @@ +import { + createStartHandler, + defaultStreamHandler, + getResponseStatus, + handleStartError, +} from '@tanstack/react-start/server' +import handler, { createServerEntry } from '@tanstack/react-start/server-entry' + +const uncaughtFetch = createStartHandler(defaultStreamHandler) + +// Reproduce #7647's custom stream handler that preserves middleware status. +const preserveStatusFetch = createStartHandler(async (ctx) => { + const result = await defaultStreamHandler(ctx) + const response = result instanceof Response ? result : result.response + const status = getResponseStatus() + if (status === response.status) { + return result + } + + const headers = new Headers(response.headers) + headers.set('x-stream-response-rebuilt', 'yes') + const replacement = new Response(response.body, { + status, + statusText: response.statusText, + headers, + }) + return result instanceof Response + ? replacement + : { ...result, response: replacement } +}) + +function markCustomServerEntry(response: Response): Response { + try { + response.headers.set('x-custom-server-entry', 'yes') + return response + } catch { + const headers = new Headers(response.headers) + headers.set('x-custom-server-entry', 'yes') + return new Response(response.body, { + status: response.status, + statusText: response.statusText, + headers, + }) + } +} + +export default createServerEntry({ + async fetch(request, opts) { + if (request.headers.get('x-reconciliation-scenario') === 'issue-7647') { + return markCustomServerEntry(await preserveStatusFetch(request, opts)) + } + + if (request.headers.get('x-custom-handle-errors') === 'false') { + try { + return markCustomServerEntry(await uncaughtFetch(request, opts)) + } catch (error) { + if (request.headers.get('x-custom-handle-start-error') === 'true') { + return markCustomServerEntry(handleStartError(error)) + } + return markCustomServerEntry( + new Response(error instanceof Error ? error.message : 'error', { + status: 555, + headers: { + 'x-custom-entry-catch': 'yes', + }, + }), + ) + } + } + + try { + return markCustomServerEntry(await handler.fetch(request, opts)) + } catch (error) { + return markCustomServerEntry( + new Response(error instanceof Error ? error.message : 'error', { + status: 556, + headers: { + 'x-custom-entry-catch': 'unexpected', + }, + }), + ) + } + }, +}) diff --git a/e2e/react-start/response-reconciliation/src/start.ts b/e2e/react-start/response-reconciliation/src/start.ts new file mode 100644 index 0000000000..2ac158b799 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/start.ts @@ -0,0 +1,170 @@ +import { createMiddleware, createStart } from '@tanstack/react-start' +import { + clearResponseHeaders, + setCookie, + getCookie, + setResponseHeader, + setResponseHeaders, + setResponseStatus, +} from '@tanstack/react-start/server' +import { createUpstreamFailure } from './routes/api/-upstream' +import { installResponseWrapper } from './response-wrapper' + +const globalResponseMiddleware = createMiddleware().server( + async ({ next, request }) => { + if (request.headers.get('x-wrap-response') === 'true') { + installResponseWrapper() + } + + const scenario = + request.headers.get('x-reconciliation-scenario') || + getCookie('reconciliation-scenario') + + if (scenario === 'issue-7647') { + setResponseStatus(418) + setResponseHeader('x-middleware-header', 'present') + setResponseHeader('cache-control', 'no-store') + return next() + } + + if (scenario === 'global-before') { + setResponseHeaders( + new Headers({ + 'x-global-before': 'yes', + 'x-global-common': 'before', + }), + ) + setResponseStatus(231, 'global-before') + return next() + } + + if (scenario === 'global-after') { + const result = await next() + setResponseHeader('x-global-after', 'yes') + setResponseHeader('x-global-common', 'after') + setResponseStatus(232, 'global-after') + return result + } + + if (scenario === 'global-multiple-cookies') { + setCookie('global-one', '1', { path: '/' }) + setCookie('global-two', '2', { path: '/' }) + return next() + } + + if (scenario === 'global-upstream-cause') { + throw new Error('Upstream failed', { cause: createUpstreamFailure() }) + } + + if (scenario === 'global-location-error') { + throw Object.assign(new Error('Moved error'), { + status: 302, + headers: { location: '/api/base' }, + }) + } + + if (scenario === 'global-same-body-wrapper') { + const result = await next() + const wrapped = new Response(result.response.body, result.response) + clearResponseHeaders() + setResponseHeader('x-same-body-wrapper', 'yes') + return { ...result, response: wrapped } + } + + if (scenario === 'global-copy') { + // Session middleware copies the response to add a header (#8627). + const result = await next() + const headers = new Headers(result.response.headers) + headers.set('x-global-copy', 'yes') + return { + ...result, + response: new Response(result.response.body, { + status: result.response.status, + statusText: result.response.statusText, + headers, + }), + } + } + + if (scenario === 'global-piped-copy') { + const result = await next() + const response = new Response( + result.response.body!.pipeThrough(new TransformStream()), + result.response, + ) + response.headers.set('x-global-piped-copy', 'yes') + return { ...result, response } + } + + if (scenario === 'global-representation') { + // Representation metadata computed from the body, as by ETag middleware. + const result = await next() + const body = await result.response.text() + const response = new Response(body, result.response) + response.headers.set('x-body-length', String(body.length)) + return { ...result, response } + } + + if (scenario === 'global-assigned-transform-not-modified') { + // Transform the body in place, then answer an ETag match instead. + const result = await next() + result.response = new Response( + result.response.body!.pipeThrough(new TransformStream()), + result.response, + ) + return new Response(null, { status: 304 }) + } + + if (scenario === 'global-timeout') { + // Keep working after next() while the handler the inner timeout + // abandoned is still running. + const result = await next() + await sleep(400) + return result + } + + if (scenario === 'global-throw') { + setResponseStatus(401, 'Unauthorized') + setResponseHeader('x-global-error', 'yes') + throw new Error('Unauthorized global middleware') + } + + if (scenario === 'global-throw-string') { + throw 'global string' + } + + if (scenario === 'global-throw-response') { + throw Response.json({ denied: true }, { status: 403 }) + } + + return next() + }, +) + +const sleep = (ms: number) => + new Promise((resolve) => setTimeout(resolve, ms)) + +const globalTimeoutMiddleware = createMiddleware().server( + ({ next, request }) => { + const scenario = + request.headers.get('x-reconciliation-scenario') || + getCookie('reconciliation-scenario') + if (scenario !== 'global-timeout') { + return next() + } + return Promise.race([ + next(), + sleep(50).then( + () => + new Response('timeout', { + status: 504, + headers: { 'x-timeout-fallback': 'yes' }, + }), + ), + ]) + }, +) + +export const startInstance = createStart(() => ({ + requestMiddleware: [globalResponseMiddleware, globalTimeoutMiddleware], +})) diff --git a/e2e/react-start/response-reconciliation/src/styles/app.css b/e2e/react-start/response-reconciliation/src/styles/app.css new file mode 100644 index 0000000000..a38fb439a6 --- /dev/null +++ b/e2e/react-start/response-reconciliation/src/styles/app.css @@ -0,0 +1,12 @@ +html { + color-scheme: light dark; + font-family: system-ui, sans-serif; +} + +body { + margin: 0; +} + +main { + padding: 16px; +} diff --git a/e2e/react-start/response-reconciliation/tests/response-reconciliation.spec.ts b/e2e/react-start/response-reconciliation/tests/response-reconciliation.spec.ts new file mode 100644 index 0000000000..728b0782c5 --- /dev/null +++ b/e2e/react-start/response-reconciliation/tests/response-reconciliation.spec.ts @@ -0,0 +1,1038 @@ +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' +import type { APIResponse, Page, Response } from '@playwright/test' + +type TestResponse = APIResponse | Response + +function header(response: TestResponse, name: string) { + return response.headers()[name.toLowerCase()] ?? null +} + +async function setCookieValues(response: TestResponse) { + return (await Promise.resolve(response.headersArray())) + .filter((item) => item.name.toLowerCase() === 'set-cookie') + .map((item) => item.value) +} + +function expectCookie(cookies: Array, name: string, value: string) { + expect( + cookies.filter((cookie) => cookie.startsWith(`${name}=${value};`)), + ).toHaveLength(1) +} + +async function invokeServerFunction( + page: Page, + name: string, + scenario?: string, +) { + await page.goto( + scenario + ? `/server-functions?scenario=${encodeURIComponent(scenario)}` + : '/server-functions', + ) + await expect(page.getByTestId('server-functions-hydrated')).toBeAttached() + await page.evaluate((value) => { + document.cookie = value + ? `reconciliation-scenario=${value}; Path=/` + : 'reconciliation-scenario=; Max-Age=0; Path=/' + }, scenario) + const responsePromise = page.waitForResponse((response) => + response.url().includes('/_serverFn/'), + ) + await page.getByTestId(`server-function-${name}`).click() + const response = await responsePromise + await expect( + page.getByTestId(`server-function-${name}-result`), + ).not.toHaveText('pending') + return response +} + +async function invokeJsonServerFunction( + page: Page, + name: string, + scenario?: string, +) { + const response = await invokeServerFunction(page, name, scenario) + const request = response.request() + expect(request.headers()['x-tsr-serverfn']).toBe('true') + const postData = request.postData() + if (postData) { + expect(postData).not.toContain('x-reconciliation-scenario') + } + return response +} + +async function expectServerFunctionResult( + page: Page, + name: string, + result: string | RegExp, +) { + await expect(page.getByTestId(`server-function-${name}-result`)).toHaveText( + result, + ) +} + +test.describe('server routes', () => { + test('uses expected server entry mode', async ({ request }) => { + const response = await request.get('/api/base') + + if (process.env.TSS_E2E_SERVER_ENTRY) { + expect(header(response, 'x-custom-server-entry')).toBe('yes') + } else { + expect(header(response, 'x-custom-server-entry')).toBe(null) + } + }) + + test('global request middleware cookies are preserved on server routes', async ({ + request, + }) => { + const response = await request.get('/api/base', { + headers: { 'x-reconciliation-scenario': 'global-multiple-cookies' }, + }) + const cookies = await setCookieValues(response) + + expectCookie(cookies, 'global-one', '1') + expectCookie(cookies, 'global-two', '2') + }) + + test('regression #5407: global middleware setResponseHeaders and status apply before next', async ({ + request, + }) => { + const response = await request.get('/api/base', { + headers: { 'x-reconciliation-scenario': 'global-before' }, + }) + + expect(response.status()).toBe(231) + expect(response.statusText()).toBe('global-before') + expect(header(response, 'x-global-before')).toBe('yes') + expect(header(response, 'x-global-common')).toBe('before') + expect(header(response, 'x-base')).toBe('yes') + }) + + test('global middleware helper changes apply after next', async ({ + request, + }) => { + const response = await request.get('/api/base', { + headers: { 'x-reconciliation-scenario': 'global-after' }, + }) + + expect(response.status()).toBe(232) + expect(response.statusText()).toBe('global-after') + expect(header(response, 'x-global-after')).toBe('yes') + expect(header(response, 'x-global-common')).toBe('after') + expect(header(response, 'x-base')).toBe('yes') + }) + + test('route middleware helper changes apply before and after next', async ({ + request, + }) => { + const before = await request.get('/api/route-before-next') + expect(before.status()).toBe(234) + expect(before.statusText()).toBe('route-before') + expect(header(before, 'x-route-before')).toBe('yes') + expect(header(before, 'x-handler')).toBe('route-before-next') + + const after = await request.get('/api/route-after-next') + expect(after.status()).toBe(233) + expect(after.statusText()).toBe('route-after') + expect(header(after, 'x-route-after')).toBe('yes') + expect(header(after, 'x-handler')).toBe('route-after-next') + }) + + test('helper changes overlay same-boundary returned response conflicts', async ({ + request, + }) => { + const response = await request.get('/api/same-boundary-conflict') + + expect(response.status()).toBe(235) + expect(response.statusText()).toBe('same-boundary') + expect(header(response, 'x-conflict')).toBe('helper') + await expect(response.text()).resolves.toBe('conflict') + }) + + test('setResponseHeaders accepts Headers and preserves multiple cookies', async ({ + request, + }) => { + const response = await request.get('/api/bulk-headers') + const cookies = await setCookieValues(response) + + expect(header(response, 'x-bulk-one')).toBe('1') + expect(header(response, 'x-bulk-two')).toBe('2') + expect(header(response, 'x-keep')).toBe('yes') + expectCookie(cookies, 'bulk-one', '1') + expectCookie(cookies, 'bulk-two', '2') + }) + + test('remove and clear helpers can remove returned response headers', async ({ + request, + }) => { + const removed = await request.get('/api/remove-returned-header') + expect(header(removed, 'x-remove-me')).toBe(null) + expect(header(removed, 'x-keep')).toBe('yes') + + const cleared = await request.get('/api/clear-returned-headers') + expect(header(cleared, 'x-clear-one')).toBe(null) + expect(header(cleared, 'x-clear-two')).toBe(null) + }) + + test('getResponseHeader and getResponseHeaders read helper writes immediately', async ({ + request, + }) => { + const headerResponse = await request.get('/api/get-response-header-helper') + expect(header(headerResponse, 'x-read-after-set')).toBe('yes') + await expect(headerResponse.text()).resolves.toBe('yes') + + const headersResponse = await request.get( + '/api/get-response-headers-helper', + ) + expect(header(headersResponse, 'x-headers-read')).toBe('yes') + expect(header(headersResponse, 'x-headers-snapshot-write')).toBe(null) + await expect(headersResponse.text()).resolves.toBe('yes') + }) + + test('getResponseHeader sees direct current response header mutation', async ({ + request, + }) => { + const response = await request.get('/api/direct-mutation-visible') + + expect(header(response, 'x-direct-visible')).toBe('yes') + expect(header(response, 'x-direct-read')).toBe('yes') + }) + + test('response replacement carries helper deltas but not old response mutations', async ({ + request, + }) => { + const response = await request.get('/api/replace-after-direct-mutation') + + expect(response.status()).toBe(202) + expect(header(response, 'x-direct-a')).toBe(null) + expect(header(response, 'x-helper-delta')).toBe('yes') + expect(header(response, 'x-response-b')).toBe('yes') + await expect(response.text()).resolves.toBe('replacement') + }) + + test('later returned response replaces earlier response metadata', async ({ + request, + }) => { + const response = await request.get('/api/two-returned-responses') + + expect(header(response, 'x-response-a')).toBe(null) + expect(header(response, 'x-response-b')).toBe('yes') + expect(header(response, 'x-helper-after-a')).toBe('yes') + await expect(response.text()).resolves.toBe('response-b') + }) + + test('readonly responses reconcile through clone fallback', async ({ + request, + }) => { + const response = await request.get('/api/readonly-after-next') + + expect(header(response, 'x-readonly-after')).toBe('yes') + await expect(response.text()).resolves.toBe('readonly') + }) + + for (const status of [204, 205, 304]) { + test(`null-body status ${status} drops the response body`, async ({ + request, + }) => { + const response = await request.get( + `/api/null-body-status?status=${status}`, + ) + + expect(response.status()).toBe(status) + expect(header(response, 'x-null-body')).toBe('yes') + await expect(response.text()).resolves.toBe('') + }) + } + + test('out-of-range setResponseStatus keeps the returned status', async ({ + request, + }) => { + const response = await request.get( + '/api/status-contracts?scenario=invalid-status-return', + ) + + expect(response.status()).toBe(404) + expect(response.statusText()).toBe('Not Found') + await expect(response.text()).resolves.toBe('missing') + }) + + test('out-of-range setResponseStatus keeps the uncaught error status', async ({ + request, + }) => { + const response = await request.get( + '/api/status-contracts?scenario=invalid-status-throw', + ) + + expect(response.status()).toBe(500) + await expect(response.json()).resolves.toMatchObject({ + status: 500, + unhandled: true, + }) + }) + + test('a timeout fallback survives the handler it abandoned while an outer middleware awaits', async ({ + request, + }) => { + const response = await request.get('/api/status-contracts?scenario=slow', { + headers: { 'x-reconciliation-scenario': 'global-timeout' }, + }) + + expect(response.status()).toBe(504) + expect(header(response, 'x-timeout-fallback')).toBe('yes') + await expect(response.text()).resolves.toBe('timeout') + }) + + test('a helper success status does not hide an uncaught error', async ({ + request, + }) => { + const response = await request.get( + '/api/status-contracts?scenario=helper-success-crash', + ) + + expect(response.status()).toBe(500) + await expect(response.json()).resolves.toMatchObject({ + status: 500, + unhandled: true, + }) + }) + + test('errors caused by an upstream response adopt only its status', async ({ + request, + }) => { + const response = await request.get( + '/api/status-contracts?scenario=upstream-error-cause', + ) + const body = await response.body() + + expect(response.status()).toBe(502) + expect(header(response, 'x-upstream')).toBeNull() + expect(header(response, 'content-type')).toContain('application/json') + expect(header(response, 'content-encoding')).toBeNull() + const contentLength = header(response, 'content-length') + if (contentLength !== null) { + expect(Number(contentLength)).toBe(body.byteLength) + } + expect(await setCookieValues(response)).toEqual([]) + expect(JSON.parse(body.toString())).toMatchObject({ status: 502 }) + }) + + test('regression #5107: thrown errors preserve explicit response status and headers', async ({ + request, + }) => { + const response = await request.get('/api/throw-after-status') + + expect(response.status()).toBe(401) + expect(response.statusText()).toBe('Unauthorized') + expect(header(response, 'x-error-helper')).toBe('yes') + expect(header(response, 'content-type')).toContain('application/json') + if (process.env.TSS_E2E_SERVER_ENTRY) { + expect(header(response, 'x-custom-server-entry')).toBe('yes') + expect(header(response, 'x-custom-entry-catch')).toBe(null) + } + await expect(response.json()).resolves.toMatchObject({ status: 401 }) + }) + + test('thrown responses preserve explicit response status and headers', async ({ + request, + }) => { + const response = await request.get('/api/throw-after-status?throw=response') + + expect(response.status()).toBe(401) + expect(response.statusText()).toBe('Unauthorized') + expect(header(response, 'x-error-helper')).toBe('yes') + expect(header(response, 'x-thrown-response')).toBe('yes') + if (process.env.TSS_E2E_SERVER_ENTRY) { + expect(header(response, 'x-custom-server-entry')).toBe('yes') + expect(header(response, 'x-custom-entry-catch')).toBe(null) + } + await expect(response.text()).resolves.toBe('Unauthorized response') + }) + + test('custom server entry can opt out of automatic error responses', async ({ + request, + }) => { + test.skip(!process.env.TSS_E2E_SERVER_ENTRY, 'custom server entry only') + + const response = await request.get('/api/throw-after-status', { + headers: { 'x-custom-handle-errors': 'false' }, + }) + + expect(response.status()).toBe(555) + expect(header(response, 'x-custom-server-entry')).toBe('yes') + expect(header(response, 'x-custom-entry-catch')).toBe('yes') + await expect(response.text()).resolves.toBe('Unauthorized route') + }) + + test('custom server entry can recover Start error response state', async ({ + request, + }) => { + test.skip(!process.env.TSS_E2E_SERVER_ENTRY, 'custom server entry only') + + const response = await request.get('/api/throw-after-status', { + headers: { + 'x-custom-handle-errors': 'false', + 'x-custom-handle-start-error': 'true', + }, + }) + const cookies = await setCookieValues(response) + + expect(response.status()).toBe(401) + expect(response.statusText()).toBe('Unauthorized') + expect(header(response, 'x-error-helper')).toBe('yes') + expect(header(response, 'x-custom-server-entry')).toBe('yes') + expect(header(response, 'x-custom-entry-catch')).toBe(null) + expectCookie(cookies, 'throw-after-status', '1') + await expect(response.json()).resolves.toMatchObject({ status: 401 }) + }) + + test('custom server entry can recover thrown response state', async ({ + request, + }) => { + test.skip(!process.env.TSS_E2E_SERVER_ENTRY, 'custom server entry only') + + const response = await request.get( + '/api/throw-after-status?throw=response', + { + headers: { + 'x-custom-handle-errors': 'false', + 'x-custom-handle-start-error': 'true', + }, + }, + ) + const cookies = await setCookieValues(response) + + expect(response.status()).toBe(401) + expect(response.statusText()).toBe('Unauthorized') + expect(header(response, 'x-error-helper')).toBe('yes') + expect(header(response, 'x-thrown-response')).toBe('yes') + expect(header(response, 'x-custom-server-entry')).toBe('yes') + expect(header(response, 'x-custom-entry-catch')).toBe(null) + expectCookie(cookies, 'throw-after-status', '1') + await expect(response.text()).resolves.toBe('Unauthorized response') + }) + + test('custom server entry can opt out of SSR request middleware error responses', async ({ + request, + }) => { + test.skip(!process.env.TSS_E2E_SERVER_ENTRY, 'custom server entry only') + + const response = await request.get('/ssr', { + headers: { + 'x-custom-handle-errors': 'false', + 'x-reconciliation-scenario': 'global-throw', + }, + }) + + expect(response.status()).toBe(555) + expect(header(response, 'x-custom-server-entry')).toBe('yes') + expect(header(response, 'x-custom-entry-catch')).toBe('yes') + await expect(response.text()).resolves.toBe( + 'Unauthorized global middleware', + ) + }) + + test('regression #5464: multiple Set-Cookie headers are preserved', async ({ + request, + }) => { + const response = await request.get('/api/multiple-cookies') + const cookies = await setCookieValues(response) + + expectCookie(cookies, 'route-one', '1') + expectCookie(cookies, 'route-two', '2') + }) + + test('explicit Set-Cookie header values are preserved and replace response values', async ({ + request, + }) => { + const explicit = await request.get('/api/explicit-set-cookie-header') + const explicitCookies = await setCookieValues(explicit) + expectCookie(explicitCookies, 'explicit-one', '1') + expectCookie(explicitCookies, 'explicit-two', '2') + + const replaced = await request.get('/api/replace-explicit-set-cookie') + const replacedCookies = await setCookieValues(replaced) + expectCookie(replacedCookies, 'explicit-new', '1') + expect( + replacedCookies.some((cookie) => cookie.startsWith('explicit-old=1;')), + ).toBe(false) + }) + + test('cookies survive redirect responses', async ({ request }) => { + const response = await request.get('/api/redirect-with-cookies', { + maxRedirects: 0, + }) + const cookies = await setCookieValues(response) + + expect(response.status()).toBe(307) + expect(header(response, 'location')).toBe('/api/base') + expectCookie(cookies, 'redirect-one', '1') + expectCookie(cookies, 'redirect-two', '2') + expectCookie(cookies, 'redirect-three', '3') + }) + + test('generated errors drop framing headers that helpers set for the failed body', async ({ + request, + }) => { + const response = await request.get('/api/framing-error') + + expect(response.status()).toBe(500) + expect(header(response, 'content-encoding')).toBeNull() + expect(header(response, 'content-length')).not.toBe('2') + expect(await response.json()).toMatchObject({ + status: 500, + unhandled: true, + }) + }) + + test('HEAD keeps the body for middleware until the response leaves the pipeline', async ({ + request, + }) => { + const headers = { 'x-reconciliation-scenario': 'global-representation' } + const get = await request.get('/api/base', { headers }) + const head = await request.head('/api/base', { headers }) + + expect(head.status()).toBe(get.status()) + expect(Number(header(get, 'x-body-length'))).toBeGreaterThan(0) + expect(header(head, 'x-body-length')).toBe(header(get, 'x-body-length')) + expect(await head.body()).toHaveLength(0) + }) + + test('a response that middleware assigned is disposed when it returns another', async ({ + request, + }) => { + const id = crypto.randomUUID() + const response = await request.get(`/api/tracked-stream?id=${id}`, { + headers: { + 'x-reconciliation-scenario': 'global-assigned-transform-not-modified', + }, + }) + + expect(response.status()).toBe(304) + await expect + .poll(async () => + (await request.get(`/api/tracked-stream-status?id=${id}`)).json(), + ) + .toEqual({ cancelled: true }) + }) +}) + +test.describe('SSR document responses', () => { + test('regression #7647: middleware status and headers survive alongside route headers', async ({ + request, + }) => { + const response = await request.get('/', { + headers: { + accept: 'text/html', + 'x-reconciliation-scenario': 'issue-7647', + }, + }) + + expect(response.status()).toBe(418) + expect(header(response, 'x-middleware-header')).toBe('present') + expect(header(response, 'cache-control')).toBe('no-store') + expect(header(response, 'x-route-header')).toBe('present') + expect(header(response, 'content-type')).toContain('text/html') + // Custom-entry modes must actually reconstruct the streamed response. + expect(header(response, 'x-stream-response-rebuilt')).toBe( + process.env.TSS_E2E_SERVER_ENTRY ? 'yes' : null, + ) + const html = await response.text() + expect(html).toContain('Response Reconciliation E2E') + }) + + test('loader helper headers, status, and cookies reconcile onto document response', async ({ + request, + }) => { + const response = await request.get('/ssr') + const cookies = await setCookieValues(response) + + expect(response.status()).toBe(238) + expect(response.statusText()).toBe('ssr-loader') + expect(header(response, 'x-ssr-loader')).toBe('yes') + expect(header(response, 'content-type')).toContain('text/html') + expectCookie(cookies, 'ssr-one', '1') + expectCookie(cookies, 'ssr-two', '2') + await expect(response.text()).resolves.toContain('ssr response') + }) + + test('regression #5464: SSR document responses preserve multiple Set-Cookie headers', async ({ + request, + }) => { + const response = await request.get('/ssr', { + headers: { 'x-reconciliation-scenario': 'global-multiple-cookies' }, + }) + const cookies = await setCookieValues(response) + + expectCookie(cookies, 'global-one', '1') + expectCookie(cookies, 'global-two', '2') + expectCookie(cookies, 'ssr-one', '1') + expectCookie(cookies, 'ssr-two', '2') + }) + + test('global middleware after next reconciles onto document response', async ({ + request, + }) => { + const response = await request.get('/ssr', { + headers: { 'x-reconciliation-scenario': 'global-after' }, + }) + + expect(response.status()).toBe(232) + expect(response.statusText()).toBe('global-after') + expect(header(response, 'x-global-after')).toBe('yes') + expect(header(response, 'x-ssr-loader')).toBe('yes') + }) + + test('middleware can stream the document through a body transform', async ({ + request, + }) => { + const response = await request.get('/streamed', { + headers: { 'x-reconciliation-scenario': 'global-piped-copy' }, + }) + + expect(response.status()).toBe(200) + expect(header(response, 'x-global-piped-copy')).toBe('yes') + const html = await response.text() + expect(html).toContain('streamed after the shell') + expect(html).toContain('') + }) + + test('HEAD documents keep their body for middleware until the response leaves the pipeline', async ({ + request, + }) => { + const headers = { 'x-reconciliation-scenario': 'global-representation' } + const get = await request.get('/', { headers }) + const head = await request.head('/', { headers }) + + expect(head.status()).toBe(get.status()) + expect(Number(header(get, 'x-body-length'))).toBeGreaterThan(0) + expect(header(head, 'x-body-length')).toBe(header(get, 'x-body-length')) + expect(await head.body()).toHaveLength(0) + }) + + test('regression #8627: middleware can copy the document when Response is wrapped', async ({ + request, + }) => { + const response = await request.get('/streamed', { + headers: { + 'x-reconciliation-scenario': 'global-copy', + 'x-wrap-response': 'true', + }, + }) + + expect(response.status()).toBe(200) + expect(header(response, 'x-global-copy')).toBe('yes') + const html = await response.text() + expect(html).toContain('streamed after the shell') + expect(html).toContain('') + }) + + test('regression #8627: loader helpers reconcile onto the document when Response is wrapped', async ({ + request, + }) => { + const response = await request.get('/ssr', { + headers: { 'x-wrap-response': 'true' }, + }) + const cookies = await setCookieValues(response) + + expect(response.status()).toBe(238) + expect(header(response, 'x-ssr-loader')).toBe('yes') + expectCookie(cookies, 'ssr-one', '1') + const html = await response.text() + expect(html).toContain('ssr response') + expect(html).toContain('') + }) +}) + +test.describe('server functions', () => { + test('global request middleware helper changes reconcile onto serialized responses', async ({ + page, + }) => { + const response = await invokeJsonServerFunction( + page, + 'globalSerialized', + 'global-before', + ) + + expect(response.status()).toBe(231) + expect(response.statusText()).toBe('global-before') + expect(header(response, 'x-global-before')).toBe('yes') + expect(header(response, 'x-tss-serialized')).toBe('true') + await expectServerFunctionResult(page, 'globalSerialized', '{"ok":true}') + }) + + test('global request middleware helper changes after next reconcile onto serialized responses', async ({ + page, + }) => { + const response = await invokeJsonServerFunction( + page, + 'globalSerialized', + 'global-after', + ) + + expect(response.status()).toBe(232) + expect(response.statusText()).toBe('global-after') + expect(header(response, 'x-global-after')).toBe('yes') + expect(header(response, 'x-tss-serialized')).toBe('true') + await expectServerFunctionResult(page, 'globalSerialized', '{"ok":true}') + }) + + test('function middleware helper changes after next reconcile onto serialized responses', async ({ + page, + }) => { + const response = await invokeJsonServerFunction(page, 'functionAfterNext') + + expect(response.status()).toBe(236) + expect(response.statusText()).toBe('function-after') + expect(header(response, 'x-function-after')).toBe('yes') + expect(header(response, 'x-tss-serialized')).toBe('true') + await expectServerFunctionResult(page, 'functionAfterNext', '{"ok":true}') + }) + + test('raw server function responses reconcile helper changes after next', async ({ + page, + }) => { + const response = await invokeJsonServerFunction( + page, + 'rawResponseAfterNext', + ) + + expect(response.status()).toBe(237) + expect(response.statusText()).toBe('function-raw-after') + expect(header(response, 'x-function-raw')).toBe('yes') + expect(header(response, 'x-function-raw-after')).toBe('yes') + expect(header(response, 'x-tss-raw')).toBe('true') + await expect(response.text()).resolves.toBe('raw function body') + await expectServerFunctionResult( + page, + 'rawResponseAfterNext', + '237:raw function body', + ) + }) + + test('function response replacement carries helper deltas only', async ({ + page, + }) => { + const response = await invokeJsonServerFunction(page, 'replacement') + + expect(header(response, 'x-function-a')).toBe(null) + expect(header(response, 'x-function-b')).toBe('yes') + expect(header(response, 'x-function-helper-delta')).toBe('yes') + await expect(response.text()).resolves.toBe('function-b') + await expectServerFunctionResult(page, 'replacement', '200:function-b') + }) + + test('server function preserves multiple Set-Cookie headers', async ({ + page, + }) => { + const response = await invokeJsonServerFunction(page, 'multipleCookies') + const cookies = await setCookieValues(response) + + expectCookie(cookies, 'fn-one', '1') + expectCookie(cookies, 'fn-two', '2') + await expectServerFunctionResult(page, 'multipleCookies', '{"ok":true}') + }) + + test('raw server function responses preserve multiple Set-Cookie headers', async ({ + page, + }) => { + const response = await invokeJsonServerFunction(page, 'rawMultipleCookies') + const cookies = await setCookieValues(response) + + expect(header(response, 'x-tss-raw')).toBe('true') + expectCookie(cookies, 'fn-raw-returned-one', '1') + expectCookie(cookies, 'fn-raw-returned-two', '2') + expectCookie(cookies, 'fn-raw-helper-one', '1') + expectCookie(cookies, 'fn-raw-helper-two', '2') + await expect(response.text()).resolves.toBe('raw cookie body') + await expectServerFunctionResult( + page, + 'rawMultipleCookies', + '200:raw cookie body', + ) + }) + + test('server function explicit Set-Cookie header arrays are preserved', async ({ + page, + }) => { + const response = await invokeJsonServerFunction( + page, + 'explicitCookieHeader', + ) + const cookies = await setCookieValues(response) + + expectCookie(cookies, 'fn-explicit-one', '1') + expectCookie(cookies, 'fn-explicit-two', '2') + await expectServerFunctionResult( + page, + 'explicitCookieHeader', + '{"ok":true}', + ) + }) + + test.describe('expected error responses', () => { + test.use({ + // A second RegExp would make Playwright read the array as a fixture + // tuple, so all expected statuses share one pattern. + whitelistErrors: [ + /Failed to load resource: the server responded with a status of (401 \(Unauthorized\)|403 \([^)]*\)|418 \([^)]*\)|500 \([^)]*\)|502 \([^)]*\))/, + ], + }) + + test('a server function that throws a Response rejects with it on the client', async ({ + page, + }) => { + const response = await invokeServerFunction(page, 'throwResponse') + + expect(response.status()).toBe(418) + expect(header(response, 'x-tss-raw')).toBe('thrown') + await expectServerFunctionResult( + page, + 'throwResponse', + 'thrown 418:teapot', + ) + }) + + test('server function thrown errors preserve explicit response status', async ({ + page, + }) => { + const response = await invokeJsonServerFunction(page, 'throwAfterStatus') + + expect(response.status()).toBe(401) + expect(response.statusText()).toBe('Unauthorized') + expect(header(response, 'x-function-error')).toBe('yes') + expect(header(response, 'x-tss-serialized')).toBe('true') + await expectServerFunctionResult(page, 'throwAfterStatus', /Unauthorized/) + }) + + test('server function errors drop framing headers that helpers set for the failed body', async ({ + page, + }) => { + const response = await invokeJsonServerFunction(page, 'throwAfterFraming') + + expect(header(response, 'content-encoding')).toBeNull() + expect(header(response, 'content-length')).not.toBe('2') + expect(header(response, 'x-tss-serialized')).toBe('true') + await expectServerFunctionResult( + page, + 'throwAfterFraming', + 'File read failed', + ) + }) + + test('server function request middleware errors caused by an upstream response adopt only its status', async ({ + page, + context, + }) => { + const response = await invokeJsonServerFunction( + page, + 'globalSerialized', + 'global-upstream-cause', + ) + + expect(response.status()).toBe(502) + expect(header(response, 'x-upstream')).toBeNull() + expect(header(response, 'content-type')).toContain('application/json') + expect(header(response, 'content-encoding')).toBeNull() + expect(await setCookieValues(response)).toEqual([]) + expect(await context.cookies()).not.toEqual( + expect.arrayContaining([ + expect.objectContaining({ name: 'upstream-session' }), + ]), + ) + await expectServerFunctionResult( + page, + 'globalSerialized', + 'Upstream failed', + ) + }) + + test('serialized errors drop a Location from error metadata', async ({ + page, + }) => { + const response = await invokeJsonServerFunction( + page, + 'globalSerialized', + 'global-location-error', + ) + + // Error metadata below 400 falls back to 500, and Location is dropped. + expect(response.status()).toBe(500) + expect(header(response, 'location')).toBeNull() + expect(response.request().redirectedTo()).toBeNull() + await expectServerFunctionResult(page, 'globalSerialized', 'Moved error') + }) + + test('server function request middleware errors are serialized', async ({ + page, + }) => { + const response = await invokeJsonServerFunction( + page, + 'globalSerialized', + 'global-throw', + ) + + expect(response.status()).toBe(401) + expect(response.statusText()).toBe('Unauthorized') + expect(header(response, 'x-global-error')).toBe('yes') + expect(header(response, 'x-tss-serialized')).toBe('true') + await expectServerFunctionResult(page, 'globalSerialized', /Unauthorized/) + }) + + test('a string thrown by request middleware rejects the server function call with it', async ({ + page, + }) => { + const response = await invokeJsonServerFunction( + page, + 'globalSerialized', + 'global-throw-string', + ) + + expect(response.status()).toBe(500) + expect(header(response, 'x-tss-serialized')).toBe('true') + await expectServerFunctionResult( + page, + 'globalSerialized', + 'thrown:"global string"', + ) + }) + + test('a Response thrown by request middleware rejects the server function call with it', async ({ + page, + }) => { + const response = await invokeServerFunction( + page, + 'globalSerialized', + 'global-throw-response', + ) + + expect(response.status()).toBe(403) + expect(header(response, 'x-tss-raw')).toBe('thrown') + await expectServerFunctionResult( + page, + 'globalSerialized', + 'thrown 403:{"denied":true}', + ) + }) + + test('regression #5107: function middleware thrown errors preserve explicit response status', async ({ + page, + }) => { + const response = await invokeJsonServerFunction( + page, + 'throwAfterMiddlewareStatus', + ) + + expect(response.status()).toBe(401) + expect(response.statusText()).toBe('Unauthorized') + expect(header(response, 'x-function-error-middleware')).toBe('yes') + expect(header(response, 'x-tss-serialized')).toBe('true') + await expectServerFunctionResult( + page, + 'throwAfterMiddlewareStatus', + /Unauthorized/, + ) + }) + }) + + test('a server function that throws 0 rejects on the client', async ({ + page, + }) => { + const response = await invokeJsonServerFunction(page, 'throwZero') + + expect(header(response, 'x-tss-serialized')).toBe('true') + await expectServerFunctionResult(page, 'throwZero', 'thrown:0') + }) + + test('serialized server function replies keep their body when a helper selects 204', async ({ + page, + }) => { + const response = await invokeJsonServerFunction(page, 'bodylessStatus') + + expect(response.status()).toBe(200) + expect(header(response, 'x-bodyless-status')).toBe('ignored') + expect(header(response, 'x-tss-serialized')).toBe('true') + await expectServerFunctionResult(page, 'bodylessStatus', '{"ok":true}') + }) + + test('serialized replies drop a helper Location so fetch does not follow it', async ({ + page, + }) => { + const response = await invokeJsonServerFunction(page, 'helperLocation') + + expect(response.status()).toBe(302) + expect(header(response, 'location')).toBeNull() + expect(response.request().redirectedTo()).toBeNull() + await expectServerFunctionResult(page, 'helperLocation', '{"ok":true}') + }) + + test('same-body wrapper responses keep serialized transport headers', async ({ + page, + }) => { + const response = await invokeJsonServerFunction( + page, + 'globalSerialized', + 'global-same-body-wrapper', + ) + + expect(header(response, 'x-same-body-wrapper')).toBe('yes') + expect(header(response, 'x-tss-serialized')).toBe('true') + expect(header(response, 'content-type')).toContain('application/json') + await expectServerFunctionResult(page, 'globalSerialized', '{"ok":true}') + }) + + test('transport headers win over user helpers while user headers persist', async ({ + page, + }) => { + const response = await invokeJsonServerFunction(page, 'transportProtected') + + expect(header(response, 'x-user-header')).toBe('yes') + expect(header(response, 'x-tss-serialized')).toBe('true') + expect(header(response, 'content-type')).toContain('application/json') + await expectServerFunctionResult(page, 'transportProtected', '{"ok":true}') + }) + + for (const name of ['returnRedirect', 'throwRedirect']) { + test(`server function ${name} navigates through the client with helper status and headers`, async ({ + page, + context, + }) => { + await page.goto('/server-functions') + await expect(page.getByTestId('server-functions-hydrated')).toBeAttached() + const responsePromise = page.waitForResponse((response) => + response.url().includes('/_serverFn/'), + ) + await page.getByTestId(`server-function-${name}`).click() + const response = await responsePromise + + expect(response.status()).toBe(302) + expect(header(response, 'location')).toBeNull() + expect(header(response, 'content-type')).toContain('application/json') + expect(header(response, 'x-tss-raw')).toBeNull() + expect(header(response, 'x-tss-serialized')).toBeNull() + expect(response.request().redirectedTo()).toBeNull() + // Playwright cannot expose a 302 body, even without Location. Successful + // client navigation verifies that Start decoded the redirect envelope. + await expect(page).toHaveURL('/') + await expect( + page.getByRole('heading', { name: 'Response Reconciliation E2E' }), + ).toBeVisible() + expect(await context.cookies()).toEqual( + expect.arrayContaining([ + expect.objectContaining({ name: 'rpc-redirect', value: 'committed' }), + ]), + ) + }) + } + + test('server function getResponseHeader sees helper writes immediately', async ({ + page, + }) => { + const response = await invokeJsonServerFunction(page, 'readAfterSet') + + expect(header(response, 'x-read-after-set')).toBe('yes') + expect(header(response, 'x-read-after-set-value')).toBe('yes') + await expectServerFunctionResult(page, 'readAfterSet', '{"ok":true}') + }) +}) diff --git a/e2e/react-start/response-reconciliation/tsconfig.json b/e2e/react-start/response-reconciliation/tsconfig.json new file mode 100644 index 0000000000..3824b148e1 --- /dev/null +++ b/e2e/react-start/response-reconciliation/tsconfig.json @@ -0,0 +1,22 @@ +{ + "include": ["**/*.ts", "**/*.tsx", "public/script*.js"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "isolatedModules": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "target": "ES2022", + "allowJs": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "~/*": ["./src/*"] + }, + "noEmit": true, + "types": ["vite/client"] + } +} diff --git a/e2e/react-start/response-reconciliation/vite.config.ts b/e2e/react-start/response-reconciliation/vite.config.ts new file mode 100644 index 0000000000..355e12a2f7 --- /dev/null +++ b/e2e/react-start/response-reconciliation/vite.config.ts @@ -0,0 +1,19 @@ +import { defineConfig } from 'vite' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' + +const serverEntry = process.env.TSS_E2E_SERVER_ENTRY +const outDir = process.env.E2E_DIST_DIR ?? 'dist' + +export default defineConfig({ + resolve: { tsconfigPaths: true }, + build: { + outDir, + }, + plugins: [ + tanstackStart({ + server: serverEntry ? { entry: serverEntry } : undefined, + }), + viteReact(), + ], +}) diff --git a/e2e/react-start/root-document-hydration/.gitignore b/e2e/react-start/root-document-hydration/.gitignore new file mode 100644 index 0000000000..229709a89d --- /dev/null +++ b/e2e/react-start/root-document-hydration/.gitignore @@ -0,0 +1,5 @@ +node_modules +dist +test-results +playwright-report +port*.txt diff --git a/e2e/react-start/root-document-hydration/.prettierignore b/e2e/react-start/root-document-hydration/.prettierignore new file mode 100644 index 0000000000..083bdb7c4c --- /dev/null +++ b/e2e/react-start/root-document-hydration/.prettierignore @@ -0,0 +1 @@ +src/routeTree.gen.ts diff --git a/e2e/react-start/root-document-hydration/package.json b/e2e/react-start/root-document-hydration/package.json new file mode 100644 index 0000000000..9dcfcb6fbc --- /dev/null +++ b/e2e/react-start/root-document-hydration/package.json @@ -0,0 +1,40 @@ +{ + "name": "tanstack-react-start-e2e-root-document-hydration", + "private": true, + "sideEffects": false, + "type": "module", + "scripts": { + "dev": "vite dev --port 3000", + "dev:e2e": "vite dev --port $PORT", + "build": "vite build && tsc --noEmit", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", + "test:e2e:dev": "MODE=dev playwright test --project=chromium", + "test:e2e:prod": "MODE=prod playwright test --project=chromium", + "test:e2e": "pnpm run test:e2e:dev && pnpm run test:e2e:prod" + }, + "dependencies": { + "@tanstack/react-router": "workspace:*", + "@tanstack/react-start": "workspace:*", + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@playwright/test": "^1.61.0", + "@tanstack/router-e2e-utils": "workspace:*", + "@types/node": "^22.10.2", + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^6.0.1", + "srvx": "^1.0.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" + }, + "nx": { + "targets": { + "test:e2e": { + "parallelism": false + } + } + } +} diff --git a/e2e/react-start/root-document-hydration/playwright.config.ts b/e2e/react-start/root-document-hydration/playwright.config.ts new file mode 100644 index 0000000000..13dda4e328 --- /dev/null +++ b/e2e/react-start/root-document-hydration/playwright.config.ts @@ -0,0 +1,37 @@ +import { defineConfig, devices } from '@playwright/test' +import { appServerReady } from '@tanstack/router-e2e-utils' + +const isDev = process.env.MODE === 'dev' +const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const baseURL = `http://localhost:${PORT}` + +export default defineConfig({ + testDir: './tests', + workers: 1, + reporter: [['line']], + + use: { + baseURL, + }, + + webServer: { + command: isDev + ? 'pnpm dev:e2e --port 0' + : `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + env: { + PORT: String(PORT), + }, + }, + + projects: [ + { + name: 'chromium', + use: { + ...devices['Desktop Chrome'], + }, + }, + ], +}) diff --git a/e2e/react-start/root-document-hydration/src/routeTree.gen.ts b/e2e/react-start/root-document-hydration/src/routeTree.gen.ts new file mode 100644 index 0000000000..dceedffdc1 --- /dev/null +++ b/e2e/react-start/root-document-hydration/src/routeTree.gen.ts @@ -0,0 +1,68 @@ +/* eslint-disable */ + +// @ts-nocheck + +// 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' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' + fileRoutesByTo: FileRoutesByTo + to: '/' + id: '__root__' | '/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { createStart } from '@tanstack/react-start' +declare module '@tanstack/react-start' { + interface Register { + ssr: true + router: Awaited> + } +} diff --git a/e2e/react-start/root-document-hydration/src/router.tsx b/e2e/react-start/root-document-hydration/src/router.tsx new file mode 100644 index 0000000000..58f4d54e88 --- /dev/null +++ b/e2e/react-start/root-document-hydration/src/router.tsx @@ -0,0 +1,6 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ routeTree }) +} diff --git a/e2e/react-start/root-document-hydration/src/routes/__root.tsx b/e2e/react-start/root-document-hydration/src/routes/__root.tsx new file mode 100644 index 0000000000..2dc235e951 --- /dev/null +++ b/e2e/react-start/root-document-hydration/src/routes/__root.tsx @@ -0,0 +1,36 @@ +import { + HeadContent, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/react-router' +import { useEffect } from 'react' + +export const Route = createRootRoute({ + pendingComponent: () => null, + component: RootComponent, +}) + +function RootComponent() { + useEffect(() => { + document.documentElement.dataset.hydrated = 'true' + }, []) + + return ( + + + + + +
+ ', endIndex) - - expect(endIndex).toBeGreaterThan(-1) - expect(lastScriptOpen).toBeGreaterThan(lastScriptClose) - expect(slowAsyncPayloadIndex).toBeGreaterThan(-1) - expect(slowAsyncPayloadIndex).toBeLessThan(endIndex) - expect(html.slice(lastScriptOpen, endIndex)).toContain('.return(void 0)') - expect(endIndex).toBeLessThan(html.indexOf('')) - }) + expect(syncQueryChunk).toBeDefined() + expect(syncQueryChunk).toContain('sync-value-2') + expect(syncQueryChunk).toContain('sync-value-3') }) diff --git a/e2e/react-start/streaming-ssr/tests/router-html-buffer.spec.ts b/e2e/react-start/streaming-ssr/tests/router-html-buffer.spec.ts new file mode 100644 index 0000000000..a9cf8a8142 --- /dev/null +++ b/e2e/react-start/streaming-ssr/tests/router-html-buffer.spec.ts @@ -0,0 +1,34 @@ +import { + STREAM_PART_SELECTOR, + expect, + test, + testWithHydration, +} from '../../../streaming-ssr-assertions' + +const runBufferReproduction = + process.env.RUN_SSR_ROUTER_HTML_BUFFER_REPRO === 'true' + +test.describe('SSR router HTML buffer', () => { + test.skip( + !runBufferReproduction, + 'The 17 MiB ASCII reproduction is intentionally opt-in: pnpm test:e2e:buffer-repro', + ) + + testWithHydration( + 'hydrates a large deferred loader payload from server state', + async ({ page }) => { + const response = await page.goto('/router-html-buffer') + + expect(response?.ok()).toBe(true) + await expect(page.getByTestId('router-html-payload-length')).toHaveText( + '17825792', + ) + await expect(page.locator(STREAM_PART_SELECTOR)).toHaveCount(0) + + await page.getByTestId('router-html-payload-check').click() + await expect(page.getByTestId('router-html-payload-result')).toHaveText( + 'server:17825792:x', + ) + }, + ) +}) diff --git a/e2e/react-start/streaming-ssr/tests/slow-render.spec.ts b/e2e/react-start/streaming-ssr/tests/slow-render.spec.ts index c3631a7fc0..0d5a87363f 100644 --- a/e2e/react-start/streaming-ssr/tests/slow-render.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/slow-render.spec.ts @@ -1,73 +1 @@ -import { expect, test, testWithHydration } from './fixtures' - -test.describe('Slow render (render takes longer than serialization)', () => { - test('all data eventually renders with server source', async ({ page }) => { - await page.goto('/slow-render') - await page.waitForLoadState('networkidle') - - // Quick data should be available with server source - await expect(page.getByTestId('quick-data')).toContainText('Quick:') - await expect(page.getByTestId('quick-source')).toContainText( - 'Quick data source: server', - ) - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - - // Deferred data should resolve with server source - await expect(page.getByTestId('deferred-resolved')).toContainText( - 'Deferred resolved!', - { timeout: 5000 }, - ) - await expect(page.getByTestId('deferred-resolved')).toContainText( - 'source: server', - { timeout: 5000 }, - ) - - // Slow components should have rendered - await expect(page.getByTestId('slow-component-1')).toBeVisible() - await expect(page.getByTestId('slow-component-2')).toBeVisible() - await expect(page.getByTestId('slow-component-3')).toBeVisible() - }) - - testWithHydration('hydration works after slow render', async ({ page }) => { - await page.goto('/slow-render') - await page.waitForLoadState('networkidle') - - // Wait for content and verify server source - await expect(page.getByTestId('slow-component-1')).toBeVisible() - await expect(page.getByTestId('loader-source')).toContainText( - 'Loader source: server', - ) - }) - - test('client-side navigation works', async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via nav link - await page.getByRole('link', { name: 'Slow Render' }).first().click() - await expect(page).toHaveURL('/slow-render') - - await expect(page.getByTestId('quick-data')).toBeVisible({ timeout: 10000 }) - }) - - test('all data sources are server - proves SSR streaming works', async ({ - page, - }) => { - await page.goto('/slow-render') - await page.waitForLoadState('networkidle') - - // Wait for deferred content - await expect(page.getByTestId('deferred-resolved')).toBeVisible({ - timeout: 5000, - }) - - // Verify all sources are server - await expect(page.getByTestId('quick-source')).toContainText('server') - await expect(page.getByTestId('loader-source')).toContainText('server') - await expect(page.getByTestId('deferred-resolved')).toContainText( - 'source: server', - ) - }) -}) +import '../../../streaming-ssr-specs/slow-render' diff --git a/e2e/react-start/streaming-ssr/tests/stream.spec.ts b/e2e/react-start/streaming-ssr/tests/stream.spec.ts index 5e4c134f82..a51614f09a 100644 --- a/e2e/react-start/streaming-ssr/tests/stream.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/stream.spec.ts @@ -1,46 +1 @@ -import { expect, test, testWithHydration } from './fixtures' - -test.describe('ReadableStream streaming', () => { - testWithHydration('promise data resolves correctly', async ({ page }) => { - await page.goto('/stream') - - // Promise should resolve - await expect(page.getByTestId('promise-data')).toContainText( - 'promise-resolved', - { timeout: 5000 }, - ) - }) - - testWithHydration('stream chunks arrive incrementally', async ({ page }) => { - await page.goto('/stream') - - // Wait for stream to complete - await expect(page.getByTestId('stream-complete')).toBeVisible({ - timeout: 10000, - }) - - // All chunks should be present - await expect(page.getByTestId('stream-chunk-0')).toContainText('chunk-0') - await expect(page.getByTestId('stream-chunk-1')).toContainText('chunk-1') - await expect(page.getByTestId('stream-chunk-2')).toContainText('chunk-2') - await expect(page.getByTestId('stream-chunk-3')).toContainText('chunk-3') - await expect(page.getByTestId('stream-chunk-4')).toContainText('chunk-4') - }) - - testWithHydration( - 'client-side navigation to stream route works', - async ({ page }) => { - await page.goto('/') - await page.waitForLoadState('networkidle') - - // Navigate via nav link - await page.getByRole('link', { name: 'Stream' }).first().click() - await expect(page).toHaveURL('/stream') - - // Wait for stream to complete - await expect(page.getByTestId('stream-complete')).toBeVisible({ - timeout: 10000, - }) - }, - ) -}) +import '../../../streaming-ssr-specs/stream' diff --git a/e2e/react-start/streaming-ssr/tests/sync-only.spec.ts b/e2e/react-start/streaming-ssr/tests/sync-only.spec.ts index a0060a07ee..0e9278d3f2 100644 --- a/e2e/react-start/streaming-ssr/tests/sync-only.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/sync-only.spec.ts @@ -1,84 +1 @@ -import { expect } from '@playwright/test' -import { test, testWithHydration } from './fixtures' - -/** - * Tests for synchronous serialization - no deferred data, no streaming. - * This is the most common case where all loader data is immediately available. - * The hydration scripts should be included in the initial HTML response. - */ - -test('Sync-only route renders with loader data', async ({ page }) => { - await page.goto('/sync-only') - - // Verify the page content is rendered - await expect(page.getByTestId('sync-title')).toContainText( - 'Synchronous Serialization Test', - ) - await expect(page.getByTestId('sync-message')).toContainText( - 'Hello from sync loader!', - ) - - // Verify loader data items are rendered - await expect(page.getByTestId('sync-item-item-1')).toBeVisible() - await expect(page.getByTestId('sync-item-item-2')).toBeVisible() - await expect(page.getByTestId('sync-item-item-3')).toBeVisible() - - // Verify data came from server (proves SSR streaming worked) - await expect(page.getByTestId('sync-source')).toContainText('Source: server') -}) - -testWithHydration('Sync-only route hydrates correctly', async ({ page }) => { - await page.goto('/sync-only') - - // Verify client-side navigation works (proves hydration succeeded) - await page.getByRole('navigation').getByRole('link', { name: 'Home' }).click() - await expect(page.getByTestId('index-title')).toBeVisible() - - // Navigate back to sync-only via client-side navigation (use nav link to be specific) - await page - .getByRole('navigation') - .getByRole('link', { name: 'Sync Only' }) - .click() - await expect(page.getByTestId('sync-title')).toBeVisible() -}) - -test('Sync-only route has bootstrap scripts in initial HTML', async ({ - page, -}) => { - // Intercept the response to check the raw HTML - let responseHtml = '' - await page.route('/sync-only', async (route) => { - const response = await route.fetch() - responseHtml = await response.text() - await route.fulfill({ response }) - }) - - await page.goto('/sync-only') - - // Wait for page to load - await expect(page.getByTestId('sync-title')).toBeVisible() - - // The HTML should contain the bootstrap scripts - // $_TSR.router should be present (the dehydrated router state) - expect(responseHtml).toContain('$_TSR') - expect(responseHtml).toContain('$_TSR.router') - // The serialization end marker should be present - expect(responseHtml).toContain('$_TSR.e()') - - // SSR should include the barrier script tag in the HTML (rendered by ) - // This is the critical marker transformStreamWithRouter can scan for. - expect(responseHtml).toContain('$tsr-stream-barrier') -}) - -test('Navigating to sync-only from home page', async ({ page }) => { - await page.goto('/') - - await page.getByTestId('link-sync-only').click() - - await expect(page.getByTestId('sync-title')).toContainText( - 'Synchronous Serialization Test', - ) - await expect(page.getByTestId('sync-message')).toContainText( - 'Hello from sync loader!', - ) -}) +import '../../../streaming-ssr-specs/sync-only' diff --git a/e2e/react-start/streaming-ssr/vite.config.ts b/e2e/react-start/streaming-ssr/vite.config.ts index 275bfacde2..0590c197a5 100644 --- a/e2e/react-start/streaming-ssr/vite.config.ts +++ b/e2e/react-start/streaming-ssr/vite.config.ts @@ -1,9 +1,10 @@ import { defineConfig } from 'vite' import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import viteReact from '@vitejs/plugin-react' export default defineConfig({ server: { port: 3000, }, - plugins: [tanstackStart()], + plugins: [tanstackStart(), viteReact()], }) diff --git a/e2e/react-start/transform-asset-urls/package.json b/e2e/react-start/transform-asset-urls/package.json index 979f7c4f76..e0a5ffec59 100644 --- a/e2e/react-start/transform-asset-urls/package.json +++ b/e2e/react-start/transform-asset-urls/package.json @@ -16,19 +16,19 @@ "manual:both:options": "TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform pnpm manual:both", "manual:both:options:transform": "TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform pnpm manual:both", "manual:both:options:createTransform": "TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform pnpm manual:both", - "test:e2e:string": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=string playwright test --project=chromium", - "test:e2e:function": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=function playwright test --project=chromium", - "test:e2e:options": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform playwright test --project=chromium", - "test:e2e:options:transform": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform playwright test --project=chromium", - "test:e2e:options:createTransform": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform playwright test --project=chromium", - "test:e2e:options:transform:cache-true:warmup-true": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform TRANSFORM_ASSETS_OPTIONS_CACHE=true TRANSFORM_ASSETS_OPTIONS_WARMUP=true playwright test --project=chromium", - "test:e2e:options:transform:cache-true:warmup-false": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform TRANSFORM_ASSETS_OPTIONS_CACHE=true TRANSFORM_ASSETS_OPTIONS_WARMUP=false playwright test --project=chromium", - "test:e2e:options:transform:cache-false:warmup-true": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform TRANSFORM_ASSETS_OPTIONS_CACHE=false TRANSFORM_ASSETS_OPTIONS_WARMUP=true playwright test --project=chromium", - "test:e2e:options:transform:cache-false:warmup-false": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform TRANSFORM_ASSETS_OPTIONS_CACHE=false TRANSFORM_ASSETS_OPTIONS_WARMUP=false playwright test --project=chromium", - "test:e2e:options:createTransform:cache-true:warmup-true": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform TRANSFORM_ASSETS_OPTIONS_CACHE=true TRANSFORM_ASSETS_OPTIONS_WARMUP=true playwright test --project=chromium", - "test:e2e:options:createTransform:cache-true:warmup-false": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform TRANSFORM_ASSETS_OPTIONS_CACHE=true TRANSFORM_ASSETS_OPTIONS_WARMUP=false playwright test --project=chromium", - "test:e2e:options:createTransform:cache-false:warmup-true": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform TRANSFORM_ASSETS_OPTIONS_CACHE=false TRANSFORM_ASSETS_OPTIONS_WARMUP=true playwright test --project=chromium", - "test:e2e:options:createTransform:cache-false:warmup-false": "rm -rf dist; rm -rf port*.txt; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform TRANSFORM_ASSETS_OPTIONS_CACHE=false TRANSFORM_ASSETS_OPTIONS_WARMUP=false playwright test --project=chromium", + "test:e2e:string": "rm -rf dist; TRANSFORM_ASSETS_MODE=string playwright test --project=chromium", + "test:e2e:function": "rm -rf dist; TRANSFORM_ASSETS_MODE=function playwright test --project=chromium", + "test:e2e:options": "rm -rf dist; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform playwright test --project=chromium", + "test:e2e:options:transform": "rm -rf dist; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform playwright test --project=chromium", + "test:e2e:options:createTransform": "rm -rf dist; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform playwright test --project=chromium", + "test:e2e:options:transform:cache-true:warmup-true": "rm -rf dist; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform TRANSFORM_ASSETS_OPTIONS_CACHE=true TRANSFORM_ASSETS_OPTIONS_WARMUP=true playwright test --project=chromium", + "test:e2e:options:transform:cache-true:warmup-false": "rm -rf dist; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform TRANSFORM_ASSETS_OPTIONS_CACHE=true TRANSFORM_ASSETS_OPTIONS_WARMUP=false playwright test --project=chromium", + "test:e2e:options:transform:cache-false:warmup-true": "rm -rf dist; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform TRANSFORM_ASSETS_OPTIONS_CACHE=false TRANSFORM_ASSETS_OPTIONS_WARMUP=true playwright test --project=chromium", + "test:e2e:options:transform:cache-false:warmup-false": "rm -rf dist; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=transform TRANSFORM_ASSETS_OPTIONS_CACHE=false TRANSFORM_ASSETS_OPTIONS_WARMUP=false playwright test --project=chromium", + "test:e2e:options:createTransform:cache-true:warmup-true": "rm -rf dist; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform TRANSFORM_ASSETS_OPTIONS_CACHE=true TRANSFORM_ASSETS_OPTIONS_WARMUP=true playwright test --project=chromium", + "test:e2e:options:createTransform:cache-true:warmup-false": "rm -rf dist; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform TRANSFORM_ASSETS_OPTIONS_CACHE=true TRANSFORM_ASSETS_OPTIONS_WARMUP=false playwright test --project=chromium", + "test:e2e:options:createTransform:cache-false:warmup-true": "rm -rf dist; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform TRANSFORM_ASSETS_OPTIONS_CACHE=false TRANSFORM_ASSETS_OPTIONS_WARMUP=true playwright test --project=chromium", + "test:e2e:options:createTransform:cache-false:warmup-false": "rm -rf dist; TRANSFORM_ASSETS_MODE=options TRANSFORM_ASSETS_OPTIONS_KIND=createTransform TRANSFORM_ASSETS_OPTIONS_CACHE=false TRANSFORM_ASSETS_OPTIONS_WARMUP=false playwright test --project=chromium", "test:e2e:options:matrix": "pnpm test:e2e:options:transform:cache-true:warmup-true && pnpm test:e2e:options:transform:cache-true:warmup-false && pnpm test:e2e:options:transform:cache-false:warmup-true && pnpm test:e2e:options:transform:cache-false:warmup-false && pnpm test:e2e:options:createTransform:cache-true:warmup-true && pnpm test:e2e:options:createTransform:cache-true:warmup-false && pnpm test:e2e:options:createTransform:cache-false:warmup-true && pnpm test:e2e:options:createTransform:cache-false:warmup-false", "test:e2e": "pnpm test:e2e:string && pnpm test:e2e:function && pnpm test:e2e:options:matrix" }, @@ -46,8 +46,9 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^0.11.9", - "typescript": "^6.0.2", + "srvx": "^1.0.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/e2e/react-start/transform-asset-urls/playwright.config.ts b/e2e/react-start/transform-asset-urls/playwright.config.ts index bbef6838fe..209a7e0596 100644 --- a/e2e/react-start/transform-asset-urls/playwright.config.ts +++ b/e2e/react-start/transform-asset-urls/playwright.config.ts @@ -1,12 +1,10 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const APP_PORT = await getTestServerPort(packageJson.name) -const CDN_PORT = await getTestServerPort(`${packageJson.name}_cdn`) +const APP_PORT = Number(process.env.E2E_APP_PORT ?? 0) +const CDN_PORT = Number(process.env.E2E_CDN_PORT ?? 0) const baseURL = `http://localhost:${APP_PORT}` -const cdnOrigin = `http://localhost:${CDN_PORT}` const transformMode = process.env.TRANSFORM_ASSETS_MODE || 'string' const optionsKind = process.env.TRANSFORM_ASSETS_OPTIONS_KIND || 'createTransform' @@ -26,8 +24,11 @@ export default defineConfig({ { // CDN server — serves built client assets on a separate port with CORS command: `node tests/cdn-server.mjs`, - url: `http://localhost:${CDN_PORT}/health`, - reuseExistingServer: !process.env.CI, + wait: { + stdout: + /CDN Server: (?http:\/\/localhost:(?\d+))/, + }, + reuseExistingServer: false, stdout: 'pipe', env: { CDN_PORT: String(CDN_PORT), @@ -37,12 +38,11 @@ export default defineConfig({ // App server — builds the project then starts the srvx server // with CDN_ORIGIN so that transformAssets rewrites manifest URLs command: `pnpm build && pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', env: { PORT: String(APP_PORT), - CDN_ORIGIN: cdnOrigin, TRANSFORM_ASSETS_MODE: transformMode, TRANSFORM_ASSETS_OPTIONS_KIND: optionsKind, TRANSFORM_ASSETS_OPTIONS_CACHE: optionsCache, diff --git a/e2e/react-start/transform-asset-urls/src/routeTree.gen.ts b/e2e/react-start/transform-asset-urls/src/routeTree.gen.ts index 421daf2790..d89758e684 100644 --- a/e2e/react-start/transform-asset-urls/src/routeTree.gen.ts +++ b/e2e/react-start/transform-asset-urls/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/e2e/react-start/transform-asset-urls/src/server.ts b/e2e/react-start/transform-asset-urls/src/server.ts index 241fc2fe51..a51f29ad66 100644 --- a/e2e/react-start/transform-asset-urls/src/server.ts +++ b/e2e/react-start/transform-asset-urls/src/server.ts @@ -83,4 +83,18 @@ const handler = createStartHandler( : defaultStreamHandler, ) -export default createServerEntry({ fetch: handler }) +export default createServerEntry({ + fetch(request, options) { + const scriptUrl = request.headers.get('x-test-script-url') + if (scriptUrl) { + return createStartHandler({ + handler: defaultStreamHandler, + transformAssets: ({ kind, url }) => ({ + href: kind === 'script' ? scriptUrl : url, + }), + })(request, options) + } + + return handler(request, options) + }, +}) diff --git a/e2e/react-start/transform-asset-urls/tests/cdn-server.mjs b/e2e/react-start/transform-asset-urls/tests/cdn-server.mjs index ea9bf62cd0..280c626867 100644 --- a/e2e/react-start/transform-asset-urls/tests/cdn-server.mjs +++ b/e2e/react-start/transform-asset-urls/tests/cdn-server.mjs @@ -3,7 +3,7 @@ import path from 'node:path' import { fileURLToPath } from 'node:url' const __dirname = path.dirname(fileURLToPath(import.meta.url)) -const port = process.env.CDN_PORT || 3002 +const port = Number(process.env.CDN_PORT ?? 0) const app = express() @@ -36,7 +36,7 @@ app.use((req, res, next) => { app.use(express.static(path.resolve(__dirname, '..', 'dist', 'client'))) -app.listen(port, (error) => { +const server = app.listen(port, (error) => { if (error) throw error - console.info(`CDN Server: http://localhost:${port}`) + console.info(`CDN Server: http://localhost:${server.address().port}`) }) diff --git a/e2e/react-start/transform-asset-urls/tests/script-url-escaping.spec.ts b/e2e/react-start/transform-asset-urls/tests/script-url-escaping.spec.ts new file mode 100644 index 0000000000..22251df671 --- /dev/null +++ b/e2e/react-start/transform-asset-urls/tests/script-url-escaping.spec.ts @@ -0,0 +1,46 @@ +import { expect, test } from '@playwright/test' + +for (const [name, scriptUrl] of [ + [ + 'closing script tag', + '', endIndex) + const scriptCloseIndex = html.indexOf('', endIndex) + const bodyCloseIndex = html.indexOf('', scriptCloseIndex) + const htmlCloseIndex = html.indexOf('', bodyCloseIndex) + + expect(endIndex).toBeGreaterThan(-1) + expect(scriptOpenIndex).toBeGreaterThan(previousScriptCloseIndex) + expect(scriptCloseIndex).toBeGreaterThan(endIndex) + expect(payloadIndex).toBeGreaterThan(-1) + expect(payloadIndex).toBeLessThan(endIndex) + expect(html.slice(endIndex, scriptCloseIndex)).toContain(LATE_RECORD_CLOSE) + expect(scriptCloseIndex).toBeLessThan(bodyCloseIndex) + expect(bodyCloseIndex).toBeLessThan(htmlCloseIndex) +} + +async function verifyHydration( + page: Page, + { timeout = 10_000 }: { timeout?: number } = {}, +) { + const button = page.getByTestId('hydration-check-btn') + const status = page.getByTestId('hydration-status') + + await expect(button).toBeVisible() + await expect(async () => { + await button.click() + await expect(status).toHaveText('hydrated', { timeout: 100 }) + }).toPass({ timeout }) + + await expect(page.locator(STREAM_PART_SELECTOR)).toHaveCount(0) + await expect( + page.locator('script').filter({ hasText: STREAM_BOUNDARY_MARKER }), + ).toHaveCount(0) +} + +export { test } + +export const testWithHydration = test.extend({ + page: async ({ page }, use) => { + await use(page) + await verifyHydration(page) + }, +}) + +export { expect } diff --git a/e2e/streaming-ssr-fixtures/index.ts b/e2e/streaming-ssr-fixtures/index.ts new file mode 100644 index 0000000000..a70ef94459 --- /dev/null +++ b/e2e/streaming-ssr-fixtures/index.ts @@ -0,0 +1,381 @@ +export type SourceMarker = 'server' | 'client' + +export type ServerData = { + name: string + timestamp: number + source: 'server' +} + +export type DeferredMessage = { + message: string + source: SourceMarker +} + +export type QueryType = 'sync' | 'fast-async' | 'slow-async' + +export type QueryData = { + type: QueryType + id: number + value: string + source: SourceMarker +} + +export const deferredDataMessage = 'Deferred data loaded!' +export const deferredDataDelay = 1000 +export const deferredServerDelay = 800 +export const deferredImmediateName = 'Fast User' +export const deferredSlowName = 'Slow User' +export const deferredErrorMessage = 'Error in deferred object' + +export const fastSerialStaticData = 'This is static data' +export const fastSerialSmallValue = 'small-data' + +export const syncOnlyMessage = 'Hello from sync loader!' +export const syncOnlyItems = ['item-1', 'item-2', 'item-3'] as const + +export const slowRenderDeferredMessage = 'Deferred resolved!' +export const slowRenderDeferredDelay = 50 +export const slowRenderQuickName = 'Quick data' +export const slowRenderComponents = [ + 'Slow component 1', + 'Slow component 2', + 'Slow component 3', +] as const + +export const nestedLevelDelays = [200, 400, 600] as const +export const nestedPlainDelay = 300 +export const nestedPlainMessage = 'Plain deferred resolved!' + +export const streamPromiseValue = 'promise-resolved' +export const streamPromiseDelay = 150 +export const streamChunkDelay = 200 +export const streamChunks = Array.from({ length: 5 }, (_, i) => `chunk-${i}`) + +export const routerHtmlPayloadChars = 17 * 1024 * 1024 +export const routerHtmlPayloadChar = 'x' +export const routerHtmlPayloadDelay = 100 + +export const manyPromiseItems = [ + { + key: 'immediate1', + testId: 'immediate-1', + label: 'Immediate 1', + value: 'immediate-1', + delayMs: 0, + }, + { + key: 'immediate2', + testId: 'immediate-2', + label: 'Immediate 2', + value: 'immediate-2', + delayMs: 10, + }, + { + key: 'immediate3', + testId: 'immediate-3', + label: 'Immediate 3', + value: 'immediate-3', + delayMs: 20, + }, + { + key: 'fast1', + testId: 'fast-1', + label: 'Fast 1', + value: 'fast-1', + delayMs: 50, + }, + { + key: 'fast2', + testId: 'fast-2', + label: 'Fast 2', + value: 'fast-2', + delayMs: 75, + }, + { + key: 'fast3', + testId: 'fast-3', + label: 'Fast 3', + value: 'fast-3', + delayMs: 100, + }, + { + key: 'fast4', + testId: 'fast-4', + label: 'Fast 4', + value: 'fast-4', + delayMs: 125, + }, + { + key: 'medium1', + testId: 'medium-1', + label: 'Medium 1', + value: 'medium-1', + delayMs: 150, + }, + { + key: 'medium2', + testId: 'medium-2', + label: 'Medium 2', + value: 'medium-2', + delayMs: 200, + }, + { + key: 'medium3', + testId: 'medium-3', + label: 'Medium 3', + value: 'medium-3', + delayMs: 250, + }, + { + key: 'slow1', + testId: 'slow-1', + label: 'Slow 1', + value: 'slow-1', + delayMs: 300, + }, + { + key: 'slow2', + testId: 'slow-2', + label: 'Slow 2', + value: 'slow-2', + delayMs: 400, + }, + { + key: 'slow3', + testId: 'slow-3', + label: 'Slow 3', + value: 'slow-3', + delayMs: 500, + }, + { + key: 'verySlow1', + testId: 'very-slow-1', + label: 'Very Slow 1', + value: 'very-slow-1', + delayMs: 600, + }, + { + key: 'verySlow2', + testId: 'very-slow-2', + label: 'Very Slow 2', + value: 'very-slow-2', + delayMs: 800, + }, +] as const + +export const concurrentBatchCount = 5 +export const concurrentBatchDelays = [100, 200, 300] as const + +export const queryHeavyItems = [ + { + type: 'sync', + id: 1, + value: 'sync-value-1', + delayMs: 0, + testId: 'sync-query-1', + fallback: 'Loading sync 1...', + }, + { + type: 'sync', + id: 2, + value: 'sync-value-2', + delayMs: 0, + testId: 'sync-query-2', + fallback: 'Loading sync 2...', + }, + { + type: 'sync', + id: 3, + value: 'sync-value-3', + delayMs: 0, + testId: 'sync-query-3', + fallback: 'Loading sync 3...', + }, + { + type: 'fast-async', + id: 1, + value: 'fast-async-1', + delayMs: 50, + testId: 'fast-async-query-1', + fallback: 'Loading fast 1...', + }, + { + type: 'fast-async', + id: 2, + value: 'fast-async-2', + delayMs: 75, + testId: 'fast-async-query-2', + fallback: 'Loading fast 2...', + }, + { + type: 'fast-async', + id: 3, + value: 'fast-async-3', + delayMs: 100, + testId: 'fast-async-query-3', + fallback: 'Loading fast 3...', + }, + { + type: 'slow-async', + id: 1, + value: 'slow-async-1', + delayMs: 200, + testId: 'slow-async-query-1', + fallback: 'Loading slow 1...', + }, + { + type: 'slow-async', + id: 2, + value: 'slow-async-2', + delayMs: 300, + testId: 'slow-async-query-2', + fallback: 'Loading slow 2...', + }, + { + type: 'slow-async', + id: 3, + value: 'slow-async-3', + delayMs: 400, + testId: 'slow-async-query-3', + fallback: 'Loading slow 3...', + }, +] as const + +export function sourceMarker(): SourceMarker { + return typeof window === 'undefined' ? 'server' : 'client' +} + +export function delay(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)) +} + +export function makeServerData(name: string): ServerData { + return { + name, + timestamp: Date.now(), + source: 'server', + } +} + +export function makeDeferred(value: T, delayMs: number): Promise { + return new Promise((resolve) => setTimeout(() => resolve(value), delayMs)) +} + +export function makeDeferredMessage( + message: string, + delayMs: number, +): Promise { + return makeDeferred({ message, source: sourceMarker() }, delayMs) +} + +export function makeFastSerialSmallData() { + return { + value: fastSerialSmallValue, + timestamp: Date.now(), + source: 'server' as const, + } +} + +export function makeSyncOnlyData() { + return { + message: syncOnlyMessage, + timestamp: Date.now(), + items: syncOnlyItems, + source: sourceMarker(), + } +} + +export function makeLevelData(level: number) { + return { level, timestamp: Date.now() } +} + +export function makeQueryData(item: { + type: QueryType + id: number + value: string +}): QueryData { + return { + type: item.type, + id: item.id, + value: item.value, + source: sourceMarker(), + } +} + +export function createManyPromises() { + return Object.fromEntries( + manyPromiseItems.map((item) => [ + item.key, + makeDeferred(item.value, item.delayMs), + ]), + ) as Record<(typeof manyPromiseItems)[number]['key'], Promise> +} + +export function createConcurrentPromises( + count: number, + delayMs: number, +): Array> { + const sharedPromise = delay(delayMs) + return Array.from({ length: count }, (_, i) => + sharedPromise.then(() => `concurrent-${i + 1}`), + ) +} + +export function createConcurrentLoaderData() { + const batch1 = createConcurrentPromises( + concurrentBatchCount, + concurrentBatchDelays[0], + ) + const batch2 = createConcurrentPromises( + concurrentBatchCount, + concurrentBatchDelays[1], + ) + const batch3 = createConcurrentPromises( + concurrentBatchCount, + concurrentBatchDelays[2], + ) + + return { + concurrent1_1: batch1[0], + concurrent1_2: batch1[1], + concurrent1_3: batch1[2], + concurrent1_4: batch1[3], + concurrent1_5: batch1[4], + concurrent2_1: batch2[0], + concurrent2_2: batch2[1], + concurrent2_3: batch2[2], + concurrent2_4: batch2[3], + concurrent2_5: batch2[4], + concurrent3_1: batch3[0], + concurrent3_2: batch3[1], + concurrent3_3: batch3[2], + concurrent3_4: batch3[3], + concurrent3_5: batch3[4], + } +} + +export function createStreamPromise(): Promise { + return makeDeferred(streamPromiseValue, streamPromiseDelay) +} + +export function createChunkStream(): ReadableStream { + return new ReadableStream({ + async start(controller) { + for (const chunk of streamChunks) { + await delay(streamChunkDelay) + controller.enqueue(chunk) + } + controller.close() + }, + }) +} + +export function createRouterHtmlPayload() { + return makeDeferred( + { + value: routerHtmlPayloadChar.repeat(routerHtmlPayloadChars), + source: sourceMarker(), + }, + routerHtmlPayloadDelay, + ) +} diff --git a/e2e/streaming-ssr-specs/client-navigation.ts b/e2e/streaming-ssr-specs/client-navigation.ts new file mode 100644 index 0000000000..759f8e0282 --- /dev/null +++ b/e2e/streaming-ssr-specs/client-navigation.ts @@ -0,0 +1,372 @@ +import { expect, test, testWithHydration } from '../streaming-ssr-assertions' + +test.describe('Client-side navigation between all routes', () => { + test.beforeEach(async ({ page }) => { + // Start from home page + await page.goto('/') + await page.waitForLoadState('networkidle') + }) + + test('home -> sync-only -> home works', async ({ page }) => { + // Navigate to sync-only + await page + .getByRole('navigation') + .getByRole('link', { name: 'Sync Only' }) + .click() + await expect(page).toHaveURL('/sync-only') + await expect(page.getByTestId('sync-message')).toBeVisible() + + // Navigate back to home + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + await expect(page.getByTestId('index-title')).toBeVisible() + }) + + test('home -> deferred -> home works', async ({ page }) => { + // Navigate to deferred (use exact: true to avoid matching "Nested Deferred") + await page + .getByRole('navigation') + .getByRole('link', { name: 'Deferred', exact: true }) + .click() + await expect(page).toHaveURL('/deferred') + await expect(page.getByTestId('immediate-data')).toBeVisible() + + // Wait for deferred data + await expect(page.getByTestId('deferred-data')).toBeVisible({ + timeout: 5000, + }) + + // Navigate back to home + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + }) + + test('home -> stream -> home works (no stream locking error)', async ({ + page, + }) => { + // This test specifically validates the ReadableStream locking fix + // Console errors are monitored by the fixture automatically + + // Navigate to stream + await page + .getByRole('navigation') + .getByRole('link', { name: 'Stream' }) + .click() + await expect(page).toHaveURL('/stream') + + // Wait for stream to start (at least one chunk or promise resolved) + await expect(page.getByTestId('promise-data')).toBeVisible({ + timeout: 5000, + }) + + // Navigate back without waiting for stream completion. + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + }) + + test('home -> stream -> wait for completion -> home works', async ({ + page, + }) => { + // Navigate to stream + await page + .getByRole('navigation') + .getByRole('link', { name: 'Stream' }) + .click() + await expect(page).toHaveURL('/stream') + + // Wait for stream to complete + await expect(page.getByTestId('stream-complete')).toBeVisible({ + timeout: 10000, + }) + + // Navigate back to home + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + await expect(page.getByTestId('index-title')).toBeVisible() + }) + + test('home -> stream -> home -> stream again works (fresh stream each time)', async ({ + page, + }) => { + // Console errors are monitored by the fixture automatically + + // First navigation to stream + await page + .getByRole('navigation') + .getByRole('link', { name: 'Stream' }) + .click() + await expect(page).toHaveURL('/stream') + await expect(page.getByTestId('promise-data')).toBeVisible({ + timeout: 5000, + }) + + // Navigate back to home + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + + // Second navigation to stream - should get fresh stream without errors + await page + .getByRole('navigation') + .getByRole('link', { name: 'Stream' }) + .click() + await expect(page).toHaveURL('/stream') + + // Wait for stream to complete + await expect(page.getByTestId('stream-complete')).toBeVisible({ + timeout: 10000, + }) + + // Verify all chunks are present + await expect(page.getByTestId('stream-chunk-0')).toBeVisible() + await expect(page.getByTestId('stream-chunk-4')).toBeVisible() + }) + + test('home -> fast-serial -> home works', async ({ page }) => { + await page + .getByRole('navigation') + .getByRole('link', { name: 'Fast Serial' }) + .click() + await expect(page).toHaveURL('/fast-serial') + await expect(page.getByTestId('server-data')).toBeVisible() + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + }) + + test('home -> slow-render -> home works', async ({ page }) => { + await page + .getByRole('navigation') + .getByRole('link', { name: 'Slow Render' }) + .click() + await expect(page).toHaveURL('/slow-render') + await expect(page.getByTestId('quick-data')).toBeVisible() + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + }) + + test('home -> nested-deferred -> home works', async ({ page }) => { + await page + .getByRole('navigation') + .getByRole('link', { name: 'Nested Deferred' }) + .click() + await expect(page).toHaveURL('/nested-deferred') + + // Wait for all levels to load + await expect(page.getByTestId('level3-data')).toBeVisible({ timeout: 5000 }) + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + }) + + test('navigation without waiting for route data works', async ({ page }) => { + // Console errors are monitored by the fixture automatically + + // Change routes as soon as each URL updates, without waiting for route data. + await page + .getByRole('navigation') + .getByRole('link', { name: 'Sync Only' }) + .click() + await expect(page).toHaveURL('/sync-only') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Deferred', exact: true }) + .click() + await expect(page).toHaveURL('/deferred') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Stream' }) + .click() + await expect(page).toHaveURL('/stream') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Fast Serial' }) + .click() + await expect(page).toHaveURL('/fast-serial') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Slow Render' }) + .click() + await expect(page).toHaveURL('/slow-render') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Nested Deferred' }) + .click() + await expect(page).toHaveURL('/nested-deferred') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + }) +}) + +test.describe('Direct navigation followed by client navigation', () => { + test('direct to stream -> client nav to deferred works', async ({ page }) => { + // Direct navigation to stream + await page.goto('/stream') + await expect(page.getByTestId('promise-data')).toBeVisible({ + timeout: 5000, + }) + + // Client navigation to deferred (use exact: true) + await page + .getByRole('navigation') + .getByRole('link', { name: 'Deferred', exact: true }) + .click() + await expect(page).toHaveURL('/deferred') + await expect(page.getByTestId('immediate-data')).toBeVisible() + }) + + test('direct to deferred -> client nav to stream works', async ({ page }) => { + // Console errors are monitored by the fixture automatically + + // Direct navigation to deferred + await page.goto('/deferred') + await expect(page.getByTestId('immediate-data')).toBeVisible() + + // Client navigation to stream + await page + .getByRole('navigation') + .getByRole('link', { name: 'Stream' }) + .click() + await expect(page).toHaveURL('/stream') + await expect(page.getByTestId('stream-complete')).toBeVisible({ + timeout: 10000, + }) + }) + + test('direct to sync-only -> client nav to all routes works', async ({ + page, + }) => { + await page.goto('/sync-only') + await expect(page.getByTestId('sync-message')).toBeVisible() + + // Navigate through all routes + await page + .getByRole('navigation') + .getByRole('link', { name: 'Deferred', exact: true }) + .click() + await expect(page).toHaveURL('/deferred') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Stream' }) + .click() + await expect(page).toHaveURL('/stream') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Fast Serial' }) + .click() + await expect(page).toHaveURL('/fast-serial') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Home' }) + .click() + await expect(page).toHaveURL('/') + }) +}) + +testWithHydration.describe('Hydration after client navigation', () => { + testWithHydration( + 'interactive elements work after navigating to deferred', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Deferred', exact: true }) + .click() + await expect(page).toHaveURL('/deferred') + + // Wait for the page to be fully loaded + await expect(page.getByTestId('immediate-data')).toBeVisible() + }, + ) + + testWithHydration( + 'interactive elements work after navigating to fast-serial', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Fast Serial' }) + .click() + await expect(page).toHaveURL('/fast-serial') + + // Wait for page to load + await expect(page.getByTestId('server-data')).toBeVisible() + }, + ) + + testWithHydration( + 'interactive elements work after navigating to nested-deferred', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Nested Deferred' }) + .click() + await expect(page).toHaveURL('/nested-deferred') + + // Wait for page to load + await expect(page.getByTestId('plain-deferred')).toBeVisible({ + timeout: 5000, + }) + }, + ) + + testWithHydration( + 'interactive elements work after navigating to slow-render', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + await page + .getByRole('navigation') + .getByRole('link', { name: 'Slow Render' }) + .click() + await expect(page).toHaveURL('/slow-render') + + // Wait for page to load (slow-render has blocking loops) + await expect(page.getByTestId('quick-data')).toBeVisible() + }, + ) +}) diff --git a/e2e/streaming-ssr-specs/concurrent.ts b/e2e/streaming-ssr-specs/concurrent.ts new file mode 100644 index 0000000000..ef14f80367 --- /dev/null +++ b/e2e/streaming-ssr-specs/concurrent.ts @@ -0,0 +1,86 @@ +import { expect, test, testWithHydration } from '../streaming-ssr-assertions' + +test.describe('Concurrent promise resolution (15 promises in 3 batches)', () => { + test('all concurrent promises resolve correctly', async ({ page }) => { + await page.goto('/concurrent') + + // Batch 1 (5 promises at 100ms) + await expect(page.getByTestId('concurrent-1-1')).toContainText( + 'concurrent-1', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-1-2')).toContainText( + 'concurrent-2', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-1-3')).toContainText( + 'concurrent-3', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-1-4')).toContainText( + 'concurrent-4', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-1-5')).toContainText( + 'concurrent-5', + { timeout: 5000 }, + ) + + // Batch 2 (5 promises at 200ms) + await expect(page.getByTestId('concurrent-2-1')).toContainText( + 'concurrent-1', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-2-2')).toContainText( + 'concurrent-2', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-2-3')).toContainText( + 'concurrent-3', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-2-4')).toContainText( + 'concurrent-4', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-2-5')).toContainText( + 'concurrent-5', + { timeout: 5000 }, + ) + + // Batch 3 (5 promises at 300ms) + await expect(page.getByTestId('concurrent-3-1')).toContainText( + 'concurrent-1', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-3-2')).toContainText( + 'concurrent-2', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-3-3')).toContainText( + 'concurrent-3', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-3-4')).toContainText( + 'concurrent-4', + { timeout: 5000 }, + ) + await expect(page.getByTestId('concurrent-3-5')).toContainText( + 'concurrent-5', + { timeout: 5000 }, + ) + }) + + testWithHydration( + 'hydration works with concurrent resolutions', + async ({ page }) => { + await page.goto('/concurrent') + await page.waitForLoadState('networkidle') + + // Wait for all batches + await expect(page.getByTestId('concurrent-3-5')).toBeVisible({ + timeout: 5000, + }) + }, + ) +}) diff --git a/e2e/streaming-ssr-specs/deferred-rejection.ts b/e2e/streaming-ssr-specs/deferred-rejection.ts new file mode 100644 index 0000000000..3e944b1c0c --- /dev/null +++ b/e2e/streaming-ssr-specs/deferred-rejection.ts @@ -0,0 +1,21 @@ +import { expect, test } from '../streaming-ssr-assertions' + +test.use({ + whitelistErrors: ['Error in deferred object'], +}) + +test('rejected deferred Await renders the route error boundary without killing SSR', async ({ + page, +}) => { + await page.goto('/deferred-rejection') + + await expect(page.getByTestId('deferred-error-boundary')).toContainText( + 'Error in deferred object', + { timeout: 5000 }, + ) + + await page.goto('/sync-only') + await expect(page.getByTestId('sync-message')).toContainText( + 'Hello from sync loader!', + ) +}) diff --git a/e2e/streaming-ssr-specs/deferred.ts b/e2e/streaming-ssr-specs/deferred.ts new file mode 100644 index 0000000000..abece0b43e --- /dev/null +++ b/e2e/streaming-ssr-specs/deferred.ts @@ -0,0 +1,113 @@ +import { + expect, + expectDeferredRouteResponseOrder, + test, + testWithHydration, +} from '../streaming-ssr-assertions' + +test.describe('Deferred data streaming', () => { + test('finishes the router stream after renderer output', async ({ + baseURL, + }) => { + await expectDeferredRouteResponseOrder(baseURL) + }) + + test('renders immediate and deferred server data', async ({ page }) => { + await page.goto('/deferred') + + // Immediate loader data is rendered. + await expect(page.getByTestId('immediate-data')).toBeVisible() + await expect(page.getByTestId('immediate-data')).toContainText( + 'Immediate: Fast User', + ) + + // Verify immediate data came from server + await expect(page.getByTestId('immediate-source')).toContainText( + 'Immediate source: server', + ) + await expect(page.getByTestId('loader-source')).toContainText( + 'Loader source: server', + ) + + // Deferred data should eventually appear with server source + await expect(page.getByTestId('deferred-data')).toContainText( + 'Deferred data loaded!', + { timeout: 5000 }, + ) + await expect(page.getByTestId('deferred-data')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + await expect(page.getByTestId('deferred-server-data')).toContainText( + 'Server: Slow User', + { timeout: 5000 }, + ) + await expect(page.getByTestId('deferred-server-data')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + }) + + testWithHydration( + 'hydration works - interactive elements respond', + async ({ page }) => { + await page.goto('/deferred') + await page.waitForLoadState('networkidle') + + // Wait for all deferred content to load + await expect(page.getByTestId('deferred-data')).toBeVisible({ + timeout: 5000, + }) + + // Verify all data came from server after hydration + await expect(page.getByTestId('loader-source')).toContainText( + 'Loader source: server', + ) + await expect(page.getByTestId('deferred-data')).toContainText( + 'source: server', + ) + }, + ) + + test('client-side navigation to deferred route works', async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate via client-side routing using nav link + await page.getByRole('link', { name: 'Deferred' }).first().click() + await expect(page).toHaveURL('/deferred') + + // Data should load + await expect(page.getByTestId('immediate-data')).toContainText('Fast User') + await expect(page.getByTestId('deferred-data')).toContainText( + 'Deferred data loaded!', + { timeout: 5000 }, + ) + }) + + test('all data sources are server', async ({ page }) => { + await page.goto('/deferred') + + // Wait for all deferred content + await expect(page.getByTestId('deferred-data')).toBeVisible({ + timeout: 5000, + }) + await expect(page.getByTestId('deferred-server-data')).toBeVisible({ + timeout: 5000, + }) + + // Count all elements showing 'server' source - should be 4: + // 1. immediate-source + // 2. loader-source + // 3. deferred-data (contains "source: server") + // 4. deferred-server-data (contains "source: server") + await expect(page.getByTestId('immediate-source')).toContainText('server') + await expect(page.getByTestId('loader-source')).toContainText('server') + await expect(page.getByTestId('deferred-data')).toContainText( + 'source: server', + ) + await expect(page.getByTestId('deferred-server-data')).toContainText( + 'source: server', + ) + }) +}) diff --git a/e2e/streaming-ssr-specs/fast-serial.ts b/e2e/streaming-ssr-specs/fast-serial.ts new file mode 100644 index 0000000000..03201f0a55 --- /dev/null +++ b/e2e/streaming-ssr-specs/fast-serial.ts @@ -0,0 +1,74 @@ +import { + expect, + expectRouterHydrationMarkers, + test, + testWithHydration, +} from '../streaming-ssr-assertions' + +test.describe('Fast serialization (serialization completes before render)', () => { + test('initial HTML contains router bootstrap + barrier', async ({ page }) => { + let responseHtml = '' + await page.route('/fast-serial', async (route) => { + const response = await route.fetch() + responseHtml = await response.text() + await route.fulfill({ response }) + }) + + await page.goto('/fast-serial') + await expect(page.getByTestId('server-data')).toBeVisible() + + expectRouterHydrationMarkers(responseHtml) + }) + + test('renders all server data', async ({ page }) => { + await page.goto('/fast-serial') + await page.waitForLoadState('networkidle') + + // All data should be visible + await expect(page.getByTestId('server-data')).toContainText('small-data') + await expect(page.getByTestId('static-data')).toContainText( + 'This is static data', + ) + await expect(page.getByTestId('loader-timestamp')).toBeVisible() + + // Verify the loader and server function ran during SSR. + await expect(page.getByTestId('loader-source')).toContainText( + 'Loader source: server', + ) + await expect(page.getByTestId('server-fn-source')).toContainText( + 'Server function source: server', + ) + }) + + testWithHydration('hydration works correctly', async ({ page }) => { + await page.goto('/fast-serial') + await page.waitForLoadState('networkidle') + + // Verify data came from server after hydration + await expect(page.getByTestId('loader-source')).toContainText( + 'Loader source: server', + ) + }) + + test('direct navigation renders correctly', async ({ page }) => { + // Direct navigation (SSR) + await page.goto('/fast-serial') + + // Should render without errors and show server source + await expect(page.getByTestId('server-data')).toBeVisible() + await expect(page.getByTestId('loader-source')).toContainText( + 'Loader source: server', + ) + }) + + test('client-side navigation works', async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate via nav link + await page.getByRole('link', { name: 'Fast Serial' }).first().click() + await expect(page).toHaveURL('/fast-serial') + + await expect(page.getByTestId('server-data')).toContainText('small-data') + }) +}) diff --git a/e2e/streaming-ssr-specs/home.ts b/e2e/streaming-ssr-specs/home.ts new file mode 100644 index 0000000000..d85e19bfa7 --- /dev/null +++ b/e2e/streaming-ssr-specs/home.ts @@ -0,0 +1,34 @@ +import { expect, test, testWithHydration } from '../streaming-ssr-assertions' + +test.describe('Home page', () => { + testWithHydration( + 'renders index page with all navigation links', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + await expect(page.getByTestId('index-title')).toContainText( + 'Streaming SSR Test Scenarios', + ) + // Check links exist (they're in the nav and the body) + await expect( + page.getByRole('link', { name: 'Deferred' }).first(), + ).toBeVisible() + await expect( + page.getByRole('link', { name: 'Stream' }).first(), + ).toBeVisible() + }, + ) + + testWithHydration( + 'navigation from home to routes works', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Use the link in the content (not nav) + await page.getByTestId('link-deferred').click() + await expect(page).toHaveURL('/deferred') + }, + ) +}) diff --git a/e2e/streaming-ssr-specs/many-promises.ts b/e2e/streaming-ssr-specs/many-promises.ts new file mode 100644 index 0000000000..768859c7e4 --- /dev/null +++ b/e2e/streaming-ssr-specs/many-promises.ts @@ -0,0 +1,82 @@ +import { expect, test, testWithHydration } from '../streaming-ssr-assertions' + +test.describe('Many promises streaming (15 deferred)', () => { + test('all 15 promises eventually resolve', async ({ page }) => { + await page.goto('/many-promises') + + // Immediate group (0-20ms) + await expect(page.getByTestId('immediate-1')).toContainText('immediate-1', { + timeout: 5000, + }) + await expect(page.getByTestId('immediate-2')).toContainText('immediate-2', { + timeout: 5000, + }) + await expect(page.getByTestId('immediate-3')).toContainText('immediate-3', { + timeout: 5000, + }) + + // Fast group (50-125ms) + await expect(page.getByTestId('fast-1')).toContainText('fast-1', { + timeout: 5000, + }) + await expect(page.getByTestId('fast-2')).toContainText('fast-2', { + timeout: 5000, + }) + await expect(page.getByTestId('fast-3')).toContainText('fast-3', { + timeout: 5000, + }) + await expect(page.getByTestId('fast-4')).toContainText('fast-4', { + timeout: 5000, + }) + + // Medium group (150-250ms) + await expect(page.getByTestId('medium-1')).toContainText('medium-1', { + timeout: 5000, + }) + await expect(page.getByTestId('medium-2')).toContainText('medium-2', { + timeout: 5000, + }) + await expect(page.getByTestId('medium-3')).toContainText('medium-3', { + timeout: 5000, + }) + + // Slow group (300-500ms) + await expect(page.getByTestId('slow-1')).toContainText('slow-1', { + timeout: 5000, + }) + await expect(page.getByTestId('slow-2')).toContainText('slow-2', { + timeout: 5000, + }) + await expect(page.getByTestId('slow-3')).toContainText('slow-3', { + timeout: 5000, + }) + + // Very slow group (600-800ms) + await expect(page.getByTestId('very-slow-1')).toContainText('very-slow-1', { + timeout: 5000, + }) + await expect(page.getByTestId('very-slow-2')).toContainText('very-slow-2', { + timeout: 5000, + }) + }) + + testWithHydration('hydration works with many promises', async ({ page }) => { + await page.goto('/many-promises') + await page.waitForLoadState('networkidle') + + // Wait for all promises to resolve + await expect(page.getByTestId('very-slow-2')).toBeVisible({ timeout: 5000 }) + }) + + test('client-side navigation works', async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate via nav link + await page.getByRole('link', { name: 'Many Promises' }).click() + await expect(page).toHaveURL('/many-promises') + + // All promises should eventually resolve + await expect(page.getByTestId('very-slow-2')).toBeVisible({ timeout: 5000 }) + }) +}) diff --git a/e2e/streaming-ssr-specs/nested-deferred.ts b/e2e/streaming-ssr-specs/nested-deferred.ts new file mode 100644 index 0000000000..0146a23162 --- /dev/null +++ b/e2e/streaming-ssr-specs/nested-deferred.ts @@ -0,0 +1,52 @@ +import { expect, test, testWithHydration } from '../streaming-ssr-assertions' + +test.describe('Nested deferred (multiple levels of deferred data)', () => { + test('all levels of deferred data eventually resolve', async ({ page }) => { + await page.goto('/nested-deferred') + + // All deferred values should eventually resolve. + await expect(page.getByTestId('plain-deferred')).toContainText( + 'Plain deferred resolved!', + { timeout: 5000 }, + ) + + await expect(page.getByTestId('level1-data')).toContainText('Level 1:', { + timeout: 5000, + }) + + await expect(page.getByTestId('level2-data')).toContainText('Level 2:', { + timeout: 5000, + }) + + await expect(page.getByTestId('level3-data')).toContainText('Level 3:', { + timeout: 5000, + }) + }) + + testWithHydration( + 'hydration works with nested deferred', + async ({ page }) => { + await page.goto('/nested-deferred') + await page.waitForLoadState('networkidle') + + // Wait for all data + await expect(page.getByTestId('level3-data')).toBeVisible({ + timeout: 10000, + }) + }, + ) + + test('client-side navigation works', async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate via nav link + await page.getByRole('link', { name: 'Nested Deferred' }).first().click() + await expect(page).toHaveURL('/nested-deferred') + + // All levels should eventually render + await expect(page.getByTestId('level3-data')).toBeVisible({ + timeout: 10000, + }) + }) +}) diff --git a/e2e/streaming-ssr-specs/preview-streaming.ts b/e2e/streaming-ssr-specs/preview-streaming.ts new file mode 100644 index 0000000000..5087dff730 --- /dev/null +++ b/e2e/streaming-ssr-specs/preview-streaming.ts @@ -0,0 +1,13 @@ +import { + expectDeferredRouteResponseOrder, + test, +} from '../streaming-ssr-assertions' + +test.skip( + process.env.MODE !== 'preview', + 'Only runs against vite preview: pnpm test:e2e:preview', +) + +test('vite preview preserves deferred HTML order', async ({ baseURL }) => { + await expectDeferredRouteResponseOrder(baseURL) +}) diff --git a/e2e/streaming-ssr-specs/query-heavy.ts b/e2e/streaming-ssr-specs/query-heavy.ts new file mode 100644 index 0000000000..b33a64f366 --- /dev/null +++ b/e2e/streaming-ssr-specs/query-heavy.ts @@ -0,0 +1,142 @@ +import { + expect, + expectQueryHeavyRouteStreamOrder, + test, + testWithHydration, +} from '../streaming-ssr-assertions' + +test.describe('Query heavy route (9 queries)', () => { + test('emits the complete router stream before document closes', async ({ + baseURL, + }) => { + await expectQueryHeavyRouteStreamOrder(baseURL) + }) + + test('all queries resolve with server data', async ({ page }) => { + await page.goto('/query-heavy') + + // Sync queries should show server source + await expect(page.getByTestId('sync-query-1')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + await expect(page.getByTestId('sync-query-2')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + await expect(page.getByTestId('sync-query-3')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + + // Fast async queries should show server source + await expect(page.getByTestId('fast-async-query-1')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + await expect(page.getByTestId('fast-async-query-2')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + await expect(page.getByTestId('fast-async-query-3')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + + // Slow async queries should show server source + await expect(page.getByTestId('slow-async-query-1')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + await expect(page.getByTestId('slow-async-query-2')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + await expect(page.getByTestId('slow-async-query-3')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + }) + + test('sync queries have correct values', async ({ page }) => { + await page.goto('/query-heavy') + + await expect(page.getByTestId('sync-query-1')).toContainText('sync-value-1') + await expect(page.getByTestId('sync-query-2')).toContainText('sync-value-2') + await expect(page.getByTestId('sync-query-3')).toContainText('sync-value-3') + }) + + test('async queries have correct values', async ({ page }) => { + await page.goto('/query-heavy') + + await expect(page.getByTestId('fast-async-query-1')).toContainText( + 'fast-async-1', + { timeout: 5000 }, + ) + await expect(page.getByTestId('fast-async-query-2')).toContainText( + 'fast-async-2', + { timeout: 5000 }, + ) + await expect(page.getByTestId('fast-async-query-3')).toContainText( + 'fast-async-3', + { timeout: 5000 }, + ) + + await expect(page.getByTestId('slow-async-query-1')).toContainText( + 'slow-async-1', + { timeout: 5000 }, + ) + await expect(page.getByTestId('slow-async-query-2')).toContainText( + 'slow-async-2', + { timeout: 5000 }, + ) + await expect(page.getByTestId('slow-async-query-3')).toContainText( + 'slow-async-3', + { timeout: 5000 }, + ) + }) + + testWithHydration('hydration works with many queries', async ({ page }) => { + await page.goto('/query-heavy') + await page.waitForLoadState('networkidle') + + // Wait for all queries to resolve + await expect(page.getByTestId('slow-async-query-3')).toBeVisible({ + timeout: 5000, + }) + }) + + test('client-side navigation works', async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate via nav link + await page.getByRole('link', { name: 'Query Heavy' }).click() + await expect(page).toHaveURL('/query-heavy') + + // All queries should eventually resolve (on client) + await expect(page.getByTestId('slow-async-query-3')).toBeVisible({ + timeout: 5000, + }) + }) + + test('server query data hydrates without client refetch', async ({ + page, + }) => { + // If hydration missed the server data, these queries would re-execute on + // the client and show "client" as their source. + await page.goto('/query-heavy') + + // Wait for all queries + await expect(page.getByTestId('slow-async-query-3')).toBeVisible({ + timeout: 5000, + }) + + // Verify that all server results hydrated without a client refetch. + const serverSourceCount = await page + .locator('[data-testid*="query-"]') + .filter({ hasText: 'source: server' }) + .count() + expect(serverSourceCount).toBe(9) + }) +}) diff --git a/e2e/streaming-ssr-specs/slow-render.ts b/e2e/streaming-ssr-specs/slow-render.ts new file mode 100644 index 0000000000..117559701e --- /dev/null +++ b/e2e/streaming-ssr-specs/slow-render.ts @@ -0,0 +1,71 @@ +import { expect, test, testWithHydration } from '../streaming-ssr-assertions' + +test.describe('Slow render (render takes longer than serialization)', () => { + test('all data eventually renders with server source', async ({ page }) => { + await page.goto('/slow-render') + await page.waitForLoadState('networkidle') + + // Quick data should be available with server source + await expect(page.getByTestId('quick-data')).toContainText('Quick:') + await expect(page.getByTestId('quick-source')).toContainText( + 'Quick data source: server', + ) + await expect(page.getByTestId('loader-source')).toContainText( + 'Loader source: server', + ) + + // Deferred data should resolve with server source + await expect(page.getByTestId('deferred-resolved')).toContainText( + 'Deferred resolved!', + { timeout: 5000 }, + ) + await expect(page.getByTestId('deferred-resolved')).toContainText( + 'source: server', + { timeout: 5000 }, + ) + + // Slow components should have rendered + await expect(page.getByTestId('slow-component-1')).toBeVisible() + await expect(page.getByTestId('slow-component-2')).toBeVisible() + await expect(page.getByTestId('slow-component-3')).toBeVisible() + }) + + testWithHydration('hydration works after slow render', async ({ page }) => { + await page.goto('/slow-render') + await page.waitForLoadState('networkidle') + + // Wait for content and verify server source + await expect(page.getByTestId('slow-component-1')).toBeVisible() + await expect(page.getByTestId('loader-source')).toContainText( + 'Loader source: server', + ) + }) + + test('client-side navigation works', async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate via nav link + await page.getByRole('link', { name: 'Slow Render' }).first().click() + await expect(page).toHaveURL('/slow-render') + + await expect(page.getByTestId('quick-data')).toBeVisible({ timeout: 10000 }) + }) + + test('all data sources are server', async ({ page }) => { + await page.goto('/slow-render') + await page.waitForLoadState('networkidle') + + // Wait for deferred content + await expect(page.getByTestId('deferred-resolved')).toBeVisible({ + timeout: 5000, + }) + + // Verify all sources are server + await expect(page.getByTestId('quick-source')).toContainText('server') + await expect(page.getByTestId('loader-source')).toContainText('server') + await expect(page.getByTestId('deferred-resolved')).toContainText( + 'source: server', + ) + }) +}) diff --git a/e2e/streaming-ssr-specs/stream.ts b/e2e/streaming-ssr-specs/stream.ts new file mode 100644 index 0000000000..ee61f170de --- /dev/null +++ b/e2e/streaming-ssr-specs/stream.ts @@ -0,0 +1,55 @@ +import { expect, test, testWithHydration } from '../streaming-ssr-assertions' + +const expectedStreamChunks = [ + 'chunk-0', + 'chunk-1', + 'chunk-2', + 'chunk-3', + 'chunk-4', +] + +test.describe('ReadableStream deserialization', () => { + testWithHydration('promise data deserializes correctly', async ({ page }) => { + await page.goto('/stream') + + await expect(page.getByTestId('promise-data')).toContainText( + 'promise-resolved', + { timeout: 5000 }, + ) + }) + + testWithHydration( + 'stream chunks deserialize in source order', + async ({ page }) => { + await page.goto('/stream') + + await expect(page.getByTestId('stream-complete')).toBeVisible({ + timeout: 10000, + }) + + const chunks = page + .getByTestId('stream-data') + .locator('[data-testid^="stream-chunk-"]') + await expect(chunks).toHaveText(expectedStreamChunks) + + // This browser assertion covers deserialization and source order. The + // raw `/deferred` assertion covers server-response and router ordering. + }, + ) + + testWithHydration( + 'client-side navigation to stream route works', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + + // Navigate via nav link + await page.getByRole('link', { name: 'Stream' }).first().click() + await expect(page).toHaveURL('/stream') + + await expect(page.getByTestId('stream-complete')).toBeVisible({ + timeout: 10000, + }) + }, + ) +}) diff --git a/e2e/streaming-ssr-specs/sync-only.ts b/e2e/streaming-ssr-specs/sync-only.ts new file mode 100644 index 0000000000..9850265109 --- /dev/null +++ b/e2e/streaming-ssr-specs/sync-only.ts @@ -0,0 +1,80 @@ +import { + expect, + expectRouterHydrationMarkers, + test, + testWithHydration, +} from '../streaming-ssr-assertions' + +/** + * Tests for synchronous serialization - no deferred data, no streaming. + * This is the most common case where all loader data is immediately available. + * The hydration scripts should be included in the initial HTML response. + */ + +test('Sync-only route renders with loader data', async ({ page }) => { + await page.goto('/sync-only') + + // Verify the page content is rendered + await expect(page.getByTestId('sync-title')).toContainText( + 'Synchronous Serialization Test', + ) + await expect(page.getByTestId('sync-message')).toContainText( + 'Hello from sync loader!', + ) + + // Verify loader data items are rendered + await expect(page.getByTestId('sync-item-item-1')).toBeVisible() + await expect(page.getByTestId('sync-item-item-2')).toBeVisible() + await expect(page.getByTestId('sync-item-item-3')).toBeVisible() + + // Verify the loader ran during SSR. + await expect(page.getByTestId('sync-source')).toContainText('Source: server') +}) + +testWithHydration('Sync-only route hydrates correctly', async ({ page }) => { + await page.goto('/sync-only') + + // Verify client-side navigation works (proves hydration succeeded) + await page.getByRole('navigation').getByRole('link', { name: 'Home' }).click() + await expect(page.getByTestId('index-title')).toBeVisible() + + // Navigate back to sync-only via client-side navigation (use nav link to be specific) + await page + .getByRole('navigation') + .getByRole('link', { name: 'Sync Only' }) + .click() + await expect(page.getByTestId('sync-title')).toBeVisible() +}) + +test('Sync-only route has bootstrap scripts in initial HTML', async ({ + page, +}) => { + // Intercept the response to check the raw HTML + let responseHtml = '' + await page.route('/sync-only', async (route) => { + const response = await route.fetch() + responseHtml = await response.text() + await route.fulfill({ response }) + }) + + await page.goto('/sync-only') + + // Wait for page to load + await expect(page.getByTestId('sync-title')).toBeVisible() + + // Bootstrap, end record, and the boundary rendered by . + expectRouterHydrationMarkers(responseHtml) +}) + +test('Navigating to sync-only from home page', async ({ page }) => { + await page.goto('/') + + await page.getByTestId('link-sync-only').click() + + await expect(page.getByTestId('sync-title')).toContainText( + 'Synchronous Serialization Test', + ) + await expect(page.getByTestId('sync-message')).toContainText( + 'Hello from sync loader!', + ) +}) diff --git a/e2e/vue-router/basepath-file-based/package.json b/e2e/vue-router/basepath-file-based/package.json index 0ed990a8ff..3af9176e83 100644 --- a/e2e/vue-router/basepath-file-based/package.json +++ b/e2e/vue-router/basepath-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -17,7 +17,7 @@ "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, @@ -28,6 +28,6 @@ "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", "vite": "^8.0.14", - "vue-tsc": "^3.1.5" + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-router/basepath-file-based/playwright.config.ts b/e2e/vue-router/basepath-file-based/playwright.config.ts index 6069bbe59f..4eead86444 100644 --- a/e2e/vue-router/basepath-file-based/playwright.config.ts +++ b/e2e/vue-router/basepath-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/basepath-file-based/src/routeTree.gen.ts b/e2e/vue-router/basepath-file-based/src/routeTree.gen.ts index 82b561baf1..75b8119285 100644 --- a/e2e/vue-router/basepath-file-based/src/routeTree.gen.ts +++ b/e2e/vue-router/basepath-file-based/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/e2e/vue-router/basepath-file-based/tests/setup/global.setup.ts b/e2e/vue-router/basepath-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basepath-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basepath-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/basepath-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basepath-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic-esbuild-file-based/package.json b/e2e/vue-router/basic-esbuild-file-based/package.json index e27d749899..a51cf9149c 100644 --- a/e2e/vue-router/basic-esbuild-file-based/package.json +++ b/e2e/vue-router/basic-esbuild-file-based/package.json @@ -7,14 +7,14 @@ "build": "node src/esbuild.run.js build && vue-tsc --noEmit", "preview": "node src/esbuild.run.js preview", "start": "pnpm dev", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "postcss": "^8.5.1", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "vue": "^3.5.16", "zod": "^4.4.3" }, @@ -27,8 +27,9 @@ "esbuild": "^0.27.4", "esbuild-plugin-vue3": "^0.5.1", "eslint-plugin-vue": "^9.33.0", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vue-eslint-parser": "^9.4.3", - "vue-tsc": "^3.1.5" + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts b/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts index 836ea41bd8..9d9c8d49a3 100644 --- a/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-esbuild-file-based/src/esbuild.config.js b/e2e/vue-router/basic-esbuild-file-based/src/esbuild.config.js index c4aba8798e..16f6fbca44 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/esbuild.config.js +++ b/e2e/vue-router/basic-esbuild-file-based/src/esbuild.config.js @@ -9,7 +9,6 @@ export default { }), tanstackRouter({ target: 'vue', - autoCodeSplitting: true, }), ], } diff --git a/e2e/vue-router/basic-esbuild-file-based/src/esbuild.run.js b/e2e/vue-router/basic-esbuild-file-based/src/esbuild.run.js index 19e882c1a9..0ab294f2bf 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/esbuild.run.js +++ b/e2e/vue-router/basic-esbuild-file-based/src/esbuild.run.js @@ -1,8 +1,7 @@ -import * as esbuild from 'esbuild' import http from 'node:http' -import { createReadStream } from 'node:fs' -import { promises as fs } from 'node:fs' +import { createReadStream, promises as fs } from 'node:fs' import path from 'node:path' +import * as esbuild from 'esbuild' import esbuildConfig from './esbuild.config.js' const args = process.argv.slice(2) @@ -18,7 +17,7 @@ function getPort() { const fromArg = getArgValue('--port') const fromEnv = process.env.VITE_SERVER_PORT const port = Number(fromArg ?? fromEnv ?? 5601) - if (!Number.isFinite(port) || port <= 0) { + if (!Number.isFinite(port) || port < 0) { throw new Error(`Invalid port: ${String(fromArg ?? fromEnv)}`) } return port @@ -138,7 +137,7 @@ function startStaticServer({ port }) { return new Promise((resolve) => { server.listen(port, () => { - console.log(`http://localhost:${port}`) + console.log(`E2E app: http://localhost:${server.address().port}`) resolve(server) }) }) diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/(another-group)/onlyrouteinside.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/(another-group)/onlyrouteinside.tsx index 727c1b4d94..8869cefc01 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/(another-group)/onlyrouteinside.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/(another-group)/onlyrouteinside.tsx @@ -1,27 +1,32 @@ +import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' +const OnlyRouteInsideComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ + from: '/(another-group)/onlyrouteinside', + }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) + }, +}) + export const Route = createFileRoute('/(another-group)/onlyrouteinside')({ validateSearch: z.object({ hello: z.string().optional() }), component: OnlyRouteInsideComponent, }) const routeApi = getRouteApi('/(another-group)/onlyrouteinside') - -function OnlyRouteInsideComponent() { - const searchViaHook = useSearch({ from: '/(another-group)/onlyrouteinside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) -} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/_layout.insidelayout.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/_layout.insidelayout.tsx index 4b239f3ef4..f2998803fd 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/_layout.insidelayout.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/_layout.insidelayout.tsx @@ -1,27 +1,30 @@ +import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' +const InsideLayoutComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ from: '/(group)/_layout/insidelayout' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) + }, +}) + export const Route = createFileRoute('/(group)/_layout/insidelayout')({ validateSearch: z.object({ hello: z.string().optional() }), component: InsideLayoutComponent, }) const routeApi = getRouteApi('/(group)/_layout/insidelayout') - -function InsideLayoutComponent() { - const searchViaHook = useSearch({ from: '/(group)/_layout/insidelayout' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) -} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/inside.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/inside.tsx index f12ca517d3..20e0d5afdb 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/inside.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/inside.tsx @@ -1,27 +1,30 @@ +import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' +const InsideComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ from: '/(group)/inside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) + }, +}) + export const Route = createFileRoute('/(group)/inside')({ validateSearch: z.object({ hello: z.string().optional() }), component: InsideComponent, }) const routeApi = getRouteApi('/(group)/inside') - -function InsideComponent() { - const searchViaHook = useSearch({ from: '/(group)/inside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) -} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/lazyinside.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/lazyinside.tsx index 05b34eb201..a46da658d6 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/lazyinside.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/lazyinside.tsx @@ -1,27 +1,30 @@ +import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' +const LazyInsideComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ from: '/(group)/lazyinside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) + }, +}) + export const Route = createFileRoute('/(group)/lazyinside')({ validateSearch: z.object({ hello: z.string().optional() }), component: LazyInsideComponent, }) const routeApi = getRouteApi('/(group)/lazyinside') - -function LazyInsideComponent() { - const searchViaHook = useSearch({ from: '/(group)/lazyinside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) -} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/subfolder/inside.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/subfolder/inside.tsx index 317c766186..715d2cc972 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/subfolder/inside.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/(group)/subfolder/inside.tsx @@ -1,27 +1,30 @@ +import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' +const SubfolderInsideComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ from: '/(group)/subfolder/inside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) + }, +}) + export const Route = createFileRoute('/(group)/subfolder/inside')({ validateSearch: z.object({ hello: z.string().optional() }), component: SubfolderInsideComponent, }) const routeApi = getRouteApi('/(group)/subfolder/inside') - -function SubfolderInsideComponent() { - const searchViaHook = useSearch({ from: '/(group)/subfolder/inside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) -} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/__root.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/__root.tsx index 59c9e6fa48..62c4af3aa4 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/__root.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/__root.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { HeadContent, Link, @@ -10,95 +11,97 @@ import { import { TanStackRouterDevtools } from '@tanstack/vue-router-devtools' import NotFoundComponent from '../components/NotFoundComponent.vue' +const RootComponent = defineComponent({ + setup() { + const router = useRouter() + const canGoBack = useCanGoBack() + // test useRouterState doesn't crash client side navigation + const _state = useRouterState() + + return () => ( + <> + +
+ + + Home + + + Posts + + + Layout + + + Only Route Inside Group + + + Inside Group + + + Inside Subfolder Inside Group + + + Inside Group Inside Layout + + + Lazy Inside Group + + + unicode path + + + This Route Does Not Exist + +
+
+ + + + ) + }, +}) + export const Route = createRootRoute({ component: RootComponent, notFoundComponent: NotFoundComponent, }) - -function RootComponent() { - const router = useRouter() - const canGoBack = useCanGoBack() - // test useRouterState doesn't crash client side navigation - const _state = useRouterState() - - return ( - <> - -
- - - Home - - - Posts - - - Layout - - - Only Route Inside Group - - - Inside Group - - - Inside Subfolder Inside Group - - - Inside Group Inside Layout - - - Lazy Inside Group - - - unicode path - - - This Route Does Not Exist - -
-
- - - - ) -} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.$postId.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.$postId.tsx index 15d17387c8..54ae789c8e 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.$postId.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.$postId.tsx @@ -1,24 +1,27 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import PostErrorComponent from '../components/PostErrorComponent.vue' import { fetchPost } from '../posts' import type { PostType } from '../posts' +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + + return () => ( +
+

+ {(post.value as PostType).title} +

+
{(post.value as PostType).body}
+
+ ) + }, +}) + export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), component: PostComponent, errorComponent: PostErrorComponent, notFoundComponent: () =>

Post not found

, }) - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

- {(post.value as PostType).title} -

-
{(post.value as PostType).body}
-
- ) -} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.tsx index ae580dfc02..e0afd27b4c 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/posts.tsx @@ -1,7 +1,38 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../posts' import type { PostType } from '../posts' +const PostsComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + + return () => ( +
+
    + {[ + ...(posts.value as Array), + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ))} +
+
+ +
+ ) + }, +}) + export const Route = createFileRoute('/posts')({ head: () => ({ meta: [ @@ -13,31 +44,3 @@ export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[ - ...(posts.value as Array), - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ))} -
-
- -
- ) -} diff --git a/e2e/vue-router/basic-esbuild-file-based/src/routes/posts_.$postId.edit.tsx b/e2e/vue-router/basic-esbuild-file-based/src/routes/posts_.$postId.edit.tsx index 57963c6b64..22979c93c9 100644 --- a/e2e/vue-router/basic-esbuild-file-based/src/routes/posts_.$postId.edit.tsx +++ b/e2e/vue-router/basic-esbuild-file-based/src/routes/posts_.$postId.edit.tsx @@ -1,23 +1,28 @@ +import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useParams } from '@tanstack/vue-router' +const PostEditComponent = defineComponent({ + setup() { + const paramsViaApi = api.useParams() + const paramsViaHook = useParams({ from: '/posts_/$postId/edit' }) + const paramsViaRouteHook = api.useParams() + + return () => ( +
+
{paramsViaHook.value.postId}
+
+ {paramsViaRouteHook.value.postId} +
+
+ {paramsViaApi.value.postId} +
+
+ ) + }, +}) + export const Route = createFileRoute('/posts_/$postId/edit')({ component: PostEditComponent, }) const api = getRouteApi('/posts_/$postId/edit') - -function PostEditComponent() { - const paramsViaApi = api.useParams() - const paramsViaHook = useParams({ from: '/posts_/$postId/edit' }) - const paramsViaRouteHook = api.useParams() - - return ( -
-
{paramsViaHook.value.postId}
-
- {paramsViaRouteHook.value.postId} -
-
{paramsViaApi.value.postId}
-
- ) -} diff --git a/e2e/vue-router/basic-esbuild-file-based/tests/app.spec.ts b/e2e/vue-router/basic-esbuild-file-based/tests/app.spec.ts index 543746d64d..7380859e7b 100644 --- a/e2e/vue-router/basic-esbuild-file-based/tests/app.spec.ts +++ b/e2e/vue-router/basic-esbuild-file-based/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' import type { Page } from '@playwright/test' test.beforeEach(async ({ page }) => { diff --git a/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.setup.ts b/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic-file-based-jsx/package.json b/e2e/vue-router/basic-file-based-jsx/package.json index e4d20d72e9..9ab7f21e82 100644 --- a/e2e/vue-router/basic-file-based-jsx/package.json +++ b/e2e/vue-router/basic-file-based-jsx/package.json @@ -8,14 +8,14 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16", "zod": "^4.4.3" @@ -32,6 +32,6 @@ "typescript": "~5.8.3", "vite": "^8.0.14", "vue-eslint-parser": "^9.4.3", - "vue-tsc": "^3.1.5" + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-router/basic-file-based-jsx/playwright.config.ts b/e2e/vue-router/basic-file-based-jsx/playwright.config.ts index 836ea41bd8..4eead86444 100644 --- a/e2e/vue-router/basic-file-based-jsx/playwright.config.ts +++ b/e2e/vue-router/basic-file-based-jsx/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-file-based-jsx/src/posts.tsx b/e2e/vue-router/basic-file-based-jsx/src/posts.tsx index 1b4c92b41d..f7a1941605 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/posts.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-file-based-jsx/src/routeTree.gen.ts b/e2e/vue-router/basic-file-based-jsx/src/routeTree.gen.ts index f5cd519d7f..5922c5f7b1 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routeTree.gen.ts +++ b/e2e/vue-router/basic-file-based-jsx/src/routeTree.gen.ts @@ -11,34 +11,62 @@ import { lazyRouteComponent } from '@tanstack/vue-router' import { Route as rootRouteImport } from './routes/__root' -import { Route as Char45824Char54620Char48124Char44397RouteImport } from './routes/대한민국' -import { Route as SfcComponentRouteImport } from './routes/sfcComponent' -import { Route as RemountDepsRouteImport } from './routes/remountDeps' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as NotRemountDepsRouteImport } from './routes/notRemountDeps' -import { Route as EditingBRouteImport } from './routes/editing-b' -import { Route as EditingARouteImport } from './routes/editing-a' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as IndexRouteImport } from './routes/index' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as EditingARouteImport } from './routes/editing-a' +import { Route as EditingBRouteImport } from './routes/editing-b' +import { Route as NotRemountDepsRouteImport } from './routes/notRemountDeps' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RemountDepsRouteImport } from './routes/remountDeps' +import { Route as SfcComponentRouteImport } from './routes/sfcComponent' +import { Route as Char45824Char54620Char48124Char44397RouteImport } from './routes/대한민국' +import { Route as anotherGroupOnlyrouteinsideRouteImport } from './routes/(another-group)/onlyrouteinside' +import { Route as groupLayoutRouteImport } from './routes/(group)/_layout' +import { Route as groupInsideRouteImport } from './routes/(group)/inside' +import { Route as groupLazyinsideRouteImport } from './routes/(group)/lazyinside' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as groupLazyinsideRouteImport } from './routes/(group)/lazyinside' -import { Route as groupInsideRouteImport } from './routes/(group)/inside' -import { Route as groupLayoutRouteImport } from './routes/(group)/_layout' -import { Route as anotherGroupOnlyrouteinsideRouteImport } from './routes/(another-group)/onlyrouteinside' -import { Route as PostsPostIdEditRouteImport } from './routes/posts_.$postId.edit' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' -import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -import { Route as groupSubfolderInsideRouteImport } from './routes/(group)/subfolder/inside' import { Route as groupLayoutInsidelayoutRouteImport } from './routes/(group)/_layout.insidelayout' +import { Route as groupSubfolderInsideRouteImport } from './routes/(group)/subfolder/inside' +import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as PostsPostIdEditRouteImport } from './routes/posts_.$postId.edit' -const Char45824Char54620Char48124Char44397Route = - Char45824Char54620Char48124Char44397RouteImport.update({ - id: '/대한민국', - path: '/대한민국', - getParentRoute: () => rootRouteImport, - } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const EditingARoute = EditingARouteImport.update({ + id: '/editing-a', + path: '/editing-a', + getParentRoute: () => rootRouteImport, +} as any) +const EditingBRoute = EditingBRouteImport.update({ + id: '/editing-b', + path: '/editing-b', + getParentRoute: () => rootRouteImport, +} as any) +const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ + id: '/notRemountDeps', + path: '/notRemountDeps', + getParentRoute: () => rootRouteImport, +} as any) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const RemountDepsRoute = RemountDepsRouteImport.update({ + id: '/remountDeps', + path: '/remountDeps', + getParentRoute: () => rootRouteImport, +} as any) const SfcComponentRoute = SfcComponentRouteImport.update({ id: '/sfcComponent', path: '/sfcComponent', @@ -49,39 +77,35 @@ const SfcComponentRoute = SfcComponentRouteImport.update({ 'default', ), }) -const RemountDepsRoute = RemountDepsRouteImport.update({ - id: '/remountDeps', - path: '/remountDeps', +const Char45824Char54620Char48124Char44397Route = + Char45824Char54620Char48124Char44397RouteImport.update({ + id: '/대한민국', + path: '/대한민국', + getParentRoute: () => rootRouteImport, + } as any) +const anotherGroupOnlyrouteinsideRoute = + anotherGroupOnlyrouteinsideRouteImport.update({ + id: '/(another-group)/onlyrouteinside', + path: '/onlyrouteinside', + getParentRoute: () => rootRouteImport, + } as any) +const groupLayoutRoute = groupLayoutRouteImport.update({ + id: '/(group)/_layout', getParentRoute: () => rootRouteImport, } as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const groupInsideRoute = groupInsideRouteImport.update({ + id: '/(group)/inside', + path: '/inside', getParentRoute: () => rootRouteImport, } as any) -const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ - id: '/notRemountDeps', - path: '/notRemountDeps', +const groupLazyinsideRoute = groupLazyinsideRouteImport.update({ + id: '/(group)/lazyinside', + path: '/lazyinside', getParentRoute: () => rootRouteImport, } as any) -const EditingBRoute = EditingBRouteImport.update({ - id: '/editing-b', - path: '/editing-b', - getParentRoute: () => rootRouteImport, -} as any) -const EditingARoute = EditingARouteImport.update({ - id: '/editing-a', - path: '/editing-a', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', @@ -93,54 +117,30 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRoute, } as any) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, -} as any) -const groupLazyinsideRoute = groupLazyinsideRouteImport.update({ - id: '/(group)/lazyinside', - path: '/lazyinside', - getParentRoute: () => rootRouteImport, -} as any) -const groupInsideRoute = groupInsideRouteImport.update({ - id: '/(group)/inside', - path: '/inside', - getParentRoute: () => rootRouteImport, -} as any) -const groupLayoutRoute = groupLayoutRouteImport.update({ - id: '/(group)/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const anotherGroupOnlyrouteinsideRoute = - anotherGroupOnlyrouteinsideRouteImport.update({ - id: '/(another-group)/onlyrouteinside', - path: '/onlyrouteinside', - getParentRoute: () => rootRouteImport, - } as any) -const PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ - id: '/posts_/$postId/edit', - path: '/posts/$postId/edit', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => LayoutLayout2Route, -} as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport.update({ + id: '/insidelayout', + path: '/insidelayout', + getParentRoute: () => groupLayoutRoute, } as any) const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport.update({ id: '/(group)/subfolder/inside', path: '/subfolder/inside', getParentRoute: () => rootRouteImport, } as any) -const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport.update({ - id: '/insidelayout', - path: '/insidelayout', - getParentRoute: () => groupLayoutRoute, +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, +} as any) +const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => LayoutLayout2Route, +} as any) +const PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ + id: '/posts_/$postId/edit', + path: '/posts/$postId/edit', + getParentRoute: () => rootRouteImport, } as any) export interface FileRoutesByFullPath { @@ -291,53 +291,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/대한민국': { - id: '/대한민국' - path: '/대한민국' - fullPath: '/대한민국' - preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport - parentRoute: typeof rootRouteImport - } - '/sfcComponent': { - id: '/sfcComponent' - path: '/sfcComponent' - fullPath: '/sfcComponent' - preLoaderRoute: typeof SfcComponentRouteImport - parentRoute: typeof rootRouteImport - } - '/remountDeps': { - id: '/remountDeps' - path: '/remountDeps' - fullPath: '/remountDeps' - preLoaderRoute: typeof RemountDepsRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/notRemountDeps': { - id: '/notRemountDeps' - path: '/notRemountDeps' - fullPath: '/notRemountDeps' - preLoaderRoute: typeof NotRemountDepsRouteImport - parentRoute: typeof rootRouteImport - } - '/editing-b': { - id: '/editing-b' - path: '/editing-b' - fullPath: '/editing-b' - preLoaderRoute: typeof EditingBRouteImport - parentRoute: typeof rootRouteImport - } - '/editing-a': { - id: '/editing-a' - path: '/editing-a' - fullPath: '/editing-a' - preLoaderRoute: typeof EditingARouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -347,13 +305,90 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/editing-a': { + id: '/editing-a' + path: '/editing-a' + fullPath: '/editing-a' + preLoaderRoute: typeof EditingARouteImport parentRoute: typeof rootRouteImport } + '/editing-b': { + id: '/editing-b' + path: '/editing-b' + fullPath: '/editing-b' + preLoaderRoute: typeof EditingBRouteImport + parentRoute: typeof rootRouteImport + } + '/notRemountDeps': { + id: '/notRemountDeps' + path: '/notRemountDeps' + fullPath: '/notRemountDeps' + preLoaderRoute: typeof NotRemountDepsRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/remountDeps': { + id: '/remountDeps' + path: '/remountDeps' + fullPath: '/remountDeps' + preLoaderRoute: typeof RemountDepsRouteImport + parentRoute: typeof rootRouteImport + } + '/sfcComponent': { + id: '/sfcComponent' + path: '/sfcComponent' + fullPath: '/sfcComponent' + preLoaderRoute: typeof SfcComponentRouteImport + parentRoute: typeof rootRouteImport + } + '/대한민국': { + id: '/대한민국' + path: '/대한민국' + fullPath: '/대한민국' + preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport + parentRoute: typeof rootRouteImport + } + '/(another-group)/onlyrouteinside': { + id: '/(another-group)/onlyrouteinside' + path: '/onlyrouteinside' + fullPath: '/onlyrouteinside' + preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/_layout': { + id: '/(group)/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof groupLayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/inside': { + id: '/(group)/inside' + path: '/inside' + fullPath: '/inside' + preLoaderRoute: typeof groupInsideRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/lazyinside': { + id: '/(group)/lazyinside' + path: '/lazyinside' + fullPath: '/lazyinside' + preLoaderRoute: typeof groupLazyinsideRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute + } '/posts/': { id: '/posts/' path: '/' @@ -368,61 +403,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute - } - '/(group)/lazyinside': { - id: '/(group)/lazyinside' - path: '/lazyinside' - fullPath: '/lazyinside' - preLoaderRoute: typeof groupLazyinsideRouteImport - parentRoute: typeof rootRouteImport - } - '/(group)/inside': { - id: '/(group)/inside' - path: '/inside' - fullPath: '/inside' - preLoaderRoute: typeof groupInsideRouteImport - parentRoute: typeof rootRouteImport - } - '/(group)/_layout': { - id: '/(group)/_layout' - path: '' - fullPath: '' - preLoaderRoute: typeof groupLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/(another-group)/onlyrouteinside': { - id: '/(another-group)/onlyrouteinside' - path: '/onlyrouteinside' - fullPath: '/onlyrouteinside' - preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport - parentRoute: typeof rootRouteImport - } - '/posts_/$postId/edit': { - id: '/posts_/$postId/edit' - path: '/posts/$postId/edit' - fullPath: '/posts/$postId/edit' - preLoaderRoute: typeof PostsPostIdEditRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout/_layout-2/layout-b': { - id: '/_layout/_layout-2/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport - parentRoute: typeof LayoutLayout2Route - } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/(group)/_layout/insidelayout': { + id: '/(group)/_layout/insidelayout' + path: '/insidelayout' + fullPath: '/insidelayout' + preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport + parentRoute: typeof groupLayoutRoute } '/(group)/subfolder/inside': { id: '/(group)/subfolder/inside' @@ -431,12 +417,26 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof groupSubfolderInsideRouteImport parentRoute: typeof rootRouteImport } - '/(group)/_layout/insidelayout': { - id: '/(group)/_layout/insidelayout' - path: '/insidelayout' - fullPath: '/insidelayout' - preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport - parentRoute: typeof groupLayoutRoute + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route + } + '/_layout/_layout-2/layout-b': { + id: '/_layout/_layout-2/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport + parentRoute: typeof LayoutLayout2Route + } + '/posts_/$postId/edit': { + id: '/posts_/$postId/edit' + path: '/posts/$postId/edit' + fullPath: '/posts/$postId/edit' + preLoaderRoute: typeof PostsPostIdEditRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx index 727c1b4d94..8869cefc01 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx @@ -1,27 +1,32 @@ +import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' +const OnlyRouteInsideComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ + from: '/(another-group)/onlyrouteinside', + }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) + }, +}) + export const Route = createFileRoute('/(another-group)/onlyrouteinside')({ validateSearch: z.object({ hello: z.string().optional() }), component: OnlyRouteInsideComponent, }) const routeApi = getRouteApi('/(another-group)/onlyrouteinside') - -function OnlyRouteInsideComponent() { - const searchViaHook = useSearch({ from: '/(another-group)/onlyrouteinside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) -} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx index 4b239f3ef4..f2998803fd 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx @@ -1,27 +1,30 @@ +import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' +const InsideLayoutComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ from: '/(group)/_layout/insidelayout' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) + }, +}) + export const Route = createFileRoute('/(group)/_layout/insidelayout')({ validateSearch: z.object({ hello: z.string().optional() }), component: InsideLayoutComponent, }) const routeApi = getRouteApi('/(group)/_layout/insidelayout') - -function InsideLayoutComponent() { - const searchViaHook = useSearch({ from: '/(group)/_layout/insidelayout' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) -} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/inside.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/inside.tsx index f12ca517d3..20e0d5afdb 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/inside.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/inside.tsx @@ -1,27 +1,30 @@ +import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' +const InsideComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ from: '/(group)/inside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) + }, +}) + export const Route = createFileRoute('/(group)/inside')({ validateSearch: z.object({ hello: z.string().optional() }), component: InsideComponent, }) const routeApi = getRouteApi('/(group)/inside') - -function InsideComponent() { - const searchViaHook = useSearch({ from: '/(group)/inside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) -} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx index 05b34eb201..a46da658d6 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx @@ -1,27 +1,30 @@ +import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' +const LazyInsideComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ from: '/(group)/lazyinside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) + }, +}) + export const Route = createFileRoute('/(group)/lazyinside')({ validateSearch: z.object({ hello: z.string().optional() }), component: LazyInsideComponent, }) const routeApi = getRouteApi('/(group)/lazyinside') - -function LazyInsideComponent() { - const searchViaHook = useSearch({ from: '/(group)/lazyinside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) -} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx index 317c766186..715d2cc972 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx @@ -1,27 +1,30 @@ +import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' import { z } from 'zod' +const SubfolderInsideComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ from: '/(group)/subfolder/inside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) + }, +}) + export const Route = createFileRoute('/(group)/subfolder/inside')({ validateSearch: z.object({ hello: z.string().optional() }), component: SubfolderInsideComponent, }) const routeApi = getRouteApi('/(group)/subfolder/inside') - -function SubfolderInsideComponent() { - const searchViaHook = useSearch({ from: '/(group)/subfolder/inside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) -} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/__root.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/__root.tsx index 59c9e6fa48..62c4af3aa4 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/__root.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/__root.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { HeadContent, Link, @@ -10,95 +11,97 @@ import { import { TanStackRouterDevtools } from '@tanstack/vue-router-devtools' import NotFoundComponent from '../components/NotFoundComponent.vue' +const RootComponent = defineComponent({ + setup() { + const router = useRouter() + const canGoBack = useCanGoBack() + // test useRouterState doesn't crash client side navigation + const _state = useRouterState() + + return () => ( + <> + +
+ + + Home + + + Posts + + + Layout + + + Only Route Inside Group + + + Inside Group + + + Inside Subfolder Inside Group + + + Inside Group Inside Layout + + + Lazy Inside Group + + + unicode path + + + This Route Does Not Exist + +
+
+ + + + ) + }, +}) + export const Route = createRootRoute({ component: RootComponent, notFoundComponent: NotFoundComponent, }) - -function RootComponent() { - const router = useRouter() - const canGoBack = useCanGoBack() - // test useRouterState doesn't crash client side navigation - const _state = useRouterState() - - return ( - <> - -
- - - Home - - - Posts - - - Layout - - - Only Route Inside Group - - - Inside Group - - - Inside Subfolder Inside Group - - - Inside Group Inside Layout - - - Lazy Inside Group - - - unicode path - - - This Route Does Not Exist - -
-
- - - - ) -} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/posts.$postId.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/posts.$postId.tsx index 15d17387c8..54ae789c8e 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/posts.$postId.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/posts.$postId.tsx @@ -1,24 +1,27 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import PostErrorComponent from '../components/PostErrorComponent.vue' import { fetchPost } from '../posts' import type { PostType } from '../posts' +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + + return () => ( +
+

+ {(post.value as PostType).title} +

+
{(post.value as PostType).body}
+
+ ) + }, +}) + export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), component: PostComponent, errorComponent: PostErrorComponent, notFoundComponent: () =>

Post not found

, }) - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

- {(post.value as PostType).title} -

-
{(post.value as PostType).body}
-
- ) -} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/posts.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/posts.tsx index ae580dfc02..e0afd27b4c 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/posts.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/posts.tsx @@ -1,7 +1,38 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../posts' import type { PostType } from '../posts' +const PostsComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + + return () => ( +
+
    + {[ + ...(posts.value as Array), + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ))} +
+
+ +
+ ) + }, +}) + export const Route = createFileRoute('/posts')({ head: () => ({ meta: [ @@ -13,31 +44,3 @@ export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[ - ...(posts.value as Array), - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ))} -
-
- -
- ) -} diff --git a/e2e/vue-router/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx b/e2e/vue-router/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx index 57963c6b64..22979c93c9 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx @@ -1,23 +1,28 @@ +import { defineComponent } from 'vue' import { createFileRoute, getRouteApi, useParams } from '@tanstack/vue-router' +const PostEditComponent = defineComponent({ + setup() { + const paramsViaApi = api.useParams() + const paramsViaHook = useParams({ from: '/posts_/$postId/edit' }) + const paramsViaRouteHook = api.useParams() + + return () => ( +
+
{paramsViaHook.value.postId}
+
+ {paramsViaRouteHook.value.postId} +
+
+ {paramsViaApi.value.postId} +
+
+ ) + }, +}) + export const Route = createFileRoute('/posts_/$postId/edit')({ component: PostEditComponent, }) const api = getRouteApi('/posts_/$postId/edit') - -function PostEditComponent() { - const paramsViaApi = api.useParams() - const paramsViaHook = useParams({ from: '/posts_/$postId/edit' }) - const paramsViaRouteHook = api.useParams() - - return ( -
-
{paramsViaHook.value.postId}
-
- {paramsViaRouteHook.value.postId} -
-
{paramsViaApi.value.postId}
-
- ) -} diff --git a/e2e/vue-router/basic-file-based-jsx/tests/app.spec.ts b/e2e/vue-router/basic-file-based-jsx/tests/app.spec.ts index 543746d64d..7380859e7b 100644 --- a/e2e/vue-router/basic-file-based-jsx/tests/app.spec.ts +++ b/e2e/vue-router/basic-file-based-jsx/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' import type { Page } from '@playwright/test' test.beforeEach(async ({ page }) => { diff --git a/e2e/vue-router/basic-file-based-jsx/tests/setup/global.setup.ts b/e2e/vue-router/basic-file-based-jsx/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basic-file-based-jsx/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic-file-based-jsx/tests/setup/global.teardown.ts b/e2e/vue-router/basic-file-based-jsx/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basic-file-based-jsx/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic-file-based-sfc/package.json b/e2e/vue-router/basic-file-based-sfc/package.json index 0f1934b9a9..e6ffa156f9 100644 --- a/e2e/vue-router/basic-file-based-sfc/package.json +++ b/e2e/vue-router/basic-file-based-sfc/package.json @@ -8,14 +8,14 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16", "zod": "^4.4.3" @@ -27,6 +27,6 @@ "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", "vite": "^8.0.14", - "vue-tsc": "^3.1.5" + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-router/basic-file-based-sfc/playwright.config.ts b/e2e/vue-router/basic-file-based-sfc/playwright.config.ts index 836ea41bd8..4eead86444 100644 --- a/e2e/vue-router/basic-file-based-sfc/playwright.config.ts +++ b/e2e/vue-router/basic-file-based-sfc/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-file-based-sfc/src/posts.ts b/e2e/vue-router/basic-file-based-sfc/src/posts.ts index 1b4c92b41d..f7a1941605 100644 --- a/e2e/vue-router/basic-file-based-sfc/src/posts.ts +++ b/e2e/vue-router/basic-file-based-sfc/src/posts.ts @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-file-based-sfc/src/routeTree.gen.ts b/e2e/vue-router/basic-file-based-sfc/src/routeTree.gen.ts index fa00eb1ce0..0bfdddab3d 100644 --- a/e2e/vue-router/basic-file-based-sfc/src/routeTree.gen.ts +++ b/e2e/vue-router/basic-file-based-sfc/src/routeTree.gen.ts @@ -11,75 +11,43 @@ import { lazyRouteComponent } from '@tanstack/vue-router' import { Route as rootRouteImport } from './routes/__root' -import { Route as Char45824Char54620Char48124Char44397RouteImport } from './routes/대한민국' -import { Route as RemountDepsRouteImport } from './routes/remountDeps' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as NotRemountDepsRouteImport } from './routes/notRemountDeps' -import { Route as EditingBRouteImport } from './routes/editing-b' -import { Route as EditingARouteImport } from './routes/editing-a' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as IndexRouteImport } from './routes/index' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as EditingARouteImport } from './routes/editing-a' +import { Route as EditingBRouteImport } from './routes/editing-b' +import { Route as NotRemountDepsRouteImport } from './routes/notRemountDeps' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RemountDepsRouteImport } from './routes/remountDeps' +import { Route as Char45824Char54620Char48124Char44397RouteImport } from './routes/대한민국' +import { Route as anotherGroupOnlyrouteinsideRouteImport } from './routes/(another-group)/onlyrouteinside' +import { Route as groupLayoutRouteImport } from './routes/(group)/_layout' +import { Route as groupInsideRouteImport } from './routes/(group)/inside' +import { Route as groupLazyinsideRouteImport } from './routes/(group)/lazyinside' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as groupLazyinsideRouteImport } from './routes/(group)/lazyinside' -import { Route as groupInsideRouteImport } from './routes/(group)/inside' -import { Route as groupLayoutRouteImport } from './routes/(group)/_layout' -import { Route as anotherGroupOnlyrouteinsideRouteImport } from './routes/(another-group)/onlyrouteinside' -import { Route as PostsPostIdEditRouteImport } from './routes/posts_.$postId.edit' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' -import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -import { Route as groupSubfolderInsideRouteImport } from './routes/(group)/subfolder/inside' import { Route as groupLayoutInsidelayoutRouteImport } from './routes/(group)/_layout.insidelayout' +import { Route as groupSubfolderInsideRouteImport } from './routes/(group)/subfolder/inside' +import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as PostsPostIdEditRouteImport } from './routes/posts_.$postId.edit' -const Char45824Char54620Char48124Char44397Route = - Char45824Char54620Char48124Char44397RouteImport.update({ - id: '/대한민국', - path: '/대한민국', - getParentRoute: () => rootRouteImport, - } as any).update({ - component: lazyRouteComponent( - () => import('./routes/대한민국.component.vue'), - 'default', - ), - }) -const RemountDepsRoute = RemountDepsRouteImport.update({ - id: '/remountDeps', - path: '/remountDeps', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/remountDeps.component.vue'), + () => import('./routes/index.component.vue'), 'default', ), }) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/posts.component.vue'), - 'default', - ), -}) -const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ - id: '/notRemountDeps', - path: '/notRemountDeps', - getParentRoute: () => rootRouteImport, -} as any).update({ - component: lazyRouteComponent( - () => import('./routes/notRemountDeps.component.vue'), - 'default', - ), -}) -const EditingBRoute = EditingBRouteImport.update({ - id: '/editing-b', - path: '/editing-b', - getParentRoute: () => rootRouteImport, -} as any).update({ - component: lazyRouteComponent( - () => import('./routes/editing-b.component.vue'), + () => import('./routes/_layout.component.vue'), 'default', ), }) @@ -93,22 +61,110 @@ const EditingARoute = EditingARouteImport.update({ 'default', ), }) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', +const EditingBRoute = EditingBRouteImport.update({ + id: '/editing-b', + path: '/editing-b', getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/_layout.component.vue'), + () => import('./routes/editing-b.component.vue'), 'default', ), }) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ + id: '/notRemountDeps', + path: '/notRemountDeps', getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/index.component.vue'), + () => import('./routes/notRemountDeps.component.vue'), + 'default', + ), +}) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/posts.component.vue'), + 'default', + ), +}) +const RemountDepsRoute = RemountDepsRouteImport.update({ + id: '/remountDeps', + path: '/remountDeps', + getParentRoute: () => rootRouteImport, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/remountDeps.component.vue'), + 'default', + ), +}) +const Char45824Char54620Char48124Char44397Route = + Char45824Char54620Char48124Char44397RouteImport.update({ + id: '/대한민국', + path: '/대한민국', + getParentRoute: () => rootRouteImport, + } as any).update({ + component: lazyRouteComponent( + () => import('./routes/대한민국.component.vue'), + 'default', + ), + }) +const anotherGroupOnlyrouteinsideRoute = anotherGroupOnlyrouteinsideRouteImport + .update({ + id: '/(another-group)/onlyrouteinside', + path: '/onlyrouteinside', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(another-group)/onlyrouteinside.component.vue'), + 'default', + ), + }) +const groupLayoutRoute = groupLayoutRouteImport + .update({ + id: '/(group)/_layout', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/_layout.component.vue'), + 'default', + ), + }) +const groupInsideRoute = groupInsideRouteImport + .update({ + id: '/(group)/inside', + path: '/inside', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/inside.component.vue'), + 'default', + ), + }) +const groupLazyinsideRoute = groupLazyinsideRouteImport + .update({ + id: '/(group)/lazyinside', + path: '/lazyinside', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/lazyinside.component.vue'), + 'default', + ), + }) +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/_layout/_layout-2.component.vue'), 'default', ), }) @@ -136,69 +192,37 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ 'default', ), }) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, +const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport + .update({ + id: '/insidelayout', + path: '/insidelayout', + getParentRoute: () => groupLayoutRoute, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/_layout.insidelayout.component.vue'), + 'default', + ), + }) +const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport + .update({ + id: '/(group)/subfolder/inside', + path: '/subfolder/inside', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/subfolder/inside.component.vue'), + 'default', + ), + }) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any).update({ component: lazyRouteComponent( - () => import('./routes/_layout/_layout-2.component.vue'), - 'default', - ), -}) -const groupLazyinsideRoute = groupLazyinsideRouteImport - .update({ - id: '/(group)/lazyinside', - path: '/lazyinside', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/lazyinside.component.vue'), - 'default', - ), - }) -const groupInsideRoute = groupInsideRouteImport - .update({ - id: '/(group)/inside', - path: '/inside', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/inside.component.vue'), - 'default', - ), - }) -const groupLayoutRoute = groupLayoutRouteImport - .update({ - id: '/(group)/_layout', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/_layout.component.vue'), - 'default', - ), - }) -const anotherGroupOnlyrouteinsideRoute = anotherGroupOnlyrouteinsideRouteImport - .update({ - id: '/(another-group)/onlyrouteinside', - path: '/onlyrouteinside', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(another-group)/onlyrouteinside.component.vue'), - 'default', - ), - }) -const PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ - id: '/posts_/$postId/edit', - path: '/posts/$postId/edit', - getParentRoute: () => rootRouteImport, -} as any).update({ - component: lazyRouteComponent( - () => import('./routes/posts_.$postId.edit.component.vue'), + () => import('./routes/_layout/_layout-2/layout-a.component.vue'), 'default', ), }) @@ -212,40 +236,16 @@ const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ 'default', ), }) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ + id: '/posts_/$postId/edit', + path: '/posts/$postId/edit', + getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/_layout/_layout-2/layout-a.component.vue'), + () => import('./routes/posts_.$postId.edit.component.vue'), 'default', ), }) -const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport - .update({ - id: '/(group)/subfolder/inside', - path: '/subfolder/inside', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/subfolder/inside.component.vue'), - 'default', - ), - }) -const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport - .update({ - id: '/insidelayout', - path: '/insidelayout', - getParentRoute: () => groupLayoutRoute, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/_layout.insidelayout.component.vue'), - 'default', - ), - }) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -388,46 +388,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/대한민국': { - id: '/대한민국' - path: '/대한민국' - fullPath: '/대한민국' - preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport - parentRoute: typeof rootRouteImport - } - '/remountDeps': { - id: '/remountDeps' - path: '/remountDeps' - fullPath: '/remountDeps' - preLoaderRoute: typeof RemountDepsRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/notRemountDeps': { - id: '/notRemountDeps' - path: '/notRemountDeps' - fullPath: '/notRemountDeps' - preLoaderRoute: typeof NotRemountDepsRouteImport - parentRoute: typeof rootRouteImport - } - '/editing-b': { - id: '/editing-b' - path: '/editing-b' - fullPath: '/editing-b' - preLoaderRoute: typeof EditingBRouteImport - parentRoute: typeof rootRouteImport - } - '/editing-a': { - id: '/editing-a' - path: '/editing-a' - fullPath: '/editing-a' - preLoaderRoute: typeof EditingARouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -437,13 +402,83 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/editing-a': { + id: '/editing-a' + path: '/editing-a' + fullPath: '/editing-a' + preLoaderRoute: typeof EditingARouteImport parentRoute: typeof rootRouteImport } + '/editing-b': { + id: '/editing-b' + path: '/editing-b' + fullPath: '/editing-b' + preLoaderRoute: typeof EditingBRouteImport + parentRoute: typeof rootRouteImport + } + '/notRemountDeps': { + id: '/notRemountDeps' + path: '/notRemountDeps' + fullPath: '/notRemountDeps' + preLoaderRoute: typeof NotRemountDepsRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/remountDeps': { + id: '/remountDeps' + path: '/remountDeps' + fullPath: '/remountDeps' + preLoaderRoute: typeof RemountDepsRouteImport + parentRoute: typeof rootRouteImport + } + '/대한민국': { + id: '/대한민국' + path: '/대한민국' + fullPath: '/대한민국' + preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport + parentRoute: typeof rootRouteImport + } + '/(another-group)/onlyrouteinside': { + id: '/(another-group)/onlyrouteinside' + path: '/onlyrouteinside' + fullPath: '/onlyrouteinside' + preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/_layout': { + id: '/(group)/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof groupLayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/inside': { + id: '/(group)/inside' + path: '/inside' + fullPath: '/inside' + preLoaderRoute: typeof groupInsideRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/lazyinside': { + id: '/(group)/lazyinside' + path: '/lazyinside' + fullPath: '/lazyinside' + preLoaderRoute: typeof groupLazyinsideRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute + } '/posts/': { id: '/posts/' path: '/' @@ -458,61 +493,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute - } - '/(group)/lazyinside': { - id: '/(group)/lazyinside' - path: '/lazyinside' - fullPath: '/lazyinside' - preLoaderRoute: typeof groupLazyinsideRouteImport - parentRoute: typeof rootRouteImport - } - '/(group)/inside': { - id: '/(group)/inside' - path: '/inside' - fullPath: '/inside' - preLoaderRoute: typeof groupInsideRouteImport - parentRoute: typeof rootRouteImport - } - '/(group)/_layout': { - id: '/(group)/_layout' - path: '' - fullPath: '' - preLoaderRoute: typeof groupLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/(another-group)/onlyrouteinside': { - id: '/(another-group)/onlyrouteinside' - path: '/onlyrouteinside' - fullPath: '/onlyrouteinside' - preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport - parentRoute: typeof rootRouteImport - } - '/posts_/$postId/edit': { - id: '/posts_/$postId/edit' - path: '/posts/$postId/edit' - fullPath: '/posts/$postId/edit' - preLoaderRoute: typeof PostsPostIdEditRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout/_layout-2/layout-b': { - id: '/_layout/_layout-2/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport - parentRoute: typeof LayoutLayout2Route - } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/(group)/_layout/insidelayout': { + id: '/(group)/_layout/insidelayout' + path: '/insidelayout' + fullPath: '/insidelayout' + preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport + parentRoute: typeof groupLayoutRoute } '/(group)/subfolder/inside': { id: '/(group)/subfolder/inside' @@ -521,12 +507,26 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof groupSubfolderInsideRouteImport parentRoute: typeof rootRouteImport } - '/(group)/_layout/insidelayout': { - id: '/(group)/_layout/insidelayout' - path: '/insidelayout' - fullPath: '/insidelayout' - preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport - parentRoute: typeof groupLayoutRoute + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route + } + '/_layout/_layout-2/layout-b': { + id: '/_layout/_layout-2/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport + parentRoute: typeof LayoutLayout2Route + } + '/posts_/$postId/edit': { + id: '/posts_/$postId/edit' + path: '/posts/$postId/edit' + fullPath: '/posts/$postId/edit' + preLoaderRoute: typeof PostsPostIdEditRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/e2e/vue-router/basic-file-based-sfc/tests/app.spec.ts b/e2e/vue-router/basic-file-based-sfc/tests/app.spec.ts index 543746d64d..7380859e7b 100644 --- a/e2e/vue-router/basic-file-based-sfc/tests/app.spec.ts +++ b/e2e/vue-router/basic-file-based-sfc/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' import type { Page } from '@playwright/test' test.beforeEach(async ({ page }) => { diff --git a/e2e/vue-router/basic-file-based-sfc/tests/setup/global.setup.ts b/e2e/vue-router/basic-file-based-sfc/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basic-file-based-sfc/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic-file-based-sfc/tests/setup/global.teardown.ts b/e2e/vue-router/basic-file-based-sfc/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basic-file-based-sfc/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic-scroll-restoration/package.json b/e2e/vue-router/basic-scroll-restoration/package.json index 86c91c62ca..f4616a5651 100644 --- a/e2e/vue-router/basic-scroll-restoration/package.json +++ b/e2e/vue-router/basic-scroll-restoration/package.json @@ -8,14 +8,14 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-virtual": "^3.13.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "vue": "^3.5.16", "tailwindcss": "^4.2.2" }, @@ -25,7 +25,7 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "vite": "^8.0.14", - "vue-tsc": "^3.1.5", + "vue-tsc": "^3.3.8", "typescript": "~5.9.0" } } diff --git a/e2e/vue-router/basic-scroll-restoration/playwright.config.ts b/e2e/vue-router/basic-scroll-restoration/playwright.config.ts index 0c5cee43e4..6a684ac89e 100644 --- a/e2e/vue-router/basic-scroll-restoration/playwright.config.ts +++ b/e2e/vue-router/basic-scroll-restoration/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-virtual-file-based/package.json b/e2e/vue-router/basic-virtual-file-based/package.json index 3a341e0e7d..3701c2254c 100644 --- a/e2e/vue-router/basic-virtual-file-based/package.json +++ b/e2e/vue-router/basic-virtual-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -18,7 +18,7 @@ "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, @@ -29,6 +29,6 @@ "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", "vite": "^8.0.14", - "vue-tsc": "^3.1.5" + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-router/basic-virtual-file-based/playwright.config.ts b/e2e/vue-router/basic-virtual-file-based/playwright.config.ts index 836ea41bd8..4eead86444 100644 --- a/e2e/vue-router/basic-virtual-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-virtual-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-virtual-file-based/src/posts.tsx b/e2e/vue-router/basic-virtual-file-based/src/posts.tsx index 8576a3799a..5f5463a668 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/posts.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-virtual-file-based/src/routeTree.gen.ts b/e2e/vue-router/basic-virtual-file-based/src/routeTree.gen.ts index 3798afaa01..1bae3d69a1 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routeTree.gen.ts +++ b/e2e/vue-router/basic-virtual-file-based/src/routeTree.gen.ts @@ -9,76 +9,76 @@ // 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 postsPostsRouteImport } from './routes/posts/posts' -import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' import { Route as homeRouteImport } from './routes/home' -import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' +import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' +import { Route as postsPostsRouteImport } from './routes/posts/posts' import { Route as layoutSecondLayoutRouteImport } from './routes/layout/second-layout' -import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' import { Route as ClassicHelloRouteRouteImport } from './routes/file-based-subtree/hello/route' -import { Route as ClassicHelloIndexRouteImport } from './routes/file-based-subtree/hello/index' -import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' -import { Route as ClassicHelloUniverseRouteImport } from './routes/file-based-subtree/hello/universe' -import { Route as bRouteImport } from './routes/b' +import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' +import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' import { Route as aRouteImport } from './routes/a' +import { Route as bRouteImport } from './routes/b' +import { Route as ClassicHelloIndexRouteImport } from './routes/file-based-subtree/hello/index' +import { Route as ClassicHelloUniverseRouteImport } from './routes/file-based-subtree/hello/universe' +import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' -const postsPostsRoute = postsPostsRouteImport.update({ - id: '/posts', - path: '/posts', +const homeRoute = homeRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const layoutFirstLayoutRoute = layoutFirstLayoutRouteImport.update({ id: '/_first', getParentRoute: () => rootRouteImport, } as any) -const homeRoute = homeRouteImport.update({ - id: '/', - path: '/', +const postsPostsRoute = postsPostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const postsPostsDetailRoute = postsPostsDetailRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => postsPostsRoute, -} as any) const layoutSecondLayoutRoute = layoutSecondLayoutRouteImport.update({ id: '/_second', getParentRoute: () => layoutFirstLayoutRoute, } as any) -const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => postsPostsRoute, -} as any) const ClassicHelloRouteRoute = ClassicHelloRouteRouteImport.update({ id: '/classic/hello', path: '/classic/hello', getParentRoute: () => rootRouteImport, } as any) +const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => postsPostsRoute, +} as any) +const postsPostsDetailRoute = postsPostsDetailRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => postsPostsRoute, +} as any) +const aRoute = aRouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => layoutSecondLayoutRoute, +} as any) +const bRoute = bRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => layoutSecondLayoutRoute, +} as any) const ClassicHelloIndexRoute = ClassicHelloIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ - id: '/world', - path: '/world', - getParentRoute: () => ClassicHelloRouteRoute, -} as any) const ClassicHelloUniverseRoute = ClassicHelloUniverseRouteImport.update({ id: '/universe', path: '/universe', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const bRoute = bRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => layoutSecondLayoutRoute, -} as any) -const aRoute = aRouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => layoutSecondLayoutRoute, +const ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ + id: '/world', + path: '/world', + getParentRoute: () => ClassicHelloRouteRoute, } as any) export interface FileRoutesByFullPath { @@ -166,11 +166,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof postsPostsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof homeRouteImport parentRoute: typeof rootRouteImport } '/_first': { @@ -180,20 +180,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof layoutFirstLayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof homeRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof postsPostsRouteImport parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof postsPostsDetailRouteImport - parentRoute: typeof postsPostsRoute - } '/_first/_second': { id: '/_first/_second' path: '' @@ -201,13 +194,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof layoutSecondLayoutRouteImport parentRoute: typeof layoutFirstLayoutRoute } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof postsPostsHomeRouteImport - parentRoute: typeof postsPostsRoute - } '/classic/hello': { id: '/classic/hello' path: '/classic/hello' @@ -215,6 +201,34 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ClassicHelloRouteRouteImport parentRoute: typeof rootRouteImport } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof postsPostsHomeRouteImport + parentRoute: typeof postsPostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof postsPostsDetailRouteImport + parentRoute: typeof postsPostsRoute + } + '/_first/_second/layout-a': { + id: '/_first/_second/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof aRouteImport + parentRoute: typeof layoutSecondLayoutRoute + } + '/_first/_second/layout-b': { + id: '/_first/_second/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof bRouteImport + parentRoute: typeof layoutSecondLayoutRoute + } '/classic/hello/': { id: '/classic/hello/' path: '/' @@ -222,13 +236,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ClassicHelloIndexRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/classic/hello/world': { - id: '/classic/hello/world' - path: '/world' - fullPath: '/classic/hello/world' - preLoaderRoute: typeof ClassicHelloWorldRouteImport - parentRoute: typeof ClassicHelloRouteRoute - } '/classic/hello/universe': { id: '/classic/hello/universe' path: '/universe' @@ -236,19 +243,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ClassicHelloUniverseRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/_first/_second/layout-b': { - id: '/_first/_second/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof bRouteImport - parentRoute: typeof layoutSecondLayoutRoute - } - '/_first/_second/layout-a': { - id: '/_first/_second/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof aRouteImport - parentRoute: typeof layoutSecondLayoutRoute + '/classic/hello/world': { + id: '/classic/hello/world' + path: '/world' + fullPath: '/classic/hello/world' + preLoaderRoute: typeof ClassicHelloWorldRouteImport + parentRoute: typeof ClassicHelloRouteRoute } } } diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts-detail.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts-detail.tsx index b4c91d3e85..aa5387a4d8 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts-detail.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts-detail.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -6,6 +7,19 @@ export function PostErrorComponent({ error }: ErrorComponentProps) { return } +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + + return () => ( +
+

{post.value?.title}

+
{post.value?.body}
+
+ ) + }, +}) + export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent as any, @@ -14,14 +28,3 @@ export const Route = createFileRoute('/posts/$postId')({ }, component: PostComponent, }) - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

{post.value?.title}

-
{post.value?.body}
-
- ) -} diff --git a/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts.tsx b/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts.tsx index 265faaf650..2a4e8deddd 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/routes/posts/posts.tsx @@ -1,39 +1,42 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../../posts' +const PostsComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + + return () => ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+ +
+ ) + }, +}) + export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) -} diff --git a/e2e/vue-router/basic-virtual-file-based/tests/app.spec.ts b/e2e/vue-router/basic-virtual-file-based/tests/app.spec.ts index 3e5a69ccaa..fbf093cd51 100644 --- a/e2e/vue-router/basic-virtual-file-based/tests/app.spec.ts +++ b/e2e/vue-router/basic-virtual-file-based/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/basic-virtual-file-based/tests/setup/global.setup.ts b/e2e/vue-router/basic-virtual-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basic-virtual-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic-virtual-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/basic-virtual-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basic-virtual-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/package.json b/e2e/vue-router/basic-virtual-named-export-config-file-based/package.json index 08815d8265..d3a69ed573 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/package.json +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -18,7 +18,7 @@ "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, @@ -29,6 +29,6 @@ "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", "vite": "^8.0.14", - "vue-tsc": "^3.1.5" + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/playwright.config.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/playwright.config.ts index 836ea41bd8..4eead86444 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/posts.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/posts.tsx index 8576a3799a..5f5463a668 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/posts.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx index b4c91d3e85..aa5387a4d8 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -6,6 +7,19 @@ export function PostErrorComponent({ error }: ErrorComponentProps) { return } +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + + return () => ( +
+

{post.value?.title}

+
{post.value?.body}
+
+ ) + }, +}) + export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent as any, @@ -14,14 +28,3 @@ export const Route = createFileRoute('/posts/$postId')({ }, component: PostComponent, }) - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

{post.value?.title}

-
{post.value?.body}
-
- ) -} diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx index 265faaf650..2a4e8deddd 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx @@ -1,39 +1,42 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../../posts' +const PostsComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + + return () => ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+ +
+ ) + }, +}) + export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) -} diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts index 3e5a69ccaa..fbf093cd51 100644 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic-vue-query-file-based/package.json b/e2e/vue-router/basic-vue-query-file-based/package.json index 2cd6d23ba0..3b4422d8d8 100644 --- a/e2e/vue-router/basic-vue-query-file-based/package.json +++ b/e2e/vue-router/basic-vue-query-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -17,7 +17,7 @@ "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16", "zod": "^4.4.3" @@ -29,6 +29,6 @@ "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", "vite": "^8.0.14", - "vue-tsc": "^3.1.5" + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-router/basic-vue-query-file-based/playwright.config.ts b/e2e/vue-router/basic-vue-query-file-based/playwright.config.ts index 6e7c123f74..fbda9bd451 100644 --- a/e2e/vue-router/basic-vue-query-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-vue-query-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -17,17 +12,15 @@ export default defineConfig({ workers: 1, reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-vue-query-file-based/src/posts.tsx b/e2e/vue-router/basic-vue-query-file-based/src/posts.tsx index 1becc2c242..1f6cb8e308 100644 --- a/e2e/vue-router/basic-vue-query-file-based/src/posts.tsx +++ b/e2e/vue-router/basic-vue-query-file-based/src/posts.tsx @@ -8,11 +8,7 @@ export type PostType = { export class PostNotFoundError extends Error {} -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/basic-vue-query-file-based/src/routeTree.gen.ts b/e2e/vue-router/basic-vue-query-file-based/src/routeTree.gen.ts index 9dd7ada796..0af0e21dbd 100644 --- a/e2e/vue-router/basic-vue-query-file-based/src/routeTree.gen.ts +++ b/e2e/vue-router/basic-vue-query-file-based/src/routeTree.gen.ts @@ -9,29 +9,33 @@ // 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 PostsRouteImport } from './routes/posts' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as IndexRouteImport } from './routes/index' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const LayoutRoute = LayoutRouteImport.update({ id: '/_layout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, +} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -42,20 +46,16 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRoute, } as any) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any) const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ id: '/layout-b', path: '/layout-b', getParentRoute: () => LayoutLayout2Route, } as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, -} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -114,11 +114,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -128,13 +128,20 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute + } '/posts/': { id: '/posts/' path: '/' @@ -149,12 +156,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route } '/_layout/_layout-2/layout-b': { id: '/_layout/_layout-2/layout-b' @@ -163,13 +170,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport parentRoute: typeof LayoutLayout2Route } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route - } } } diff --git a/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.$postId.tsx b/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.$postId.tsx index 72109fc891..e8b66ddf5d 100644 --- a/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.$postId.tsx +++ b/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.$postId.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { ErrorComponent, useRouter } from '@tanstack/vue-router' import { useQuery } from '@tanstack/vue-query' @@ -5,6 +6,21 @@ import { PostNotFoundError } from '../posts' import { postQueryOptions } from '../postQueryOptions' import type { ErrorComponentProps } from '@tanstack/vue-router' +const PostComponent = defineComponent({ + setup() { + const params = Route.useParams() + useQuery(() => postQueryOptions(params.value.postId)) + const post = Route.useLoaderData() + + return () => ( +
+

{post.value.title}

+
{post.value.body}
+
+ ) + }, +}) + export const Route = createFileRoute('/posts/$postId')({ loader: ({ context: { queryClient }, params: { postId } }) => { return queryClient.ensureQueryData(postQueryOptions(postId)) @@ -32,16 +48,3 @@ export function PostErrorComponent({ error }: ErrorComponentProps) {
) } - -function PostComponent() { - const postId = Route.useParams().value.postId - useQuery(postQueryOptions(postId)) - const post = Route.useLoaderData() - - return ( -
-

{post.value.title}

-
{post.value.body}
-
- ) -} diff --git a/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.tsx b/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.tsx index f9e20f99d6..e1c35d59ad 100644 --- a/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.tsx +++ b/e2e/vue-router/basic-vue-query-file-based/src/routes/posts.tsx @@ -1,42 +1,45 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { useQuery } from '@tanstack/vue-query' import { postsQueryOptions } from '../postsQueryOptions' +const PostsComponent = defineComponent({ + setup() { + useQuery(postsQueryOptions) + const posts = Route.useLoaderData() + + return () => ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+ +
+ ) + }, +}) + export const Route = createFileRoute('/posts')({ loader: ({ context: { queryClient } }) => queryClient.ensureQueryData(postsQueryOptions), component: PostsComponent, }) - -function PostsComponent() { - useQuery(postsQueryOptions) - const posts = Route.useLoaderData() - - return ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) -} diff --git a/e2e/vue-router/basic-vue-query-file-based/tests/app.spec.ts b/e2e/vue-router/basic-vue-query-file-based/tests/app.spec.ts index d80e8dada5..2b42d6d589 100644 --- a/e2e/vue-router/basic-vue-query-file-based/tests/app.spec.ts +++ b/e2e/vue-router/basic-vue-query-file-based/tests/app.spec.ts @@ -1,24 +1,23 @@ -import { expect, test } from '@playwright/test' -import { getDummyServerPort } from '@tanstack/router-e2e-utils' -import packageJson from '../package.json' with { type: 'json' } +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') }) -test('GetPosts', async () => { - const port = await getDummyServerPort(packageJson.name) - const res = await fetch(`http://localhost:${port}/posts`) - - expect(res.status).toBe(200) - - const posts = await res.json() - +test('GetPosts with networking disabled', async ({ page, context }) => { + await page.goto('about:blank') + await context.setOffline(true) + const { status, posts, post } = await page.evaluate(async () => { + const response = await fetch('https://jsonplaceholder.typicode.com/posts') + const posts = await response.json() + const post = await fetch( + 'https://jsonplaceholder.typicode.com/posts/1', + ).then((r) => r.json()) + return { status: response.status, posts, post } + }) + expect(status).toBe(200) expect(posts.length).toBeGreaterThan(0) - - const postRes = await fetch(`http://localhost:${port}/posts/1`) - expect(postRes.status).toBe(200) - const post = await postRes.json() expect(post).toEqual(posts[0]) }) diff --git a/e2e/vue-router/basic-vue-query-file-based/tests/setup/global.setup.ts b/e2e/vue-router/basic-vue-query-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basic-vue-query-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic-vue-query-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/basic-vue-query-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basic-vue-query-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic-vue-query-file-based/tsconfig.json b/e2e/vue-router/basic-vue-query-file-based/tsconfig.json index 123a2f4122..28889522fc 100644 --- a/e2e/vue-router/basic-vue-query-file-based/tsconfig.json +++ b/e2e/vue-router/basic-vue-query-file-based/tsconfig.json @@ -10,7 +10,7 @@ "skipLibCheck": true, "noEmit": true, "resolveJsonModule": true, - "types": ["vite/client"] + "types": ["vite/client", "node"] }, "include": ["src", "tests"], "exclude": ["node_modules", "dist"] diff --git a/e2e/vue-router/basic-vue-query/package.json b/e2e/vue-router/basic-vue-query/package.json index 288d96018d..68f1a8c9ea 100644 --- a/e2e/vue-router/basic-vue-query/package.json +++ b/e2e/vue-router/basic-vue-query/package.json @@ -8,7 +8,7 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -16,7 +16,7 @@ "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, @@ -27,6 +27,6 @@ "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", "vite": "^8.0.14", - "vue-tsc": "^3.1.5" + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-router/basic-vue-query/playwright.config.ts b/e2e/vue-router/basic-vue-query/playwright.config.ts index 836ea41bd8..4eead86444 100644 --- a/e2e/vue-router/basic-vue-query/playwright.config.ts +++ b/e2e/vue-router/basic-vue-query/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-vue-query/src/main.tsx b/e2e/vue-router/basic-vue-query/src/main.tsx index 4f862a9b31..3235f26ce3 100644 --- a/e2e/vue-router/basic-vue-query/src/main.tsx +++ b/e2e/vue-router/basic-vue-query/src/main.tsx @@ -1,4 +1,4 @@ -import { createApp } from 'vue' +import { createApp, defineComponent } from 'vue' import { ErrorComponent, Link, @@ -108,6 +108,21 @@ function PostsIndexRouteComponent() { return
Select a post.
} +const PostRouteComponent = defineComponent({ + setup() { + const params = postRoute.useParams() + useQuery(() => postQueryOptions(params.value.postId)) + const post = postRoute.useLoaderData() + + return () => ( +
+

{post.value.title}

+
{post.value.body}
+
+ ) + }, +}) + const postRoute = createRoute({ getParentRoute: () => postsRoute, path: '$postId', @@ -137,19 +152,6 @@ function PostErrorComponent({ error }: ErrorComponentProps) { ) } -function PostRouteComponent() { - const postId = postRoute.useParams().value.postId - useQuery(postQueryOptions(postId)) - const post = postRoute.useLoaderData() - - return ( -
-

{post.value.title}

-
{post.value.body}
-
- ) -} - const layoutRoute = createRoute({ getParentRoute: () => rootRoute, id: '_layout', diff --git a/e2e/vue-router/basic-vue-query/src/posts.lazy.tsx b/e2e/vue-router/basic-vue-query/src/posts.lazy.tsx index eb844bc68d..d42d3d49dc 100644 --- a/e2e/vue-router/basic-vue-query/src/posts.lazy.tsx +++ b/e2e/vue-router/basic-vue-query/src/posts.lazy.tsx @@ -1,39 +1,42 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createLazyRoute } from '@tanstack/vue-router' import { useQuery } from '@tanstack/vue-query' import { postsQueryOptions } from './posts' +const PostsComponent = defineComponent({ + setup() { + const postsQuery = useQuery(postsQueryOptions) + const posts = postsQuery.data + + return () => ( +
+
    + {[ + ...((posts.value ?? []) as Array<{ id: string; title: string }>), + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+ +
+ ) + }, +}) + export const Route = createLazyRoute('/posts')({ component: PostsComponent, }) - -function PostsComponent() { - const postsQuery = useQuery(postsQueryOptions) - const posts = postsQuery.data - - return ( -
-
    - {[ - ...((posts.value ?? []) as Array<{ id: string; title: string }>), - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
- -
- ) -} diff --git a/e2e/vue-router/basic-vue-query/src/posts.ts b/e2e/vue-router/basic-vue-query/src/posts.ts index 18f8a9f93f..69e1814af5 100644 --- a/e2e/vue-router/basic-vue-query/src/posts.ts +++ b/e2e/vue-router/basic-vue-query/src/posts.ts @@ -9,11 +9,7 @@ type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/vue-router/basic-vue-query/tests/app.spec.ts b/e2e/vue-router/basic-vue-query/tests/app.spec.ts index 3e5a69ccaa..fbf093cd51 100644 --- a/e2e/vue-router/basic-vue-query/tests/app.spec.ts +++ b/e2e/vue-router/basic-vue-query/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/basic-vue-query/tests/setup/global.setup.ts b/e2e/vue-router/basic-vue-query/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basic-vue-query/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic-vue-query/tests/setup/global.teardown.ts b/e2e/vue-router/basic-vue-query/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basic-vue-query/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic/package.json b/e2e/vue-router/basic/package.json index ce95750e12..1b57dae772 100644 --- a/e2e/vue-router/basic/package.json +++ b/e2e/vue-router/basic/package.json @@ -8,13 +8,13 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, @@ -24,6 +24,6 @@ "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", "vite": "^8.0.14", - "vue-tsc": "^3.1.5" + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-router/basic/playwright.config.ts b/e2e/vue-router/basic/playwright.config.ts index 836ea41bd8..4eead86444 100644 --- a/e2e/vue-router/basic/playwright.config.ts +++ b/e2e/vue-router/basic/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic/src/main.tsx b/e2e/vue-router/basic/src/main.tsx index 3e5ac6f1e0..c2293018fc 100644 --- a/e2e/vue-router/basic/src/main.tsx +++ b/e2e/vue-router/basic/src/main.tsx @@ -1,4 +1,4 @@ -import { createApp } from 'vue' +import { createApp, defineComponent } from 'vue' import { ErrorComponent, Link, @@ -133,6 +133,20 @@ function PostErrorComponent({ error }: ErrorComponentProps) { return } +const PostComponent = defineComponent({ + setup() { + const post = postRoute.useLoaderData() + + return () => ( +
+

{post.value.title}

+
+
{post.value.body}
+
+ ) + }, +}) + const postRoute = createRoute({ getParentRoute: () => postsRoute, path: '$postId', @@ -141,18 +155,6 @@ const postRoute = createRoute({ component: PostComponent, }) -function PostComponent() { - const post = postRoute.useLoaderData() - - return ( -
-

{post.value.title}

-
-
{post.value.body}
-
- ) -} - const layoutRoute = createRoute({ getParentRoute: () => rootRoute, id: '_layout', @@ -315,14 +317,30 @@ const paramsPsNamedIndexRoute = createRoute({ }, }) +const ParamsNamedFoo = defineComponent({ + setup() { + const p = paramsPsNamedFooRoute.useParams() + return () => ( +
+

ParamsNamedFoo

+
{JSON.stringify(p.value)}
+
+ ) + }, +}) + const paramsPsNamedFooRoute = createRoute({ getParentRoute: () => paramsPsNamedRoute, path: '/$foo', - component: function ParamsNamedFoo() { - const p = paramsPsNamedFooRoute.useParams() - return ( + component: ParamsNamedFoo, +}) + +const ParamsNamedFooMarkdown = defineComponent({ + setup() { + const p = paramsPsNamedFooPrefixRoute.useParams() + return () => (
-

ParamsNamedFoo

+

ParamsNamedFooPrefix

{JSON.stringify(p.value)}
) @@ -332,11 +350,15 @@ const paramsPsNamedFooRoute = createRoute({ const paramsPsNamedFooPrefixRoute = createRoute({ getParentRoute: () => paramsPsNamedRoute, path: '/prefix{$foo}', - component: function ParamsNamedFooMarkdown() { - const p = paramsPsNamedFooPrefixRoute.useParams() - return ( + component: ParamsNamedFooMarkdown, +}) + +const ParamsNamedFooSuffix = defineComponent({ + setup() { + const p = paramsPsNamedFooSuffixRoute.useParams() + return () => (
-

ParamsNamedFooPrefix

+

ParamsNamedFooSuffix

{JSON.stringify(p.value)}
) @@ -346,15 +368,7 @@ const paramsPsNamedFooPrefixRoute = createRoute({ const paramsPsNamedFooSuffixRoute = createRoute({ getParentRoute: () => paramsPsNamedRoute, path: '/{$foo}suffix', - component: function ParamsNamedFooSuffix() { - const p = paramsPsNamedFooSuffixRoute.useParams() - return ( -
-

ParamsNamedFooSuffix

-
{JSON.stringify(p.value)}
-
- ) - }, + component: ParamsNamedFooSuffix, }) const paramsPsWildcardRoute = createRoute({ @@ -370,14 +384,30 @@ const paramsPsWildcardIndexRoute = createRoute({ }, }) +const ParamsWildcardSplat = defineComponent({ + setup() { + const p = paramsPsWildcardSplatRoute.useParams() + return () => ( +
+

ParamsWildcardSplat

+
{JSON.stringify(p.value)}
+
+ ) + }, +}) + const paramsPsWildcardSplatRoute = createRoute({ getParentRoute: () => paramsPsWildcardRoute, path: '$', - component: function ParamsWildcardSplat() { - const p = paramsPsWildcardSplatRoute.useParams() - return ( + component: ParamsWildcardSplat, +}) + +const ParamsWildcardSplatPrefix = defineComponent({ + setup() { + const p = paramsPsWildcardSplatPrefixRoute.useParams() + return () => (
-

ParamsWildcardSplat

+

ParamsWildcardSplatPrefix

{JSON.stringify(p.value)}
) @@ -387,11 +417,15 @@ const paramsPsWildcardSplatRoute = createRoute({ const paramsPsWildcardSplatPrefixRoute = createRoute({ getParentRoute: () => paramsPsWildcardRoute, path: 'prefix{$}', - component: function ParamsWildcardSplatPrefix() { - const p = paramsPsWildcardSplatPrefixRoute.useParams() - return ( + component: ParamsWildcardSplatPrefix, +}) + +const ParamsWildcardSplatSuffix = defineComponent({ + setup() { + const p = paramsPsWildcardSplatSuffixRoute.useParams() + return () => (
-

ParamsWildcardSplatPrefix

+

ParamsWildcardSplatSuffix

{JSON.stringify(p.value)}
) @@ -401,15 +435,7 @@ const paramsPsWildcardSplatPrefixRoute = createRoute({ const paramsPsWildcardSplatSuffixRoute = createRoute({ getParentRoute: () => paramsPsWildcardRoute, path: '{$}suffix', - component: function ParamsWildcardSplatSuffix() { - const p = paramsPsWildcardSplatSuffixRoute.useParams() - return ( -
-

ParamsWildcardSplatSuffix

-
{JSON.stringify(p.value)}
-
- ) - }, + component: ParamsWildcardSplatSuffix, }) const routeTree = rootRoute.addChildren([ diff --git a/e2e/vue-router/basic/src/posts.lazy.tsx b/e2e/vue-router/basic/src/posts.lazy.tsx index b2df740010..a236404d84 100644 --- a/e2e/vue-router/basic/src/posts.lazy.tsx +++ b/e2e/vue-router/basic/src/posts.lazy.tsx @@ -1,36 +1,39 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createLazyRoute } from '@tanstack/vue-router' +const PostsComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + + return () => ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+ +
+ ) + }, +}) + export const Route = createLazyRoute('/posts')({ component: PostsComponent, }) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
- -
- ) -} diff --git a/e2e/vue-router/basic/src/posts.ts b/e2e/vue-router/basic/src/posts.ts index e859645746..f72d16fee3 100644 --- a/e2e/vue-router/basic/src/posts.ts +++ b/e2e/vue-router/basic/src/posts.ts @@ -8,11 +8,7 @@ type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/vue-router/basic/tests/app.spec.ts b/e2e/vue-router/basic/tests/app.spec.ts index ec0e24d8a4..9c0a6b6901 100644 --- a/e2e/vue-router/basic/tests/app.spec.ts +++ b/e2e/vue-router/basic/tests/app.spec.ts @@ -1,8 +1,7 @@ -import { expect, test } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from '../package.json' with { type: 'json' } +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/basic/tests/params.spec.ts b/e2e/vue-router/basic/tests/params.spec.ts index ac18f39864..f673138047 100644 --- a/e2e/vue-router/basic/tests/params.spec.ts +++ b/e2e/vue-router/basic/tests/params.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.describe('params operations + prefix/suffix', () => { test.beforeEach(async ({ page }) => { diff --git a/e2e/vue-router/basic/tests/setup/global.setup.ts b/e2e/vue-router/basic/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/basic/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/basic/tests/setup/global.teardown.ts b/e2e/vue-router/basic/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/basic/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/generator-cli-only/package.json b/e2e/vue-router/generator-cli-only/package.json index 410a14b742..f9324643ac 100644 --- a/e2e/vue-router/generator-cli-only/package.json +++ b/e2e/vue-router/generator-cli-only/package.json @@ -8,14 +8,14 @@ "build": "tsr generate && vite build && tsc --noEmit", "preview": "vite preview", "start": "tsr generate && vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/router-cli": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "vue": "^3.5.16", "tailwindcss": "^4.2.2" }, @@ -26,6 +26,6 @@ "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", "vite": "^8.0.14", - "vue-tsc": "^3.1.5" + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-router/generator-cli-only/playwright.config.ts b/e2e/vue-router/generator-cli-only/playwright.config.ts index c9d9a76ae7..4eead86444 100644 --- a/e2e/vue-router/generator-cli-only/playwright.config.ts +++ b/e2e/vue-router/generator-cli-only/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/generator-cli-only/src/posts.ts b/e2e/vue-router/generator-cli-only/src/posts.ts index e859645746..f72d16fee3 100644 --- a/e2e/vue-router/generator-cli-only/src/posts.ts +++ b/e2e/vue-router/generator-cli-only/src/posts.ts @@ -8,11 +8,7 @@ type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/vue-router/generator-cli-only/src/routeTree.gen.ts b/e2e/vue-router/generator-cli-only/src/routeTree.gen.ts index c769c841f0..decb53754c 100644 --- a/e2e/vue-router/generator-cli-only/src/routeTree.gen.ts +++ b/e2e/vue-router/generator-cli-only/src/routeTree.gen.ts @@ -9,15 +9,20 @@ // 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 PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as PostsRouteRouteImport } from './routes/posts.route' -import { Route as IndexRouteImport } from './routes/index' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, @@ -27,11 +32,11 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, + } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -42,10 +47,11 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRouteRoute, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -53,12 +59,6 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -117,6 +117,13 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/_pathlessLayout': { id: '/_pathlessLayout' path: '' @@ -131,12 +138,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' + path: '' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/posts/': { id: '/posts/' @@ -152,12 +159,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRouteRoute } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -166,13 +173,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } } } diff --git a/e2e/vue-router/generator-cli-only/src/routes/posts.$postId.tsx b/e2e/vue-router/generator-cli-only/src/routes/posts.$postId.tsx index f4f1b04f88..bb2d728afd 100644 --- a/e2e/vue-router/generator-cli-only/src/routes/posts.$postId.tsx +++ b/e2e/vue-router/generator-cli-only/src/routes/posts.$postId.tsx @@ -1,7 +1,21 @@ +import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + + return () => ( +
+

{post.value.title}

+
{post.value.body}
+
+ ) + }, +}) + export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent, @@ -14,14 +28,3 @@ export const Route = createFileRoute('/posts/$postId')({ export function PostErrorComponent({ error }: ErrorComponentProps) { return } - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

{post.value.title}

-
{post.value.body}
-
- ) -} diff --git a/e2e/vue-router/generator-cli-only/src/routes/posts.route.tsx b/e2e/vue-router/generator-cli-only/src/routes/posts.route.tsx index eaaa35fd5c..518bdc3d70 100644 --- a/e2e/vue-router/generator-cli-only/src/routes/posts.route.tsx +++ b/e2e/vue-router/generator-cli-only/src/routes/posts.route.tsx @@ -1,39 +1,42 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../posts' +const PostsLayoutComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + + return () => ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+ +
+ ) + }, +}) + export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsLayoutComponent, }) - -function PostsLayoutComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) -} diff --git a/e2e/vue-router/generator-cli-only/tests/app.spec.ts b/e2e/vue-router/generator-cli-only/tests/app.spec.ts index 5a83a314f2..ced5ac9310 100644 --- a/e2e/vue-router/generator-cli-only/tests/app.spec.ts +++ b/e2e/vue-router/generator-cli-only/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/generator-cli-only/tests/setup/global.setup.ts b/e2e/vue-router/generator-cli-only/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/generator-cli-only/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/generator-cli-only/tests/setup/global.teardown.ts b/e2e/vue-router/generator-cli-only/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/generator-cli-only/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/js-only-file-based/package.json b/e2e/vue-router/js-only-file-based/package.json index d7f062038e..cda098978c 100644 --- a/e2e/vue-router/js-only-file-based/package.json +++ b/e2e/vue-router/js-only-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -17,7 +17,7 @@ "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, diff --git a/e2e/vue-router/js-only-file-based/playwright.config.ts b/e2e/vue-router/js-only-file-based/playwright.config.ts index 4f93bc1413..0925936d55 100644 --- a/e2e/vue-router/js-only-file-based/playwright.config.ts +++ b/e2e/vue-router/js-only-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -18,18 +13,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/js-only-file-based/src/posts.js b/e2e/vue-router/js-only-file-based/src/posts.js index 979e5e381c..36c1c281f6 100644 --- a/e2e/vue-router/js-only-file-based/src/posts.js +++ b/e2e/vue-router/js-only-file-based/src/posts.js @@ -2,11 +2,7 @@ import axios from 'redaxios' export class NotFoundError extends Error {} -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/vue-router/js-only-file-based/src/routeTree.gen.ts b/e2e/vue-router/js-only-file-based/src/routeTree.gen.ts index c769c841f0..decb53754c 100644 --- a/e2e/vue-router/js-only-file-based/src/routeTree.gen.ts +++ b/e2e/vue-router/js-only-file-based/src/routeTree.gen.ts @@ -9,15 +9,20 @@ // 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 PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as PostsRouteRouteImport } from './routes/posts.route' -import { Route as IndexRouteImport } from './routes/index' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, @@ -27,11 +32,11 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, + } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -42,10 +47,11 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRouteRoute, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -53,12 +59,6 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -117,6 +117,13 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/_pathlessLayout': { id: '/_pathlessLayout' path: '' @@ -131,12 +138,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' + path: '' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/posts/': { id: '/posts/' @@ -152,12 +159,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRouteRoute } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -166,13 +173,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } } } diff --git a/e2e/vue-router/js-only-file-based/src/routes/posts.$postId.jsx b/e2e/vue-router/js-only-file-based/src/routes/posts.$postId.jsx index b769e23862..05599a6780 100644 --- a/e2e/vue-router/js-only-file-based/src/routes/posts.$postId.jsx +++ b/e2e/vue-router/js-only-file-based/src/routes/posts.$postId.jsx @@ -1,8 +1,22 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { ErrorComponent } from '@tanstack/vue-router' import { fetchPost } from '../posts' +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + + return () => ( +
+

{post.value.title}

+
{post.value.body}
+
+ ) + }, +}) + export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent, @@ -15,14 +29,3 @@ export const Route = createFileRoute('/posts/$postId')({ export function PostErrorComponent({ error }) { return } - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

{post.value.title}

-
{post.value.body}
-
- ) -} diff --git a/e2e/vue-router/js-only-file-based/src/routes/posts.route.jsx b/e2e/vue-router/js-only-file-based/src/routes/posts.route.jsx index c1fef7213d..5925dbed54 100644 --- a/e2e/vue-router/js-only-file-based/src/routes/posts.route.jsx +++ b/e2e/vue-router/js-only-file-based/src/routes/posts.route.jsx @@ -1,41 +1,44 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { Link, Outlet } from '@tanstack/vue-router' import { fetchPosts } from '../posts' +const PostsLayoutComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + + return () => ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+ +
+ ) + }, +}) + export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsLayoutComponent, }) - -function PostsLayoutComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) -} diff --git a/e2e/vue-router/js-only-file-based/tests/app.spec.ts b/e2e/vue-router/js-only-file-based/tests/app.spec.ts index 5a83a314f2..ced5ac9310 100644 --- a/e2e/vue-router/js-only-file-based/tests/app.spec.ts +++ b/e2e/vue-router/js-only-file-based/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/js-only-file-based/tests/setup/global.setup.ts b/e2e/vue-router/js-only-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/js-only-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/js-only-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/js-only-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/js-only-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/rspack-basic-file-based/package.json b/e2e/vue-router/rspack-basic-file-based/package.json index ba0ae7efde..93439f7d5b 100644 --- a/e2e/vue-router/rspack-basic-file-based/package.json +++ b/e2e/vue-router/rspack-basic-file-based/package.json @@ -7,17 +7,17 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "vue": "^3.5.16" }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.0.11", + "@rsbuild/core": "^2.3.1", "@rsbuild/plugin-babel": "^1.1.2", "@rsbuild/plugin-vue": "^1.2.7", "@rsbuild/plugin-vue-jsx": "^2.0.0", @@ -27,7 +27,8 @@ "@tanstack/virtual-file-routes": "workspace:^", "postcss": "^8.5.1", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", - "vue-tsc": "^3.1.5" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-router/rspack-basic-file-based/playwright.config.ts b/e2e/vue-router/rspack-basic-file-based/playwright.config.ts index 5f20415459..4eead86444 100644 --- a/e2e/vue-router/rspack-basic-file-based/playwright.config.ts +++ b/e2e/vue-router/rspack-basic-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `PUBLIC_NODE_ENV="test" PUBLIC_EXTERNAL_PORT=${EXTERNAL_PORT} PUBLIC_SERVER_PORT=${PORT} pnpm build && PUBLIC_NODE_ENV="test" PUBLIC_EXTERNAL_PORT=${EXTERNAL_PORT} PUBLIC_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/rspack-basic-file-based/rsbuild.config.ts b/e2e/vue-router/rspack-basic-file-based/rsbuild.config.ts index d5e4b7456c..c91449b6c3 100644 --- a/e2e/vue-router/rspack-basic-file-based/rsbuild.config.ts +++ b/e2e/vue-router/rspack-basic-file-based/rsbuild.config.ts @@ -12,19 +12,6 @@ export default defineConfig({ pluginVue(), pluginVueJsx(), ], - source: { - define: { - // Rsbuild only defines `import.meta.env.PUBLIC_*` when the env var exists. - // When it doesn't, rspack can transform `import.meta.env` to `void 0`, which - // makes `import.meta.env.PUBLIC_*` crash at runtime. - 'import.meta.env.PUBLIC_NODE_ENV': JSON.stringify( - process.env.PUBLIC_NODE_ENV ?? '', - ), - 'import.meta.env.PUBLIC_EXTERNAL_PORT': JSON.stringify( - process.env.PUBLIC_EXTERNAL_PORT ?? '', - ), - }, - }, tools: { rspack: { plugins: [tanstackRouter({ target: 'vue', autoCodeSplitting: true })], diff --git a/e2e/vue-router/rspack-basic-file-based/src/posts.tsx b/e2e/vue-router/rspack-basic-file-based/src/posts.tsx index 0b557a0f65..5f5463a668 100644 --- a/e2e/vue-router/rspack-basic-file-based/src/posts.tsx +++ b/e2e/vue-router/rspack-basic-file-based/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.PUBLIC_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/rspack-basic-file-based/src/routes/posts.$postId.tsx b/e2e/vue-router/rspack-basic-file-based/src/routes/posts.$postId.tsx index e271c139f5..a86ea0762f 100644 --- a/e2e/vue-router/rspack-basic-file-based/src/routes/posts.$postId.tsx +++ b/e2e/vue-router/rspack-basic-file-based/src/routes/posts.$postId.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -6,6 +7,19 @@ export function PostErrorComponent({ error }: ErrorComponentProps) { return } +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + + return () => ( +
+

{post.value.title}

+
{post.value.body}
+
+ ) + }, +}) + export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent, @@ -14,14 +28,3 @@ export const Route = createFileRoute('/posts/$postId')({ }, component: PostComponent, }) - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

{post.value.title}

-
{post.value.body}
-
- ) -} diff --git a/e2e/vue-router/rspack-basic-file-based/src/routes/posts.tsx b/e2e/vue-router/rspack-basic-file-based/src/routes/posts.tsx index 653918c370..90744370ff 100644 --- a/e2e/vue-router/rspack-basic-file-based/src/routes/posts.tsx +++ b/e2e/vue-router/rspack-basic-file-based/src/routes/posts.tsx @@ -1,40 +1,43 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../posts' +const PostsComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + + return () => ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+ +
+ ) + }, +}) + export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) -} diff --git a/e2e/vue-router/rspack-basic-file-based/tests/app.spec.ts b/e2e/vue-router/rspack-basic-file-based/tests/app.spec.ts index 10beff655f..d230263bfe 100644 --- a/e2e/vue-router/rspack-basic-file-based/tests/app.spec.ts +++ b/e2e/vue-router/rspack-basic-file-based/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/rspack-basic-file-based/tests/setup/global.setup.ts b/e2e/vue-router/rspack-basic-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/rspack-basic-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/rspack-basic-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/rspack-basic-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/rspack-basic-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/package.json b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/package.json index 9b55dcc6f9..536435a09e 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/package.json +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/package.json @@ -7,17 +7,17 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "vue": "^3.5.16" }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.0.11", + "@rsbuild/core": "^2.3.1", "@rsbuild/plugin-babel": "^1.1.2", "@rsbuild/plugin-vue": "^1.2.7", "@rsbuild/plugin-vue-jsx": "^2.0.0", @@ -27,7 +27,8 @@ "@tanstack/virtual-file-routes": "workspace:^", "postcss": "^8.5.1", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", - "vue-tsc": "^3.1.5" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts index bf3adc082c..1c1d021f2f 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -17,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `PUBLIC_NODE_ENV="test" PUBLIC_EXTERNAL_PORT=${EXTERNAL_PORT} PUBLIC_SERVER_PORT=${PORT} pnpm build && PUBLIC_SERVER_PORT=${PORT} pnpm start --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm start --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/rsbuild.config.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/rsbuild.config.ts index b09f6ccda8..e5c7e8b77e 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/rsbuild.config.ts +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/rsbuild.config.ts @@ -12,19 +12,6 @@ export default defineConfig({ pluginVue(), pluginVueJsx(), ], - source: { - define: { - // Rsbuild only defines `import.meta.env.PUBLIC_*` when the env var exists. - // When it doesn't, rspack can transform `import.meta.env` to `void 0`, which - // makes `import.meta.env.PUBLIC_*` crash at runtime. - 'import.meta.env.PUBLIC_NODE_ENV': JSON.stringify( - process.env.PUBLIC_NODE_ENV ?? '', - ), - 'import.meta.env.PUBLIC_EXTERNAL_PORT': JSON.stringify( - process.env.PUBLIC_EXTERNAL_PORT ?? '', - ), - }, - }, tools: { rspack: { plugins: [ diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx index 0b557a0f65..5f5463a668 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.PUBLIC_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx index cb1924e993..5e3fe4d130 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts-detail.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -6,6 +7,19 @@ export function PostErrorComponent({ error }: ErrorComponentProps) { return } +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + + return () => ( +
+

{post.value.title}

+
{post.value.body}
+
+ ) + }, +}) + export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent as any, @@ -14,14 +28,3 @@ export const Route = createFileRoute('/posts/$postId')({ }, component: PostComponent, }) - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

{post.value.title}

-
{post.value.body}
-
- ) -} diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx index 265faaf650..2a4e8deddd 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/src/routes/posts/posts.tsx @@ -1,39 +1,42 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../../posts' +const PostsComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + + return () => ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+ +
+ ) + }, +}) + export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- -
- ) -} diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts index 10beff655f..d230263bfe 100644 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/package.json b/e2e/vue-router/scroll-restoration-sandbox-vite/package.json index ebcea6fb39..d071ee546a 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/package.json +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/package.json @@ -11,14 +11,14 @@ "start": "vite", "test:e2e:browser": "VITE_APP_HISTORY=browser playwright test --config=playwright.browser.config.ts --project=chromium", "test:e2e:hash": "VITE_APP_HISTORY=hash playwright test --config=playwright.hash.config.ts --project=chromium", - "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:browser && pnpm run test:e2e:hash" + "test:e2e": "pnpm run test:e2e:browser && pnpm run test:e2e:hash" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/router-plugin": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16", "zod": "^4.4.3" @@ -30,6 +30,16 @@ "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", "vite": "^8.0.14", - "vue-tsc": "^3.1.5" + "vue-tsc": "^3.3.8" + }, + "nx": { + "targets": { + "test:e2e": { + "outputs": [ + "...", + "{projectRoot}/dist-hash" + ] + } + } } } diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts index 9d7691f0fd..e2681daea5 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts @@ -1,15 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, - resolveRuntimeSuffix, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort( - packageJson.name + `-${resolveRuntimeSuffix('browser')}`, -) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=browser pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `VITE_APP_HISTORY=browser pnpm build && VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts index 80a340cef4..445616b9bd 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts @@ -1,15 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, - resolveRuntimeSuffix, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort( - packageJson.name + `-${resolveRuntimeSuffix('hash')}`, -) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,18 +12,15 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=hash vite build --outDir dist-hash && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `VITE_APP_HISTORY=hash vite build --outDir dist-hash && VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx b/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx index c6cba486ab..bc56dff904 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx @@ -12,11 +12,7 @@ export type PostType = { export class PostNotFoundError extends Error {} -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts index 69dda324fe..e85be2bf37 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts @@ -12,10 +12,10 @@ import { createFileRoute } from '@tanstack/vue-router' import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as testsPageWithSearchRouteImport } from './routes/(tests)/page-with-search' -import { Route as testsNormalPageRouteImport } from './routes/(tests)/normal-page' -import { Route as testsLazyWithLoaderPageRouteImport } from './routes/(tests)/lazy-with-loader-page' import { Route as testsLazyPageRouteImport } from './routes/(tests)/lazy-page' +import { Route as testsLazyWithLoaderPageRouteImport } from './routes/(tests)/lazy-with-loader-page' +import { Route as testsNormalPageRouteImport } from './routes/(tests)/normal-page' +import { Route as testsPageWithSearchRouteImport } from './routes/(tests)/page-with-search' const testsVirtualPageLazyRouteImport = createFileRoute( '/(tests)/virtual-page', @@ -26,23 +26,13 @@ const IndexRoute = IndexRouteImport.update({ path: '/', getParentRoute: () => rootRouteImport, } as any) -const testsVirtualPageLazyRoute = testsVirtualPageLazyRouteImport +const testsLazyPageRoute = testsLazyPageRouteImport .update({ - id: '/(tests)/virtual-page', - path: '/virtual-page', + id: '/(tests)/lazy-page', + path: '/lazy-page', getParentRoute: () => rootRouteImport, } as any) - .lazy(() => import('./routes/(tests)/virtual-page.lazy').then((d) => d.Route)) -const testsPageWithSearchRoute = testsPageWithSearchRouteImport.update({ - id: '/(tests)/page-with-search', - path: '/page-with-search', - getParentRoute: () => rootRouteImport, -} as any) -const testsNormalPageRoute = testsNormalPageRouteImport.update({ - id: '/(tests)/normal-page', - path: '/normal-page', - getParentRoute: () => rootRouteImport, -} as any) + .lazy(() => import('./routes/(tests)/lazy-page.lazy').then((d) => d.Route)) const testsLazyWithLoaderPageRoute = testsLazyWithLoaderPageRouteImport .update({ id: '/(tests)/lazy-with-loader-page', @@ -52,13 +42,23 @@ const testsLazyWithLoaderPageRoute = testsLazyWithLoaderPageRouteImport .lazy(() => import('./routes/(tests)/lazy-with-loader-page.lazy').then((d) => d.Route), ) -const testsLazyPageRoute = testsLazyPageRouteImport +const testsNormalPageRoute = testsNormalPageRouteImport.update({ + id: '/(tests)/normal-page', + path: '/normal-page', + getParentRoute: () => rootRouteImport, +} as any) +const testsPageWithSearchRoute = testsPageWithSearchRouteImport.update({ + id: '/(tests)/page-with-search', + path: '/page-with-search', + getParentRoute: () => rootRouteImport, +} as any) +const testsVirtualPageLazyRoute = testsVirtualPageLazyRouteImport .update({ - id: '/(tests)/lazy-page', - path: '/lazy-page', + id: '/(tests)/virtual-page', + path: '/virtual-page', getParentRoute: () => rootRouteImport, } as any) - .lazy(() => import('./routes/(tests)/lazy-page.lazy').then((d) => d.Route)) + .lazy(() => import('./routes/(tests)/virtual-page.lazy').then((d) => d.Route)) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -130,25 +130,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/(tests)/virtual-page': { - id: '/(tests)/virtual-page' - path: '/virtual-page' - fullPath: '/virtual-page' - preLoaderRoute: typeof testsVirtualPageLazyRouteImport - parentRoute: typeof rootRouteImport - } - '/(tests)/page-with-search': { - id: '/(tests)/page-with-search' - path: '/page-with-search' - fullPath: '/page-with-search' - preLoaderRoute: typeof testsPageWithSearchRouteImport - parentRoute: typeof rootRouteImport - } - '/(tests)/normal-page': { - id: '/(tests)/normal-page' - path: '/normal-page' - fullPath: '/normal-page' - preLoaderRoute: typeof testsNormalPageRouteImport + '/(tests)/lazy-page': { + id: '/(tests)/lazy-page' + path: '/lazy-page' + fullPath: '/lazy-page' + preLoaderRoute: typeof testsLazyPageRouteImport parentRoute: typeof rootRouteImport } '/(tests)/lazy-with-loader-page': { @@ -158,11 +144,25 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof testsLazyWithLoaderPageRouteImport parentRoute: typeof rootRouteImport } - '/(tests)/lazy-page': { - id: '/(tests)/lazy-page' - path: '/lazy-page' - fullPath: '/lazy-page' - preLoaderRoute: typeof testsLazyPageRouteImport + '/(tests)/normal-page': { + id: '/(tests)/normal-page' + path: '/normal-page' + fullPath: '/normal-page' + preLoaderRoute: typeof testsNormalPageRouteImport + parentRoute: typeof rootRouteImport + } + '/(tests)/page-with-search': { + id: '/(tests)/page-with-search' + path: '/page-with-search' + fullPath: '/page-with-search' + preLoaderRoute: typeof testsPageWithSearchRouteImport + parentRoute: typeof rootRouteImport + } + '/(tests)/virtual-page': { + id: '/(tests)/virtual-page' + path: '/virtual-page' + fullPath: '/virtual-page' + preLoaderRoute: typeof testsVirtualPageLazyRouteImport parentRoute: typeof rootRouteImport } } diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/app.spec.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/app.spec.ts index 5f226c6db3..067f0341c4 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/app.spec.ts +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' import { toRuntimePath } from '@tanstack/router-e2e-utils' test('Smoke - Renders home', async ({ page }) => { diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/scroll-restoration-sandbox-vite/tsconfig.json b/e2e/vue-router/scroll-restoration-sandbox-vite/tsconfig.json index 3e5b04987f..b47cca9589 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/tsconfig.json +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/tsconfig.json @@ -12,5 +12,5 @@ "allowJs": true, "types": ["vite/client", "node"] }, - "exclude": ["node_modules", "dist"] + "exclude": ["node_modules", "dist", "dist-hash"] } diff --git a/e2e/vue-router/sentry-integration/package.json b/e2e/vue-router/sentry-integration/package.json index 897331f1b8..045ddd99be 100644 --- a/e2e/vue-router/sentry-integration/package.json +++ b/e2e/vue-router/sentry-integration/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@sentry/vue": "^10.32.0", @@ -17,7 +17,7 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, @@ -27,6 +27,6 @@ "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", "vite": "^8.0.14", - "vue-tsc": "^3.1.5" + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-router/sentry-integration/playwright.config.ts b/e2e/vue-router/sentry-integration/playwright.config.ts index 0c5cee43e4..6a684ac89e 100644 --- a/e2e/vue-router/sentry-integration/playwright.config.ts +++ b/e2e/vue-router/sentry-integration/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/view-transitions/package.json b/e2e/vue-router/view-transitions/package.json index 82f88dbe64..21a0f1d8a0 100644 --- a/e2e/vue-router/view-transitions/package.json +++ b/e2e/vue-router/view-transitions/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -17,7 +17,7 @@ "@tanstack/vue-query-devtools": "^6.1.2", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "vue": "^3.5.16" }, @@ -28,6 +28,6 @@ "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", "vite": "^8.0.14", - "vue-tsc": "^3.1.5" + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-router/view-transitions/playwright.config.ts b/e2e/vue-router/view-transitions/playwright.config.ts index c5de6b5611..4eead86444 100644 --- a/e2e/vue-router/view-transitions/playwright.config.ts +++ b/e2e/vue-router/view-transitions/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -22,13 +17,10 @@ export default defineConfig({ baseURL, }, - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - webServer: { - command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && pnpm preview --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-router/view-transitions/src/routeTree.gen.ts b/e2e/vue-router/view-transitions/src/routeTree.gen.ts index 465362a7a2..04708c29a8 100644 --- a/e2e/vue-router/view-transitions/src/routeTree.gen.ts +++ b/e2e/vue-router/view-transitions/src/routeTree.gen.ts @@ -9,16 +9,16 @@ // 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 HowItWorksRouteImport } from './routes/how-it-works' -import { Route as ExploreRouteImport } from './routes/explore' -import { Route as PostsRouteRouteImport } from './routes/posts.route' import { Route as IndexRouteImport } from './routes/index' +import { Route as ExploreRouteImport } from './routes/explore' +import { Route as HowItWorksRouteImport } from './routes/how-it-works' +import { Route as PostsRouteRouteImport } from './routes/posts.route' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -const HowItWorksRoute = HowItWorksRouteImport.update({ - id: '/how-it-works', - path: '/how-it-works', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const ExploreRoute = ExploreRouteImport.update({ @@ -26,16 +26,16 @@ const ExploreRoute = ExploreRouteImport.update({ path: '/explore', getParentRoute: () => rootRouteImport, } as any) +const HowItWorksRoute = HowItWorksRouteImport.update({ + id: '/how-it-works', + path: '/how-it-works', + getParentRoute: () => rootRouteImport, +} as any) const PostsRouteRoute = PostsRouteRouteImport.update({ id: '/posts', path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -101,11 +101,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/how-it-works': { - id: '/how-it-works' - path: '/how-it-works' - fullPath: '/how-it-works' - preLoaderRoute: typeof HowItWorksRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/explore': { @@ -115,6 +115,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ExploreRouteImport parentRoute: typeof rootRouteImport } + '/how-it-works': { + id: '/how-it-works' + path: '/how-it-works' + fullPath: '/how-it-works' + preLoaderRoute: typeof HowItWorksRouteImport + parentRoute: typeof rootRouteImport + } '/posts': { id: '/posts' path: '/posts' @@ -122,13 +129,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/posts/': { id: '/posts/' path: '/' diff --git a/e2e/vue-router/view-transitions/src/routes/posts.$postId.tsx b/e2e/vue-router/view-transitions/src/routes/posts.$postId.tsx index e271c139f5..a86ea0762f 100644 --- a/e2e/vue-router/view-transitions/src/routes/posts.$postId.tsx +++ b/e2e/vue-router/view-transitions/src/routes/posts.$postId.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -6,6 +7,19 @@ export function PostErrorComponent({ error }: ErrorComponentProps) { return } +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + + return () => ( +
+

{post.value.title}

+
{post.value.body}
+
+ ) + }, +}) + export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent, @@ -14,14 +28,3 @@ export const Route = createFileRoute('/posts/$postId')({ }, component: PostComponent, }) - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

{post.value.title}

-
{post.value.body}
-
- ) -} diff --git a/e2e/vue-router/view-transitions/src/routes/posts.route.tsx b/e2e/vue-router/view-transitions/src/routes/posts.route.tsx index 01d90b7ad6..6802b073f6 100644 --- a/e2e/vue-router/view-transitions/src/routes/posts.route.tsx +++ b/e2e/vue-router/view-transitions/src/routes/posts.route.tsx @@ -1,43 +1,46 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../posts' +const PostsLayoutComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + + return () => ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+
+
+ +
+
+ ) + }, +}) + export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsLayoutComponent, }) - -function PostsLayoutComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
-
- -
-
- ) -} diff --git a/e2e/vue-router/view-transitions/tests/app.spec.ts b/e2e/vue-router/view-transitions/tests/app.spec.ts index 472bd6ed0b..6c1ccf1a6e 100644 --- a/e2e/vue-router/view-transitions/tests/app.spec.ts +++ b/e2e/vue-router/view-transitions/tests/app.spec.ts @@ -1,4 +1,4 @@ -import { test } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-router/view-transitions/tests/setup/global.setup.ts b/e2e/vue-router/view-transitions/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-router/view-transitions/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/view-transitions/tests/setup/global.teardown.ts b/e2e/vue-router/view-transitions/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-router/view-transitions/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts b/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts index 31d8b12b04..e62662a1d2 100644 --- a/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts +++ b/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.addInitScript(() => { diff --git a/e2e/vue-start/basic-auth/package.json b/e2e/vue-start/basic-auth/package.json index 25de0c6b80..7f6fb798da 100644 --- a/e2e/vue-start/basic-auth/package.json +++ b/e2e/vue-start/basic-auth/package.json @@ -10,7 +10,7 @@ "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", "prisma-generate": "prisma generate", - "test:e2e": "rm -rf port*.txt; mkdir -p .tmp; rm -f .tmp/dev.db .tmp/dev.db-journal .tmp/dev.db-wal .tmp/dev.db-shm; export DATABASE_URL=file:./.tmp/dev.db; pnpm run prisma-generate && pnpm exec prisma migrate deploy && playwright test --project=chromium" + "test:e2e": "mkdir -p .tmp; rm -f .tmp/dev.db .tmp/dev.db-journal .tmp/dev.db-wal .tmp/dev.db-shm; export DATABASE_URL=file:./.tmp/dev.db; pnpm run prisma-generate && pnpm exec prisma migrate deploy && playwright test --project=chromium" }, "dependencies": { "@libsql/client": "^0.15.15", @@ -19,7 +19,8 @@ "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "redaxios": "^0.5.1", + "iron-session": "^9.0.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "vue": "^3.5.25" }, @@ -32,9 +33,21 @@ "@vitejs/plugin-vue-jsx": "^5.1.5", "dotenv": "^17.2.3", "prisma": "^7.0.0", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" + }, + "nx": { + "targets": { + "test:e2e": { + "outputs": [ + "...", + "{projectRoot}/.tmp", + "{projectRoot}/src/prisma-generated" + ] + } + } } } diff --git a/e2e/vue-start/basic-auth/playwright.config.ts b/e2e/vue-start/basic-auth/playwright.config.ts index 18b8905468..82678ac00b 100644 --- a/e2e/vue-start/basic-auth/playwright.config.ts +++ b/e2e/vue-start/basic-auth/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-start/basic-auth/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/basic-auth/src/components/DefaultCatchBoundary.tsx index 02caf56456..0687372ae0 100644 --- a/e2e/vue-start/basic-auth/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/basic-auth/src/components/DefaultCatchBoundary.tsx @@ -1,3 +1,5 @@ +import { defineComponent } from 'vue' +import type { PropType } from 'vue' import { ErrorComponent, Link, @@ -6,46 +8,54 @@ import { } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - - console.error(error) - - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} +export const DefaultCatchBoundary = defineComponent({ + props: { + error: { + type: Object as PropType, + required: true, + }, + }, + setup(props) { + const router = useRouter() + const isRoot = useLocation({ + select: (location) => location.pathname === '/', + }) + return () => { + console.error(props.error) + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) + } + }, +}) diff --git a/e2e/vue-start/basic-auth/src/routeTree.gen.ts b/e2e/vue-start/basic-auth/src/routeTree.gen.ts index a0a61b0279..058f8674ac 100644 --- a/e2e/vue-start/basic-auth/src/routeTree.gen.ts +++ b/e2e/vue-start/basic-auth/src/routeTree.gen.ts @@ -9,23 +9,22 @@ // 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 SignupRouteImport } from './routes/signup' -import { Route as LogoutRouteImport } from './routes/logout' -import { Route as LoginRouteImport } from './routes/login' -import { Route as AuthedRouteImport } from './routes/_authed' import { Route as IndexRouteImport } from './routes/index' +import { Route as AuthedRouteImport } from './routes/_authed' +import { Route as LoginRouteImport } from './routes/login' +import { Route as LogoutRouteImport } from './routes/logout' +import { Route as SignupRouteImport } from './routes/signup' import { Route as AuthedPostsRouteImport } from './routes/_authed/posts' import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' -const SignupRoute = SignupRouteImport.update({ - id: '/signup', - path: '/signup', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', getParentRoute: () => rootRouteImport, } as any) const LoginRoute = LoginRouteImport.update({ @@ -33,13 +32,14 @@ const LoginRoute = LoginRouteImport.update({ path: '/login', getParentRoute: () => rootRouteImport, } as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', +const LogoutRoute = LogoutRouteImport.update({ + id: '/logout', + path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SignupRoute = SignupRouteImport.update({ + id: '/signup', + path: '/signup', getParentRoute: () => rootRouteImport, } as any) const AuthedPostsRoute = AuthedPostsRouteImport.update({ @@ -120,25 +120,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/signup': { - id: '/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof SignupRouteImport - parentRoute: typeof rootRouteImport - } - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport - parentRoute: typeof rootRouteImport - } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_authed': { @@ -148,11 +134,25 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof AuthedRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport + } + '/logout': { + id: '/logout' + path: '/logout' + fullPath: '/logout' + preLoaderRoute: typeof LogoutRouteImport + parentRoute: typeof rootRouteImport + } + '/signup': { + id: '/signup' + path: '/signup' + fullPath: '/signup' + preLoaderRoute: typeof SignupRouteImport parentRoute: typeof rootRouteImport } '/_authed/posts': { diff --git a/e2e/vue-start/basic-auth/src/routes/__root.tsx b/e2e/vue-start/basic-auth/src/routes/__root.tsx index 89802cfd2f..e5b6f6778f 100644 --- a/e2e/vue-start/basic-auth/src/routes/__root.tsx +++ b/e2e/vue-start/basic-auth/src/routes/__root.tsx @@ -1,4 +1,5 @@ /// +import { defineComponent } from 'vue' import { Body, HeadContent, @@ -15,21 +16,69 @@ import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' import { NotFound } from '~/components/NotFound.js' import appCss from '~/styles/app.css?url' import { seo } from '~/utils/seo.js' -import { useAppSession } from '~/utils/session.js' +import { getAppSession } from '~/utils/session.js' const fetchUser = createServerFn({ method: 'GET' }).handler(async () => { // We need to auth on the server so we have access to secure cookies - const session = await useAppSession() + const session = await getAppSession() - if (!session.data.userEmail) { + if (!session.userEmail) { return null } return { - email: session.data.userEmail, + email: session.userEmail, } }) +const RootShell = defineComponent({ + setup(_, { slots }) { + const routeContext = Route.useRouteContext() + return () => ( + + + + + +
+ + Home + {' '} + + Posts + +
+ {routeContext.value.user ? ( + <> + {routeContext.value.user.email} + Logout + + ) : ( + Login + )} +
+
+
+ {slots.default?.()} + + + + + ) + }, +}) + export const Route = createRootRoute({ beforeLoad: async () => { const user = await fetchUser() @@ -81,50 +130,3 @@ export const Route = createRootRoute({ notFoundComponent: () => , component: () => , }) - -function RootShell(_: unknown, { slots }: { slots: any }) { - const routeContext = Route.useRouteContext() - - return ( - - - - - -
- - Home - {' '} - - Posts - -
- {routeContext.value.user ? ( - <> - {routeContext.value.user.email} - Logout - - ) : ( - Login - )} -
-
-
- {slots.default?.()} - - - - - ) -} diff --git a/e2e/vue-start/basic-auth/src/routes/_authed.tsx b/e2e/vue-start/basic-auth/src/routes/_authed.tsx index 153efc39eb..606de3e487 100644 --- a/e2e/vue-start/basic-auth/src/routes/_authed.tsx +++ b/e2e/vue-start/basic-auth/src/routes/_authed.tsx @@ -3,7 +3,7 @@ import { createServerFn } from '@tanstack/vue-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { Login } from '~/components/Login' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST', @@ -37,12 +37,11 @@ export const loginFn = createServerFn({ } // Create a session - const session = await useAppSession() + const session = await getAppSession() // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + session.userEmail = user.email + await session.save() }) export const Route = createFileRoute('/_authed')({ @@ -52,7 +51,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error.message === 'Not authenticated') { + if (error instanceof Error && error.message === 'Not authenticated') { return } diff --git a/e2e/vue-start/basic-auth/src/routes/_authed/posts.$postId.tsx b/e2e/vue-start/basic-auth/src/routes/_authed/posts.$postId.tsx index da0c26f27f..45d6bbab0d 100644 --- a/e2e/vue-start/basic-auth/src/routes/_authed/posts.$postId.tsx +++ b/e2e/vue-start/basic-auth/src/routes/_authed/posts.$postId.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -8,6 +9,18 @@ export function PostErrorComponent({ error }: ErrorComponentProps) { return } +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + return () => ( +
+

{post.value.title}

+
{post.value.body}
+
+ ) + }, +}) + export const Route = createFileRoute('/_authed/posts/$postId')({ loader: ({ params: { postId } }) => fetchPost({ data: postId }), errorComponent: PostErrorComponent, @@ -16,14 +29,3 @@ export const Route = createFileRoute('/_authed/posts/$postId')({ return Post not found }, }) - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

{post.value.title}

-
{post.value.body}
-
- ) -} diff --git a/e2e/vue-start/basic-auth/src/routes/_authed/posts.tsx b/e2e/vue-start/basic-auth/src/routes/_authed/posts.tsx index cfac133b51..6b8b54c666 100644 --- a/e2e/vue-start/basic-auth/src/routes/_authed/posts.tsx +++ b/e2e/vue-start/basic-auth/src/routes/_authed/posts.tsx @@ -1,36 +1,38 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '~/utils/posts.js' -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ))} -
-
- -
- ) -} +const PostsComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + return () => ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ))} +
+
+ +
+ ) + }, +}) export const Route = createFileRoute('/_authed/posts')({ loader: () => fetchPosts(), diff --git a/e2e/vue-start/basic-auth/src/routes/logout.tsx b/e2e/vue-start/basic-auth/src/routes/logout.tsx index f1d7b58e29..8372b33608 100644 --- a/e2e/vue-start/basic-auth/src/routes/logout.tsx +++ b/e2e/vue-start/basic-auth/src/routes/logout.tsx @@ -1,12 +1,12 @@ import { redirect, createFileRoute } from '@tanstack/vue-router' import { createServerFn } from '@tanstack/vue-start' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await useAppSession() + const session = await getAppSession() - session.clear() + session.destroy() throw redirect({ href: '/', diff --git a/e2e/vue-start/basic-auth/src/routes/signup.tsx b/e2e/vue-start/basic-auth/src/routes/signup.tsx index eade8363e6..5f37f109c7 100644 --- a/e2e/vue-start/basic-auth/src/routes/signup.tsx +++ b/e2e/vue-start/basic-auth/src/routes/signup.tsx @@ -5,7 +5,7 @@ import { defineComponent } from 'vue' import { hashPassword, prismaClient } from '~/utils/prisma' import { useMutation } from '~/hooks/useMutation' import { Auth } from '~/components/Auth' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' export const signupFn = createServerFn({ method: 'POST', @@ -25,7 +25,7 @@ export const signupFn = createServerFn({ const password = await hashPassword(payload.password) // Create a session - const session = await useAppSession() + const session = await getAppSession() if (found) { if (found.password !== password) { @@ -37,9 +37,8 @@ export const signupFn = createServerFn({ } // Store the user's email in the session - await session.update({ - userEmail: found.email, - }) + session.userEmail = found.email + await session.save() // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -56,9 +55,8 @@ export const signupFn = createServerFn({ }) // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + session.userEmail = user.email + await session.save() // Redirect to the prev page stored in the "redirect" search param throw redirect({ diff --git a/e2e/vue-start/basic-auth/src/utils/session.ts b/e2e/vue-start/basic-auth/src/utils/session.ts index 7cf2a41792..7d078225a0 100644 --- a/e2e/vue-start/basic-auth/src/utils/session.ts +++ b/e2e/vue-start/basic-auth/src/utils/session.ts @@ -1,13 +1,25 @@ -// src/services/session.server.ts -import { useSession } from '@tanstack/vue-start/server' +import { getIronSession } from 'iron-session' +import { getCookie, setCookie } from '@tanstack/vue-start/server' import type { User } from '~/prisma-generated/client' type SessionUser = { userEmail: User['email'] } -export function useAppSession() { - return useSession({ - password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', - }) +export function getAppSession() { + return getIronSession( + { read: getCookie, write: setCookie }, + { + cookieName: 'test-auth-session', + // This fixture only runs locally with test credentials. + password: 'local-e2e-only-session-password-at-least-32-characters', + ttl: 60 * 60, + cookieOptions: { + httpOnly: true, + secure: false, + sameSite: 'lax', + path: '/', + }, + }, + ) } diff --git a/e2e/vue-start/basic-cloudflare/package.json b/e2e/vue-start/basic-cloudflare/package.json index 05b2158c0e..5ab77db8fc 100644 --- a/e2e/vue-start/basic-cloudflare/package.json +++ b/e2e/vue-start/basic-cloudflare/package.json @@ -10,7 +10,7 @@ "preview": "vite preview", "cf-typegen": "wrangler types", "postinstall": "WRANGLER_LOG=warn npm run --silent cf-typegen", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -25,10 +25,21 @@ "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "wrangler": "^4.74.0" + }, + "nx": { + "targets": { + "test:e2e": { + "outputs": [ + "...", + "{projectRoot}/.wrangler/deploy" + ] + } + } } } diff --git a/e2e/vue-start/basic-cloudflare/playwright.config.ts b/e2e/vue-start/basic-cloudflare/playwright.config.ts index a545dff891..0925936d55 100644 --- a/e2e/vue-start/basic-cloudflare/playwright.config.ts +++ b/e2e/vue-start/basic-cloudflare/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -14,9 +13,6 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, @@ -24,8 +20,8 @@ export default defineConfig({ webServer: { command: `pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx index 02caf56456..0687372ae0 100644 --- a/e2e/vue-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/basic-cloudflare/src/components/DefaultCatchBoundary.tsx @@ -1,3 +1,5 @@ +import { defineComponent } from 'vue' +import type { PropType } from 'vue' import { ErrorComponent, Link, @@ -6,46 +8,54 @@ import { } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - - console.error(error) - - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} +export const DefaultCatchBoundary = defineComponent({ + props: { + error: { + type: Object as PropType, + required: true, + }, + }, + setup(props) { + const router = useRouter() + const isRoot = useLocation({ + select: (location) => location.pathname === '/', + }) + return () => { + console.error(props.error) + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) + } + }, +}) diff --git a/e2e/vue-start/basic-cloudflare/src/routeTree.gen.ts b/e2e/vue-start/basic-cloudflare/src/routeTree.gen.ts index 30451e7ab7..c52a88360b 100644 --- a/e2e/vue-start/basic-cloudflare/src/routeTree.gen.ts +++ b/e2e/vue-start/basic-cloudflare/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 StaticRouteImport } from './routes/static' import { Route as IndexRouteImport } from './routes/index' +import { Route as StaticRouteImport } from './routes/static' -const StaticRoute = StaticRouteImport.update({ - id: '/static', - path: '/static', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const StaticRoute = StaticRouteImport.update({ + id: '/static', + path: '/static', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/static': { - id: '/static' - path: '/static' - fullPath: '/static' - preLoaderRoute: typeof StaticRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/static': { + id: '/static' + path: '/static' + fullPath: '/static' + preLoaderRoute: typeof StaticRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/e2e/vue-start/basic-cloudflare/src/routes/index.tsx b/e2e/vue-start/basic-cloudflare/src/routes/index.tsx index 1c708a7ec6..d3a020c7ad 100644 --- a/e2e/vue-start/basic-cloudflare/src/routes/index.tsx +++ b/e2e/vue-start/basic-cloudflare/src/routes/index.tsx @@ -1,7 +1,21 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { createServerFn } from '@tanstack/vue-start' import { env } from 'cloudflare:workers' +const Home = defineComponent({ + setup() { + const data = Route.useLoaderData() + return () => ( +
+

Welcome Home!!!

+

{data.value.message}

+

{data.value.myVar}

+
+ ) + }, +}) + export const Route = createFileRoute('/')({ loader: () => getData(), component: Home, @@ -13,15 +27,3 @@ const getData = createServerFn().handler(() => { myVar: env.MY_VAR, } }) - -function Home() { - const data = Route.useLoaderData() - - return ( -
-

Welcome Home!!!

-

{data.value.message}

-

{data.value.myVar}

-
- ) -} diff --git a/e2e/vue-start/basic-cloudflare/src/routes/static.tsx b/e2e/vue-start/basic-cloudflare/src/routes/static.tsx index 7b0f9fd232..14d0c06294 100644 --- a/e2e/vue-start/basic-cloudflare/src/routes/static.tsx +++ b/e2e/vue-start/basic-cloudflare/src/routes/static.tsx @@ -1,7 +1,20 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { createServerFn } from '@tanstack/vue-start' import { env } from 'cloudflare:workers' +const StaticPage = defineComponent({ + setup() { + const data = Route.useLoaderData() + return () => ( +
+

Static Page

+

The value is {data.value.myVar}

+
+ ) + }, +}) + export const Route = createFileRoute('/static')({ loader: () => getData(), component: StaticPage, @@ -12,14 +25,3 @@ const getData = createServerFn().handler(() => { myVar: env.MY_VAR, } }) - -function StaticPage() { - const data = Route.useLoaderData() - - return ( -
-

Static Page

-

The value is {data.value.myVar}

-
- ) -} diff --git a/e2e/vue-start/basic-cloudflare/tests/setup/global.setup.ts b/e2e/vue-start/basic-cloudflare/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-start/basic-cloudflare/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/basic-cloudflare/tests/setup/global.teardown.ts b/e2e/vue-start/basic-cloudflare/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-start/basic-cloudflare/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/basic-tsr-config/package.json b/e2e/vue-start/basic-tsr-config/package.json index 93c3b272fa..828dce5b2a 100644 --- a/e2e/vue-start/basic-tsr-config/package.json +++ b/e2e/vue-start/basic-tsr-config/package.json @@ -8,7 +8,7 @@ "dev:e2e": "vite dev", "build": "rimraf ./count.txt && vite build && tsc --noEmit", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -19,10 +19,12 @@ "devDependencies": { "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "srvx": "^0.11.9", - "typescript": "^6.0.2", + "srvx": "^1.0.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", - "vite": "^8.0.14" + "vite": "^8.0.14", + "rimraf": "catalog:" } } diff --git a/e2e/vue-start/basic-tsr-config/playwright.config.ts b/e2e/vue-start/basic-tsr-config/playwright.config.ts index f6dd61ba6c..e6b92ce385 100644 --- a/e2e/vue-start/basic-tsr-config/playwright.config.ts +++ b/e2e/vue-start/basic-tsr-config/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,8 +20,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-start/basic-tsr-config/src/app/routes/index.tsx b/e2e/vue-start/basic-tsr-config/src/app/routes/index.tsx index 3f4de50817..b4b520e8af 100644 --- a/e2e/vue-start/basic-tsr-config/src/app/routes/index.tsx +++ b/e2e/vue-start/basic-tsr-config/src/app/routes/index.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import * as fs from 'node:fs' import { createFileRoute, useRouter } from '@tanstack/vue-router' import { createServerFn } from '@tanstack/vue-start' @@ -17,25 +18,26 @@ const updateCount = createServerFn({ method: 'POST' }) const count = await getCount() await fs.promises.writeFile(filePath, `${count + data}`) }) +const Home = defineComponent({ + setup() { + const router = useRouter() + const state = Route.useLoaderData() + return () => ( + + ) + }, +}) + export const Route = createFileRoute('/')({ component: Home, loader: async () => await getCount(), }) - -function Home() { - const router = useRouter() - const state = Route.useLoaderData() - - return ( - - ) -} diff --git a/e2e/vue-start/basic-vue-query/package.json b/e2e/vue-start/basic-vue-query/package.json index 6b1335d8bd..ab9589376d 100644 --- a/e2e/vue-start/basic-vue-query/package.json +++ b/e2e/vue-start/basic-vue-query/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-query": "^5.92.1", @@ -18,7 +18,7 @@ "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-router-ssr-query": "workspace:^", "@tanstack/vue-start": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "vue": "^3.5.25", "zod": "^4.4.3" @@ -30,9 +30,10 @@ "@types/node": "^22.10.2", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/e2e/vue-start/basic-vue-query/playwright.config.ts b/e2e/vue-start/basic-vue-query/playwright.config.ts index 84636ab0f9..0618b7272a 100644 --- a/e2e/vue-start/basic-vue-query/playwright.config.ts +++ b/e2e/vue-start/basic-vue-query/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` @@ -16,18 +11,18 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', + env: { + NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, + }, }, projects: [ diff --git a/e2e/vue-start/basic-vue-query/src/routeTree.gen.ts b/e2e/vue-start/basic-vue-query/src/routeTree.gen.ts index 2c514d54ea..10e8a56450 100644 --- a/e2e/vue-start/basic-vue-query/src/routeTree.gen.ts +++ b/e2e/vue-start/basic-vue-query/src/routeTree.gen.ts @@ -9,37 +9,31 @@ // 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 UsersRouteImport } from './routes/users' -import { Route as SuspenseTransitionRouteImport } from './routes/suspense-transition' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as ApiUsersRouteImport } from './routes/api.users' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as SuspenseTransitionRouteImport } from './routes/suspense-transition' +import { Route as UsersRouteImport } from './routes/users' import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as TransitionCountQueryRouteImport } from './routes/transition/count/query' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as ApiUsersRouteImport } from './routes/api.users' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as TransitionCountQueryRouteImport } from './routes/transition/count/query' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const SuspenseTransitionRoute = SuspenseTransitionRouteImport.update({ - id: '/suspense-transition', - path: '/suspense-transition', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', getParentRoute: () => rootRouteImport, } as any) const DeferredRoute = DeferredRouteImport.update({ @@ -47,68 +41,74 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SuspenseTransitionRoute = SuspenseTransitionRouteImport.update({ + id: '/suspense-transition', + path: '/suspense-transition', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, -} as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const LayoutLayout2Route = LayoutLayout2RouteImport.update({ id: '/_layout-2', getParentRoute: () => LayoutRoute, } as any) -const TransitionCountQueryRoute = TransitionCountQueryRouteImport.update({ - id: '/transition/count/query', - path: '/transition/count/query', +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, } as any) -const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => ApiUsersRoute, +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRoute, +} as any) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any) const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ id: '/layout-b', path: '/layout-b', getParentRoute: () => LayoutLayout2Route, } as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => ApiUsersRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) +const TransitionCountQueryRoute = TransitionCountQueryRouteImport.update({ + id: '/transition/count/query', + path: '/transition/count/query', + getParentRoute: () => rootRouteImport, } as any) export interface FileRoutesByFullPath { @@ -231,32 +231,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport - parentRoute: typeof rootRouteImport - } - '/suspense-transition': { - id: '/suspense-transition' - path: '/suspense-transition' - fullPath: '/suspense-transition' - preLoaderRoute: typeof SuspenseTransitionRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -266,46 +245,32 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute + '/suspense-transition': { + id: '/suspense-transition' + path: '/suspense-transition' + fullPath: '/suspense-transition' + preLoaderRoute: typeof SuspenseTransitionRouteImport + parentRoute: typeof rootRouteImport } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/_layout/_layout-2': { @@ -315,26 +280,47 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LayoutLayout2RouteImport parentRoute: typeof LayoutRoute } - '/transition/count/query': { - id: '/transition/count/query' - path: '/transition/count/query' - fullPath: '/transition/count/query' - preLoaderRoute: typeof TransitionCountQueryRouteImport + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute } - '/api/users/$id': { - id: '/api/users/$id' - path: '/$id' - fullPath: '/api/users/$id' - preLoaderRoute: typeof ApiUsersIdRouteImport - parentRoute: typeof ApiUsersRoute + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute + } + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route } '/_layout/_layout-2/layout-b': { id: '/_layout/_layout-2/layout-b' @@ -343,12 +329,26 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport parentRoute: typeof LayoutLayout2Route } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/api/users/$id': { + id: '/api/users/$id' + path: '/$id' + fullPath: '/api/users/$id' + preLoaderRoute: typeof ApiUsersIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport + } + '/transition/count/query': { + id: '/transition/count/query' + path: '/transition/count/query' + fullPath: '/transition/count/query' + preLoaderRoute: typeof TransitionCountQueryRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/e2e/vue-start/basic-vue-query/src/routes/api.users.ts b/e2e/vue-start/basic-vue-query/src/routes/api.users.ts index cab4cafc3f..f9330a87db 100644 --- a/e2e/vue-start/basic-vue-query/src/routes/api.users.ts +++ b/e2e/vue-start/basic-vue-query/src/routes/api.users.ts @@ -2,11 +2,7 @@ import { createFileRoute } from '@tanstack/vue-router' import axios from 'redaxios' import type { User } from '../utils/users' -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const Route = createFileRoute('/api/users')({ server: { diff --git a/e2e/vue-start/basic-vue-query/src/routes/api/users.$id.ts b/e2e/vue-start/basic-vue-query/src/routes/api/users.$id.ts index 4cc4b33a0b..d138746730 100644 --- a/e2e/vue-start/basic-vue-query/src/routes/api/users.$id.ts +++ b/e2e/vue-start/basic-vue-query/src/routes/api/users.$id.ts @@ -2,11 +2,7 @@ import { createFileRoute } from '@tanstack/vue-router' import axios from 'redaxios' import type { User } from '../../utils/users' -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const Route = createFileRoute('/api/users/$id')({ server: { diff --git a/e2e/vue-start/basic-vue-query/src/routes/posts.$postId.tsx b/e2e/vue-start/basic-vue-query/src/routes/posts.$postId.tsx index 27baf4bd5f..fd8deaf291 100644 --- a/e2e/vue-start/basic-vue-query/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/basic-vue-query/src/routes/posts.$postId.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { useQuery } from '@tanstack/vue-query' import { ErrorComponent, @@ -11,27 +12,30 @@ export function PostErrorComponent(props: ErrorComponentProps) { return } -function PostComponent() { - const params = Route.useParams() - const postQuery = useQuery(() => postQueryOptions(params.value.postId)) - - return ( -
-

{postQuery.data.value?.title}

-
{postQuery.data.value?.body}
- - Deep View - -
- ) -} +const PostComponent = defineComponent({ + setup() { + const params = Route.useParams() + const postQuery = useQuery(() => postQueryOptions(params.value.postId)) + return () => ( +
+

+ {postQuery.data.value?.title} +

+
{postQuery.data.value?.body}
+ + Deep View + +
+ ) + }, +}) export const Route = createFileRoute('/posts/$postId')({ loader: async ({ context, params }) => { diff --git a/e2e/vue-start/basic-vue-query/src/routes/posts_.$postId.deep.tsx b/e2e/vue-start/basic-vue-query/src/routes/posts_.$postId.deep.tsx index 38e7429f6e..211b3ca4b1 100644 --- a/e2e/vue-start/basic-vue-query/src/routes/posts_.$postId.deep.tsx +++ b/e2e/vue-start/basic-vue-query/src/routes/posts_.$postId.deep.tsx @@ -1,22 +1,26 @@ +import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { useQuery } from '@tanstack/vue-query' import { postQueryOptions } from '../utils/posts' import { PostErrorComponent } from './posts.$postId' -function PostDeepComponent() { - const params = Route.useParams() - const postQuery = useQuery(() => postQueryOptions(params.value.postId)) - - return ( -
- - ← All Posts - -

{postQuery.data.value?.title}

-
{postQuery.data.value?.body}
-
- ) -} +const PostDeepComponent = defineComponent({ + setup() { + const params = Route.useParams() + const postQuery = useQuery(() => postQueryOptions(params.value.postId)) + return () => ( +
+ + ← All Posts + +

+ {postQuery.data.value?.title} +

+
{postQuery.data.value?.body}
+
+ ) + }, +}) export const Route = createFileRoute('/posts_/$postId/deep')({ loader: async ({ params: { postId }, context }) => { diff --git a/e2e/vue-start/basic-vue-query/src/routes/suspense-transition.tsx b/e2e/vue-start/basic-vue-query/src/routes/suspense-transition.tsx index 6d12790dc9..f5004aa21d 100644 --- a/e2e/vue-start/basic-vue-query/src/routes/suspense-transition.tsx +++ b/e2e/vue-start/basic-vue-query/src/routes/suspense-transition.tsx @@ -1,6 +1,6 @@ import { queryOptions, useQuery } from '@tanstack/vue-query' import { Link, createFileRoute } from '@tanstack/vue-router' -import { ref, watchEffect } from 'vue' +import { defineComponent, ref, watchEffect } from 'vue' const doubleQueryOptions = (n: number) => queryOptions({ @@ -19,6 +19,37 @@ export const Route = createFileRoute('/suspense-transition')({ ssr: false, // Disable SSR to avoid suspense issues during initial load }) +const Result = defineComponent({ + setup() { + const search = Route.useSearch() + const doubleQuery = useQuery(() => doubleQueryOptions(search.value.n)) + const displayedN = ref(search.value.n) + const displayedDouble = ref(undefined) + watchEffect(() => { + if (doubleQuery.data.value !== undefined) { + displayedN.value = search.value.n + displayedDouble.value = doubleQuery.data.value + } + }) + return () => ( +
+
+ Loading... +
+
+
+ n: {displayedN.value} +
+
+ double:{' '} + {displayedDouble.value} +
+
+
+ ) + }, +}) + function SuspenseTransitionComponent() { return (
@@ -39,34 +70,3 @@ function SuspenseTransitionComponent() {
) } - -function Result() { - const search = Route.useSearch() - const doubleQuery = useQuery(() => doubleQueryOptions(search.value.n)) - const displayedN = ref(search.value.n) - const displayedDouble = ref(undefined) - - watchEffect(() => { - if (doubleQuery.data.value !== undefined) { - displayedN.value = search.value.n - displayedDouble.value = doubleQuery.data.value - } - }) - - return ( -
-
- Loading... -
-
-
- n: {displayedN.value} -
-
- double:{' '} - {displayedDouble.value} -
-
-
- ) -} diff --git a/e2e/vue-start/basic-vue-query/src/routes/transition/count/query.tsx b/e2e/vue-start/basic-vue-query/src/routes/transition/count/query.tsx index 2ab0562203..32b1943c71 100644 --- a/e2e/vue-start/basic-vue-query/src/routes/transition/count/query.tsx +++ b/e2e/vue-start/basic-vue-query/src/routes/transition/count/query.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { queryOptions, useQuery } from '@tanstack/vue-query' import { z } from 'zod' @@ -16,6 +17,32 @@ const doubleQueryOptions = (n: number) => placeholderData: (oldData) => oldData, }) +const TransitionPage = defineComponent({ + setup() { + const search = Route.useSearch() + const doubleQuery = useQuery(() => doubleQueryOptions(search.value.n)) + return () => ( +
+ ({ n: s.n + 1 })} + > + Increase + + +
+
n: {doubleQuery.data.value?.n}
+
+ double: {doubleQuery.data.value?.double} +
+
+
+ ) + }, +}) + export const Route = createFileRoute('/transition/count/query')({ validateSearch: searchSchema, loader: ({ context: { queryClient }, location }) => { @@ -24,28 +51,3 @@ export const Route = createFileRoute('/transition/count/query')({ }, component: TransitionPage, }) - -function TransitionPage() { - const search = Route.useSearch() - const doubleQuery = useQuery(() => doubleQueryOptions(search.value.n)) - - return ( -
- ({ n: s.n + 1 })} - > - Increase - - -
-
n: {doubleQuery.data.value?.n}
-
- double: {doubleQuery.data.value?.double} -
-
-
- ) -} diff --git a/e2e/vue-start/basic-vue-query/src/routes/users.$userId.tsx b/e2e/vue-start/basic-vue-query/src/routes/users.$userId.tsx index 91376b9498..bf1b75861e 100644 --- a/e2e/vue-start/basic-vue-query/src/routes/users.$userId.tsx +++ b/e2e/vue-start/basic-vue-query/src/routes/users.$userId.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { useQuery } from '@tanstack/vue-query' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' @@ -5,19 +6,20 @@ import type { ErrorComponentProps } from '@tanstack/vue-router' import { NotFound } from '~/components/NotFound' import { userQueryOptions } from '~/utils/users' -function UserComponent() { - const params = Route.useParams() - const userQuery = useQuery(() => userQueryOptions(params.value.userId)) - - return ( -
-

- {userQuery.data.value?.name ?? 'loading...'} -

-
{userQuery.data.value?.email ?? ''}
-
- ) -} +const UserComponent = defineComponent({ + setup() { + const params = Route.useParams() + const userQuery = useQuery(() => userQueryOptions(params.value.userId)) + return () => ( +
+

+ {userQuery.data.value?.name ?? 'loading...'} +

+
{userQuery.data.value?.email ?? ''}
+
+ ) + }, +}) export const Route = createFileRoute('/users/$userId')({ loader: async ({ context, params: { userId } }) => { diff --git a/e2e/vue-start/basic-vue-query/src/utils/posts.tsx b/e2e/vue-start/basic-vue-query/src/utils/posts.tsx index b0a0b8f60d..c6b5e70a0b 100644 --- a/e2e/vue-start/basic-vue-query/src/utils/posts.tsx +++ b/e2e/vue-start/basic-vue-query/src/utils/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const postsQueryOptions = () => queryOptions({ diff --git a/e2e/vue-start/basic-vue-query/src/utils/users.tsx b/e2e/vue-start/basic-vue-query/src/utils/users.tsx index 29bf08c315..fe7a902fa2 100644 --- a/e2e/vue-start/basic-vue-query/src/utils/users.tsx +++ b/e2e/vue-start/basic-vue-query/src/utils/users.tsx @@ -1,4 +1,6 @@ import { queryOptions } from '@tanstack/vue-query' +import { createIsomorphicFn } from '@tanstack/vue-start' +import { getRequestUrl } from '@tanstack/vue-start/server' import axios from 'redaxios' export type User = { @@ -7,17 +9,16 @@ export type User = { email: string } -const PORT = - import.meta.env.VITE_SERVER_PORT || process.env.VITE_SERVER_PORT || 3000 - -export const DEPLOY_URL = `http://localhost:${PORT}` +const getOrigin = createIsomorphicFn() + .server(() => getRequestUrl().origin) + .client(() => window.location.origin) export const usersQueryOptions = () => queryOptions({ queryKey: ['users'], queryFn: () => axios - .get>(DEPLOY_URL + '/api/users') + .get>(getOrigin() + '/api/users') .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch users') @@ -29,7 +30,7 @@ export const userQueryOptions = (id: string) => queryKey: ['users', id], queryFn: () => axios - .get(DEPLOY_URL + '/api/users/' + id) + .get(getOrigin() + '/api/users/' + id) .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch user') diff --git a/e2e/vue-start/basic-vue-query/tests/app.spec.ts b/e2e/vue-start/basic-vue-query/tests/app.spec.ts index ab2469f68d..4ce5c20ef7 100644 --- a/e2e/vue-start/basic-vue-query/tests/app.spec.ts +++ b/e2e/vue-start/basic-vue-query/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test('Navigating to post', async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-start/basic-vue-query/tests/setup/global.setup.ts b/e2e/vue-start/basic-vue-query/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-start/basic-vue-query/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/basic-vue-query/tests/setup/global.teardown.ts b/e2e/vue-start/basic-vue-query/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-start/basic-vue-query/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/basic-vue-query/tests/transition.spec.ts b/e2e/vue-start/basic-vue-query/tests/transition.spec.ts index 2c28fc72a2..a0f3bf0964 100644 --- a/e2e/vue-start/basic-vue-query/tests/transition.spec.ts +++ b/e2e/vue-start/basic-vue-query/tests/transition.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test('transitions/count/query should keep old values visible during navigation', async ({ page, diff --git a/e2e/vue-start/basic/package.json b/e2e/vue-start/basic/package.json index dacbcc2154..2ff8329543 100644 --- a/e2e/vue-start/basic/package.json +++ b/e2e/vue-start/basic/package.json @@ -6,12 +6,12 @@ "scripts": { "dev": "vite dev --port 3000", "dev:e2e": "vite dev", - "build": "vite build && tsc --noEmit", + "build": "pnpm build:vite", "preview": "vite preview", "start": "node server.js", - "test:e2e:startDummyServer": "node -e 'import(\"./tests/setup/global.setup.ts\").then(m => m.default())' & node -e 'import(\"./tests/setup/waitForDummyServer.ts\").then(m => m.default())'", - "test:e2e:stopDummyServer": "node -e 'import(\"./tests/setup/global.teardown.ts\").then(m => m.default())'", - "test:e2e:local": "playwright test --project=chromium" + "test:e2e:local": "playwright test --project=chromium", + "build:vite": "vite build && tsc --noEmit", + "build:rsbuild": "rsbuild build && tsc --noEmit" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -20,17 +20,17 @@ "express": "^5.2.1", "http-proxy-middleware": "^3.0.5", "js-cookie": "^3.0.5", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "vue": "^3.5.16", "zod": "^4.4.3" }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.0.11", - "@rsbuild/plugin-babel": "^1.0.5", - "@rsbuild/plugin-vue": "^1.2.2", - "@rsbuild/plugin-vue-jsx": "^1.1.1", + "@rsbuild/core": "^2.3.1", + "@rsbuild/plugin-babel": "^1.1.2", + "@rsbuild/plugin-vue": "^1.2.7", + "@rsbuild/plugin-vue-jsx": "^2.0.0", "@tailwindcss/postcss": "^4.2.2", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", @@ -39,9 +39,10 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" }, "nx": { @@ -58,7 +59,10 @@ }, { "toolchain": "vite", - "mode": "prerender" + "mode": "prerender", + "env": { + "NODE_OPTIONS": "--import=@tanstack/router-e2e-utils/mock-api" + } }, { "toolchain": "vite", diff --git a/e2e/vue-start/basic/playwright.config.ts b/e2e/vue-start/basic/playwright.config.ts index 6924134cd1..9322874f3a 100644 --- a/e2e/vue-start/basic/playwright.config.ts +++ b/e2e/vue-start/basic/playwright.config.ts @@ -1,59 +1,37 @@ -import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' const mode = process.env.MODE ?? 'ssr' -const e2ePortKey = process.env.E2E_PORT_KEY ?? packageJson.name + const distDir = process.env.E2E_DIST_DIR ?? 'dist' -if (process.env.TEST_WORKER_INDEX === undefined) { - for (const portFile of [ - `port-${e2ePortKey}.txt`, - `port-${e2ePortKey}_start.txt`, - `port-${e2ePortKey}-external.txt`, - ]) { - fs.rmSync(portFile, { force: true }) - } -} - -const PORT = await getTestServerPort(e2ePortKey) -const START_PORT = await getTestServerPort(`${e2ePortKey}_start`) -const EXTERNAL_PORT = await getDummyServerPort(e2ePortKey) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` const commandByMode = mode === 'preview' - ? `pnpm run test:e2e:startDummyServer && pnpm preview --outDir ${distDir} --port ${PORT}` - : `pnpm run test:e2e:startDummyServer && pnpm start` + ? `pnpm preview --host 0.0.0.0 --outDir ${distDir} --port ${PORT}` + : `pnpm start` export default defineConfig({ testDir: './tests', workers: 1, reporter: [['line']], - globalTeardown: './tests/setup/global.teardown.ts', - use: { baseURL, }, webServer: { command: commandByMode, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', env: { + NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, MODE: mode, - VITE_NODE_ENV: 'test', - VITE_EXTERNAL_PORT: String(EXTERNAL_PORT), - VITE_SERVER_PORT: String(PORT), - START_PORT: String(START_PORT), + START_PORT: '0', PORT: String(PORT), E2E_DIST_DIR: distDir, - E2E_PORT_KEY: e2ePortKey, }, }, diff --git a/e2e/vue-start/basic/rsbuild.config.ts b/e2e/vue-start/basic/rsbuild.config.ts index 93af798c3c..aad3a76e73 100644 --- a/e2e/vue-start/basic/rsbuild.config.ts +++ b/e2e/vue-start/basic/rsbuild.config.ts @@ -16,11 +16,6 @@ export default defineConfig({ pluginVueJsx(), tanstackStart(), ], - performance: { - chunkSplit: { - strategy: 'split-by-experience', - }, - }, source: { define: { __TSR_PRERENDER__: JSON.stringify(isPrerender), diff --git a/e2e/vue-start/basic/server.js b/e2e/vue-start/basic/server.js index 69c1e4ca91..3e1ddab400 100644 --- a/e2e/vue-start/basic/server.js +++ b/e2e/vue-start/basic/server.js @@ -1,12 +1,12 @@ -import { toNodeHandler } from 'srvx/node' import fs from 'node:fs' import path from 'node:path' +import { toNodeHandler } from 'srvx/node' import express from 'express' import { createProxyMiddleware } from 'http-proxy-middleware' -const port = process.env.PORT || 3000 +const port = Number(process.env.PORT ?? 3000) -const startPort = process.env.START_PORT || 3001 +const startPort = Number(process.env.START_PORT ?? 0) const isSpaMode = process.env.MODE === 'spa' const isPrerender = process.env.MODE === 'prerender' @@ -49,13 +49,13 @@ export async function createStartServer() { return { app } } -export async function createSpaServer() { +export async function createSpaServer(backendPort) { const app = express() app.use( '/api', createProxyMiddleware({ - target: `http://localhost:${startPort}/api`, // Replace with your target server's URL + target: `http://localhost:${backendPort}/api`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -63,7 +63,7 @@ export async function createSpaServer() { app.use( '/_serverFn', createProxyMiddleware({ - target: `http://localhost:${startPort}/_serverFn`, // Replace with your target server's URL + target: `http://localhost:${backendPort}/_serverFn`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -71,31 +71,28 @@ export async function createSpaServer() { app.use(express.static(distClientDir)) app.get('/{*splat}', (req, res) => { - res.sendFile(path.resolve(distClientDir, 'index.html')) + res.sendFile('index.html', { root: distClientDir }) }) return { app } } -if (isSpaMode) { - createSpaServer().then(async ({ app }) => - app.listen(port, (error) => { - if (error) throw error - console.info(`Client Server: http://localhost:${port}`) - }), - ) - - createStartServer().then(async ({ app }) => - app.listen(startPort, (error) => { - if (error) throw error - console.info(`Start Server: http://localhost:${startPort}`) - }), - ) -} else { - createStartServer().then(async ({ app }) => - app.listen(port, (error) => { - if (error) throw error - console.info(`Start Server: http://localhost:${port}`) - }), - ) -} +// Bind the backend first so the SPA proxy receives the port actually held by it. +const { app: startApp } = await createStartServer() +const backend = startApp.listen(isSpaMode ? startPort : port, async (error) => { + if (error) { + throw error + } + const backendPort = backend.address().port + if (isSpaMode) { + const { app } = await createSpaServer(backendPort) + const frontend = app.listen(port, (frontendError) => { + if (frontendError) { + throw frontendError + } + console.info(`E2E app: http://localhost:${frontend.address().port}`) + }) + } else { + console.info(`E2E app: http://localhost:${backendPort}`) + } +}) diff --git a/e2e/vue-start/basic/src/routeTree.gen.ts b/e2e/vue-start/basic/src/routeTree.gen.ts index 016a292835..7fbcd192b6 100644 --- a/e2e/vue-start/basic/src/routeTree.gen.ts +++ b/e2e/vue-start/basic/src/routeTree.gen.ts @@ -9,97 +9,71 @@ // 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 UsersRouteImport } from './routes/users' -import { Route as StreamRouteImport } from './routes/stream' -import { Route as ScriptsRouteImport } from './routes/scripts' -import { Route as RawStreamRouteImport } from './routes/raw-stream' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as LinksRouteImport } from './routes/links' -import { Route as InlineScriptsRouteImport } from './routes/inline-scripts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as LayoutRouteImport } from './routes/_layout' -import { Route as SpecialCharsRouteRouteImport } from './routes/specialChars/route' -import { Route as SearchParamsRouteRouteImport } from './routes/search-params/route' -import { Route as NotFoundRouteRouteImport } from './routes/not-found/route' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as SearchParamsIndexRouteImport } from './routes/search-params/index' -import { Route as RedirectIndexRouteImport } from './routes/redirect/index' -import { Route as RawStreamIndexRouteImport } from './routes/raw-stream/index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as NotFoundIndexRouteImport } from './routes/not-found/index' -import { Route as MultiCookieRedirectIndexRouteImport } from './routes/multi-cookie-redirect/index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as SpecialCharsChar45824Char54620Char48124Char44397RouteImport } from './routes/specialChars/대한민국' -import { Route as SpecialCharsSearchRouteImport } from './routes/specialChars/search' -import { Route as SpecialCharsHashRouteImport } from './routes/specialChars/hash' -import { Route as SpecialCharsParamRouteImport } from './routes/specialChars/$param' -import { Route as SearchParamsLoaderThrowsRedirectRouteImport } from './routes/search-params/loader-throws-redirect' -import { Route as SearchParamsDefaultRouteImport } from './routes/search-params/default' -import { Route as RedirectTargetRouteImport } from './routes/redirect/$target' -import { Route as RawStreamSsrTextHintRouteImport } from './routes/raw-stream/ssr-text-hint' -import { Route as RawStreamSsrSingleRouteImport } from './routes/raw-stream/ssr-single' -import { Route as RawStreamSsrMultipleRouteImport } from './routes/raw-stream/ssr-multiple' -import { Route as RawStreamSsrMixedRouteImport } from './routes/raw-stream/ssr-mixed' -import { Route as RawStreamSsrBinaryHintRouteImport } from './routes/raw-stream/ssr-binary-hint' -import { Route as RawStreamClientCallRouteImport } from './routes/raw-stream/client-call' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as NotFoundViaLoaderRouteImport } from './routes/not-found/via-loader' -import { Route as NotFoundViaBeforeLoadTargetRootRouteImport } from './routes/not-found/via-beforeLoad-target-root' -import { Route as NotFoundViaBeforeLoadRouteImport } from './routes/not-found/via-beforeLoad' -import { Route as MultiCookieRedirectTargetRouteImport } from './routes/multi-cookie-redirect/target' -import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as InlineScriptsRouteImport } from './routes/inline-scripts' +import { Route as LinksRouteImport } from './routes/links' +import { Route as NotFoundRouteRouteImport } from './routes/not-found/route' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RawStreamRouteImport } from './routes/raw-stream' +import { Route as ScriptsRouteImport } from './routes/scripts' +import { Route as SearchParamsRouteRouteImport } from './routes/search-params/route' +import { Route as SpecialCharsRouteRouteImport } from './routes/specialChars/route' +import { Route as StreamRouteImport } from './routes/stream' +import { Route as UsersRouteImport } from './routes/users' import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as SpecialCharsMalformedRouteRouteImport } from './routes/specialChars/malformed/route' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as MultiCookieRedirectIndexRouteImport } from './routes/multi-cookie-redirect/index' +import { Route as MultiCookieRedirectTargetRouteImport } from './routes/multi-cookie-redirect/target' +import { Route as NotFoundIndexRouteImport } from './routes/not-found/index' import { Route as NotFoundParentBoundaryRouteRouteImport } from './routes/not-found/parent-boundary/route' -import { Route as RedirectTargetIndexRouteImport } from './routes/redirect/$target/index' -import { Route as SpecialCharsMalformedSearchRouteImport } from './routes/specialChars/malformed/search' -import { Route as SpecialCharsMalformedParamRouteImport } from './routes/specialChars/malformed/$param' -import { Route as RedirectTargetViaLoaderRouteImport } from './routes/redirect/$target/via-loader' -import { Route as RedirectTargetViaBeforeLoadRouteImport } from './routes/redirect/$target/via-beforeLoad' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as NotFoundParentBoundaryViaBeforeLoadRouteImport } from './routes/not-found/parent-boundary/via-beforeLoad' -import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as NotFoundViaBeforeLoadRouteImport } from './routes/not-found/via-beforeLoad' +import { Route as NotFoundViaBeforeLoadTargetRootRouteImport } from './routes/not-found/via-beforeLoad-target-root' +import { Route as NotFoundViaLoaderRouteImport } from './routes/not-found/via-loader' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as RawStreamIndexRouteImport } from './routes/raw-stream/index' +import { Route as RawStreamClientCallRouteImport } from './routes/raw-stream/client-call' +import { Route as RawStreamSsrBinaryHintRouteImport } from './routes/raw-stream/ssr-binary-hint' +import { Route as RawStreamSsrMixedRouteImport } from './routes/raw-stream/ssr-mixed' +import { Route as RawStreamSsrMultipleRouteImport } from './routes/raw-stream/ssr-multiple' +import { Route as RawStreamSsrSingleRouteImport } from './routes/raw-stream/ssr-single' +import { Route as RawStreamSsrTextHintRouteImport } from './routes/raw-stream/ssr-text-hint' +import { Route as RedirectIndexRouteImport } from './routes/redirect/index' +import { Route as RedirectTargetRouteImport } from './routes/redirect/$target' +import { Route as SearchParamsIndexRouteImport } from './routes/search-params/index' +import { Route as SearchParamsDefaultRouteImport } from './routes/search-params/default' +import { Route as SearchParamsLoaderThrowsRedirectRouteImport } from './routes/search-params/loader-throws-redirect' +import { Route as SpecialCharsParamRouteImport } from './routes/specialChars/$param' +import { Route as SpecialCharsHashRouteImport } from './routes/specialChars/hash' +import { Route as SpecialCharsMalformedRouteRouteImport } from './routes/specialChars/malformed/route' +import { Route as SpecialCharsSearchRouteImport } from './routes/specialChars/search' +import { Route as SpecialCharsChar45824Char54620Char48124Char44397RouteImport } from './routes/specialChars/대한민국' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as NotFoundParentBoundaryViaBeforeLoadRouteImport } from './routes/not-found/parent-boundary/via-beforeLoad' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as RedirectTargetIndexRouteImport } from './routes/redirect/$target/index' +import { Route as RedirectTargetViaBeforeLoadRouteImport } from './routes/redirect/$target/via-beforeLoad' +import { Route as RedirectTargetViaLoaderRouteImport } from './routes/redirect/$target/via-loader' +import { Route as SpecialCharsMalformedParamRouteImport } from './routes/specialChars/malformed/$param' +import { Route as SpecialCharsMalformedSearchRouteImport } from './routes/specialChars/malformed/search' import { Route as RedirectTargetServerFnIndexRouteImport } from './routes/redirect/$target/serverFn/index' -import { Route as RedirectTargetServerFnViaUseServerFnRouteImport } from './routes/redirect/$target/serverFn/via-useServerFn' -import { Route as RedirectTargetServerFnViaLoaderRouteImport } from './routes/redirect/$target/serverFn/via-loader' import { Route as RedirectTargetServerFnViaBeforeLoadRouteImport } from './routes/redirect/$target/serverFn/via-beforeLoad' +import { Route as RedirectTargetServerFnViaLoaderRouteImport } from './routes/redirect/$target/serverFn/via-loader' +import { Route as RedirectTargetServerFnViaUseServerFnRouteImport } from './routes/redirect/$target/serverFn/via-useServerFn' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const StreamRoute = StreamRouteImport.update({ - id: '/stream', - path: '/stream', - getParentRoute: () => rootRouteImport, -} as any) -const ScriptsRoute = ScriptsRouteImport.update({ - id: '/scripts', - path: '/scripts', - getParentRoute: () => rootRouteImport, -} as any) -const RawStreamRoute = RawStreamRouteImport.update({ - id: '/raw-stream', - path: '/raw-stream', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const LinksRoute = LinksRouteImport.update({ - id: '/links', - path: '/links', - getParentRoute: () => rootRouteImport, -} as any) -const InlineScriptsRoute = InlineScriptsRouteImport.update({ - id: '/inline-scripts', - path: '/inline-scripts', +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', getParentRoute: () => rootRouteImport, } as any) const DeferredRoute = DeferredRouteImport.update({ @@ -107,18 +81,14 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', +const InlineScriptsRoute = InlineScriptsRouteImport.update({ + id: '/inline-scripts', + path: '/inline-scripts', getParentRoute: () => rootRouteImport, } as any) -const SpecialCharsRouteRoute = SpecialCharsRouteRouteImport.update({ - id: '/specialChars', - path: '/specialChars', - getParentRoute: () => rootRouteImport, -} as any) -const SearchParamsRouteRoute = SearchParamsRouteRouteImport.update({ - id: '/search-params', - path: '/search-params', +const LinksRoute = LinksRouteImport.update({ + id: '/links', + path: '/links', getParentRoute: () => rootRouteImport, } as any) const NotFoundRouteRoute = NotFoundRouteRouteImport.update({ @@ -126,40 +96,49 @@ const NotFoundRouteRoute = NotFoundRouteRouteImport.update({ path: '/not-found', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, -} as any) -const SearchParamsIndexRoute = SearchParamsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => SearchParamsRouteRoute, -} as any) -const RedirectIndexRoute = RedirectIndexRouteImport.update({ - id: '/redirect/', - path: '/redirect/', +const RawStreamRoute = RawStreamRouteImport.update({ + id: '/raw-stream', + path: '/raw-stream', getParentRoute: () => rootRouteImport, } as any) -const RawStreamIndexRoute = RawStreamIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => RawStreamRoute, +const ScriptsRoute = ScriptsRouteImport.update({ + id: '/scripts', + path: '/scripts', + getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, +const SearchParamsRouteRoute = SearchParamsRouteRouteImport.update({ + id: '/search-params', + path: '/search-params', + getParentRoute: () => rootRouteImport, } as any) -const NotFoundIndexRoute = NotFoundIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => NotFoundRouteRoute, +const SpecialCharsRouteRoute = SpecialCharsRouteRouteImport.update({ + id: '/specialChars', + path: '/specialChars', + getParentRoute: () => rootRouteImport, +} as any) +const StreamRoute = StreamRouteImport.update({ + id: '/stream', + path: '/stream', + getParentRoute: () => rootRouteImport, +} as any) +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, +} as any) +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', + getParentRoute: () => rootRouteImport, } as any) const MultiCookieRedirectIndexRoute = MultiCookieRedirectIndexRouteImport.update({ @@ -167,86 +146,26 @@ const MultiCookieRedirectIndexRoute = path: '/multi-cookie-redirect/', getParentRoute: () => rootRouteImport, } as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const SpecialCharsChar45824Char54620Char48124Char44397Route = - SpecialCharsChar45824Char54620Char48124Char44397RouteImport.update({ - id: '/대한민국', - path: '/대한민국', - getParentRoute: () => SpecialCharsRouteRoute, +const MultiCookieRedirectTargetRoute = + MultiCookieRedirectTargetRouteImport.update({ + id: '/multi-cookie-redirect/target', + path: '/multi-cookie-redirect/target', + getParentRoute: () => rootRouteImport, } as any) -const SpecialCharsSearchRoute = SpecialCharsSearchRouteImport.update({ - id: '/search', - path: '/search', - getParentRoute: () => SpecialCharsRouteRoute, +const NotFoundIndexRoute = NotFoundIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => NotFoundRouteRoute, } as any) -const SpecialCharsHashRoute = SpecialCharsHashRouteImport.update({ - id: '/hash', - path: '/hash', - getParentRoute: () => SpecialCharsRouteRoute, -} as any) -const SpecialCharsParamRoute = SpecialCharsParamRouteImport.update({ - id: '/$param', - path: '/$param', - getParentRoute: () => SpecialCharsRouteRoute, -} as any) -const SearchParamsLoaderThrowsRedirectRoute = - SearchParamsLoaderThrowsRedirectRouteImport.update({ - id: '/loader-throws-redirect', - path: '/loader-throws-redirect', - getParentRoute: () => SearchParamsRouteRoute, +const NotFoundParentBoundaryRouteRoute = + NotFoundParentBoundaryRouteRouteImport.update({ + id: '/parent-boundary', + path: '/parent-boundary', + getParentRoute: () => NotFoundRouteRoute, } as any) -const SearchParamsDefaultRoute = SearchParamsDefaultRouteImport.update({ - id: '/default', - path: '/default', - getParentRoute: () => SearchParamsRouteRoute, -} as any) -const RedirectTargetRoute = RedirectTargetRouteImport.update({ - id: '/redirect/$target', - path: '/redirect/$target', - getParentRoute: () => rootRouteImport, -} as any) -const RawStreamSsrTextHintRoute = RawStreamSsrTextHintRouteImport.update({ - id: '/ssr-text-hint', - path: '/ssr-text-hint', - getParentRoute: () => RawStreamRoute, -} as any) -const RawStreamSsrSingleRoute = RawStreamSsrSingleRouteImport.update({ - id: '/ssr-single', - path: '/ssr-single', - getParentRoute: () => RawStreamRoute, -} as any) -const RawStreamSsrMultipleRoute = RawStreamSsrMultipleRouteImport.update({ - id: '/ssr-multiple', - path: '/ssr-multiple', - getParentRoute: () => RawStreamRoute, -} as any) -const RawStreamSsrMixedRoute = RawStreamSsrMixedRouteImport.update({ - id: '/ssr-mixed', - path: '/ssr-mixed', - getParentRoute: () => RawStreamRoute, -} as any) -const RawStreamSsrBinaryHintRoute = RawStreamSsrBinaryHintRouteImport.update({ - id: '/ssr-binary-hint', - path: '/ssr-binary-hint', - getParentRoute: () => RawStreamRoute, -} as any) -const RawStreamClientCallRoute = RawStreamClientCallRouteImport.update({ - id: '/client-call', - path: '/client-call', - getParentRoute: () => RawStreamRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const NotFoundViaLoaderRoute = NotFoundViaLoaderRouteImport.update({ - id: '/via-loader', - path: '/via-loader', +const NotFoundViaBeforeLoadRoute = NotFoundViaBeforeLoadRouteImport.update({ + id: '/via-beforeLoad', + path: '/via-beforeLoad', getParentRoute: () => NotFoundRouteRoute, } as any) const NotFoundViaBeforeLoadTargetRootRoute = @@ -255,25 +174,91 @@ const NotFoundViaBeforeLoadTargetRootRoute = path: '/via-beforeLoad-target-root', getParentRoute: () => NotFoundRouteRoute, } as any) -const NotFoundViaBeforeLoadRoute = NotFoundViaBeforeLoadRouteImport.update({ - id: '/via-beforeLoad', - path: '/via-beforeLoad', +const NotFoundViaLoaderRoute = NotFoundViaLoaderRouteImport.update({ + id: '/via-loader', + path: '/via-loader', getParentRoute: () => NotFoundRouteRoute, } as any) -const MultiCookieRedirectTargetRoute = - MultiCookieRedirectTargetRouteImport.update({ - id: '/multi-cookie-redirect/target', - path: '/multi-cookie-redirect/target', - getParentRoute: () => rootRouteImport, - } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const RawStreamIndexRoute = RawStreamIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamClientCallRoute = RawStreamClientCallRouteImport.update({ + id: '/client-call', + path: '/client-call', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrBinaryHintRoute = RawStreamSsrBinaryHintRouteImport.update({ + id: '/ssr-binary-hint', + path: '/ssr-binary-hint', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrMixedRoute = RawStreamSsrMixedRouteImport.update({ + id: '/ssr-mixed', + path: '/ssr-mixed', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrMultipleRoute = RawStreamSsrMultipleRouteImport.update({ + id: '/ssr-multiple', + path: '/ssr-multiple', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrSingleRoute = RawStreamSsrSingleRouteImport.update({ + id: '/ssr-single', + path: '/ssr-single', + getParentRoute: () => RawStreamRoute, +} as any) +const RawStreamSsrTextHintRoute = RawStreamSsrTextHintRouteImport.update({ + id: '/ssr-text-hint', + path: '/ssr-text-hint', + getParentRoute: () => RawStreamRoute, +} as any) +const RedirectIndexRoute = RedirectIndexRouteImport.update({ + id: '/redirect/', + path: '/redirect/', getParentRoute: () => rootRouteImport, } as any) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, +const RedirectTargetRoute = RedirectTargetRouteImport.update({ + id: '/redirect/$target', + path: '/redirect/$target', + getParentRoute: () => rootRouteImport, +} as any) +const SearchParamsIndexRoute = SearchParamsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SearchParamsRouteRoute, +} as any) +const SearchParamsDefaultRoute = SearchParamsDefaultRouteImport.update({ + id: '/default', + path: '/default', + getParentRoute: () => SearchParamsRouteRoute, +} as any) +const SearchParamsLoaderThrowsRedirectRoute = + SearchParamsLoaderThrowsRedirectRouteImport.update({ + id: '/loader-throws-redirect', + path: '/loader-throws-redirect', + getParentRoute: () => SearchParamsRouteRoute, + } as any) +const SpecialCharsParamRoute = SpecialCharsParamRouteImport.update({ + id: '/$param', + path: '/$param', + getParentRoute: () => SpecialCharsRouteRoute, +} as any) +const SpecialCharsHashRoute = SpecialCharsHashRouteImport.update({ + id: '/hash', + path: '/hash', + getParentRoute: () => SpecialCharsRouteRoute, } as any) const SpecialCharsMalformedRouteRoute = SpecialCharsMalformedRouteRouteImport.update({ @@ -281,76 +266,91 @@ const SpecialCharsMalformedRouteRoute = path: '/malformed', getParentRoute: () => SpecialCharsRouteRoute, } as any) -const NotFoundParentBoundaryRouteRoute = - NotFoundParentBoundaryRouteRouteImport.update({ - id: '/parent-boundary', - path: '/parent-boundary', - getParentRoute: () => NotFoundRouteRoute, +const SpecialCharsSearchRoute = SpecialCharsSearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => SpecialCharsRouteRoute, +} as any) +const SpecialCharsChar45824Char54620Char48124Char44397Route = + SpecialCharsChar45824Char54620Char48124Char44397RouteImport.update({ + id: '/대한민국', + path: '/대한민국', + getParentRoute: () => SpecialCharsRouteRoute, } as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRoute, +} as any) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, +} as any) +const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => LayoutLayout2Route, +} as any) +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => ApiUsersRoute, +} as any) +const NotFoundParentBoundaryViaBeforeLoadRoute = + NotFoundParentBoundaryViaBeforeLoadRouteImport.update({ + id: '/via-beforeLoad', + path: '/via-beforeLoad', + getParentRoute: () => NotFoundParentBoundaryRouteRoute, + } as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) const RedirectTargetIndexRoute = RedirectTargetIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => RedirectTargetRoute, } as any) -const SpecialCharsMalformedSearchRoute = - SpecialCharsMalformedSearchRouteImport.update({ - id: '/search', - path: '/search', - getParentRoute: () => SpecialCharsMalformedRouteRoute, - } as any) -const SpecialCharsMalformedParamRoute = - SpecialCharsMalformedParamRouteImport.update({ - id: '/$param', - path: '/$param', - getParentRoute: () => SpecialCharsMalformedRouteRoute, - } as any) -const RedirectTargetViaLoaderRoute = RedirectTargetViaLoaderRouteImport.update({ - id: '/via-loader', - path: '/via-loader', - getParentRoute: () => RedirectTargetRoute, -} as any) const RedirectTargetViaBeforeLoadRoute = RedirectTargetViaBeforeLoadRouteImport.update({ id: '/via-beforeLoad', path: '/via-beforeLoad', getParentRoute: () => RedirectTargetRoute, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, +const RedirectTargetViaLoaderRoute = RedirectTargetViaLoaderRouteImport.update({ + id: '/via-loader', + path: '/via-loader', + getParentRoute: () => RedirectTargetRoute, } as any) -const NotFoundParentBoundaryViaBeforeLoadRoute = - NotFoundParentBoundaryViaBeforeLoadRouteImport.update({ - id: '/via-beforeLoad', - path: '/via-beforeLoad', - getParentRoute: () => NotFoundParentBoundaryRouteRoute, +const SpecialCharsMalformedParamRoute = + SpecialCharsMalformedParamRouteImport.update({ + id: '/$param', + path: '/$param', + getParentRoute: () => SpecialCharsMalformedRouteRoute, + } as any) +const SpecialCharsMalformedSearchRoute = + SpecialCharsMalformedSearchRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => SpecialCharsMalformedRouteRoute, } as any) -const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => ApiUsersRoute, -} as any) -const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => LayoutLayout2Route, -} as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, -} as any) const RedirectTargetServerFnIndexRoute = RedirectTargetServerFnIndexRouteImport.update({ id: '/serverFn/', path: '/serverFn/', getParentRoute: () => RedirectTargetRoute, } as any) -const RedirectTargetServerFnViaUseServerFnRoute = - RedirectTargetServerFnViaUseServerFnRouteImport.update({ - id: '/serverFn/via-useServerFn', - path: '/serverFn/via-useServerFn', +const RedirectTargetServerFnViaBeforeLoadRoute = + RedirectTargetServerFnViaBeforeLoadRouteImport.update({ + id: '/serverFn/via-beforeLoad', + path: '/serverFn/via-beforeLoad', getParentRoute: () => RedirectTargetRoute, } as any) const RedirectTargetServerFnViaLoaderRoute = @@ -359,10 +359,10 @@ const RedirectTargetServerFnViaLoaderRoute = path: '/serverFn/via-loader', getParentRoute: () => RedirectTargetRoute, } as any) -const RedirectTargetServerFnViaBeforeLoadRoute = - RedirectTargetServerFnViaBeforeLoadRouteImport.update({ - id: '/serverFn/via-beforeLoad', - path: '/serverFn/via-beforeLoad', +const RedirectTargetServerFnViaUseServerFnRoute = + RedirectTargetServerFnViaUseServerFnRouteImport.update({ + id: '/serverFn/via-useServerFn', + path: '/serverFn/via-useServerFn', getParentRoute: () => RedirectTargetRoute, } as any) @@ -728,60 +728,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport - parentRoute: typeof rootRouteImport - } - '/stream': { - id: '/stream' - path: '/stream' - fullPath: '/stream' - preLoaderRoute: typeof StreamRouteImport - parentRoute: typeof rootRouteImport - } - '/scripts': { - id: '/scripts' - path: '/scripts' - fullPath: '/scripts' - preLoaderRoute: typeof ScriptsRouteImport - parentRoute: typeof rootRouteImport - } - '/raw-stream': { - id: '/raw-stream' - path: '/raw-stream' - fullPath: '/raw-stream' - preLoaderRoute: typeof RawStreamRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/links': { - id: '/links' - path: '/links' - fullPath: '/links' - preLoaderRoute: typeof LinksRouteImport - parentRoute: typeof rootRouteImport - } - '/inline-scripts': { - id: '/inline-scripts' - path: '/inline-scripts' - fullPath: '/inline-scripts' - preLoaderRoute: typeof InlineScriptsRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -791,18 +742,25 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/specialChars': { - id: '/specialChars' - path: '/specialChars' - fullPath: '/specialChars' - preLoaderRoute: typeof SpecialCharsRouteRouteImport + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/search-params': { - id: '/search-params' - path: '/search-params' - fullPath: '/search-params' - preLoaderRoute: typeof SearchParamsRouteRouteImport + '/inline-scripts': { + id: '/inline-scripts' + path: '/inline-scripts' + fullPath: '/inline-scripts' + preLoaderRoute: typeof InlineScriptsRouteImport + parentRoute: typeof rootRouteImport + } + '/links': { + id: '/links' + path: '/links' + fullPath: '/links' + preLoaderRoute: typeof LinksRouteImport parentRoute: typeof rootRouteImport } '/not-found': { @@ -812,200 +770,53 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof NotFoundRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute - } - '/search-params/': { - id: '/search-params/' - path: '/' - fullPath: '/search-params/' - preLoaderRoute: typeof SearchParamsIndexRouteImport - parentRoute: typeof SearchParamsRouteRoute - } - '/redirect/': { - id: '/redirect/' - path: '/redirect' - fullPath: '/redirect/' - preLoaderRoute: typeof RedirectIndexRouteImport + '/raw-stream': { + id: '/raw-stream' + path: '/raw-stream' + fullPath: '/raw-stream' + preLoaderRoute: typeof RawStreamRouteImport parentRoute: typeof rootRouteImport } - '/raw-stream/': { - id: '/raw-stream/' - path: '/' - fullPath: '/raw-stream/' - preLoaderRoute: typeof RawStreamIndexRouteImport - parentRoute: typeof RawStreamRoute - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute - } - '/not-found/': { - id: '/not-found/' - path: '/' - fullPath: '/not-found/' - preLoaderRoute: typeof NotFoundIndexRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/multi-cookie-redirect/': { - id: '/multi-cookie-redirect/' - path: '/multi-cookie-redirect' - fullPath: '/multi-cookie-redirect/' - preLoaderRoute: typeof MultiCookieRedirectIndexRouteImport + '/scripts': { + id: '/scripts' + path: '/scripts' + fullPath: '/scripts' + preLoaderRoute: typeof ScriptsRouteImport parentRoute: typeof rootRouteImport } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/specialChars/대한민국': { - id: '/specialChars/대한민국' - path: '/대한민국' - fullPath: '/specialChars/대한민국' - preLoaderRoute: typeof SpecialCharsChar45824Char54620Char48124Char44397RouteImport - parentRoute: typeof SpecialCharsRouteRoute - } - '/specialChars/search': { - id: '/specialChars/search' - path: '/search' - fullPath: '/specialChars/search' - preLoaderRoute: typeof SpecialCharsSearchRouteImport - parentRoute: typeof SpecialCharsRouteRoute - } - '/specialChars/hash': { - id: '/specialChars/hash' - path: '/hash' - fullPath: '/specialChars/hash' - preLoaderRoute: typeof SpecialCharsHashRouteImport - parentRoute: typeof SpecialCharsRouteRoute - } - '/specialChars/$param': { - id: '/specialChars/$param' - path: '/$param' - fullPath: '/specialChars/$param' - preLoaderRoute: typeof SpecialCharsParamRouteImport - parentRoute: typeof SpecialCharsRouteRoute - } - '/search-params/loader-throws-redirect': { - id: '/search-params/loader-throws-redirect' - path: '/loader-throws-redirect' - fullPath: '/search-params/loader-throws-redirect' - preLoaderRoute: typeof SearchParamsLoaderThrowsRedirectRouteImport - parentRoute: typeof SearchParamsRouteRoute - } - '/search-params/default': { - id: '/search-params/default' - path: '/default' - fullPath: '/search-params/default' - preLoaderRoute: typeof SearchParamsDefaultRouteImport - parentRoute: typeof SearchParamsRouteRoute - } - '/redirect/$target': { - id: '/redirect/$target' - path: '/redirect/$target' - fullPath: '/redirect/$target' - preLoaderRoute: typeof RedirectTargetRouteImport + '/search-params': { + id: '/search-params' + path: '/search-params' + fullPath: '/search-params' + preLoaderRoute: typeof SearchParamsRouteRouteImport parentRoute: typeof rootRouteImport } - '/raw-stream/ssr-text-hint': { - id: '/raw-stream/ssr-text-hint' - path: '/ssr-text-hint' - fullPath: '/raw-stream/ssr-text-hint' - preLoaderRoute: typeof RawStreamSsrTextHintRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-single': { - id: '/raw-stream/ssr-single' - path: '/ssr-single' - fullPath: '/raw-stream/ssr-single' - preLoaderRoute: typeof RawStreamSsrSingleRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-multiple': { - id: '/raw-stream/ssr-multiple' - path: '/ssr-multiple' - fullPath: '/raw-stream/ssr-multiple' - preLoaderRoute: typeof RawStreamSsrMultipleRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-mixed': { - id: '/raw-stream/ssr-mixed' - path: '/ssr-mixed' - fullPath: '/raw-stream/ssr-mixed' - preLoaderRoute: typeof RawStreamSsrMixedRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/ssr-binary-hint': { - id: '/raw-stream/ssr-binary-hint' - path: '/ssr-binary-hint' - fullPath: '/raw-stream/ssr-binary-hint' - preLoaderRoute: typeof RawStreamSsrBinaryHintRouteImport - parentRoute: typeof RawStreamRoute - } - '/raw-stream/client-call': { - id: '/raw-stream/client-call' - path: '/client-call' - fullPath: '/raw-stream/client-call' - preLoaderRoute: typeof RawStreamClientCallRouteImport - parentRoute: typeof RawStreamRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/not-found/via-loader': { - id: '/not-found/via-loader' - path: '/via-loader' - fullPath: '/not-found/via-loader' - preLoaderRoute: typeof NotFoundViaLoaderRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/not-found/via-beforeLoad-target-root': { - id: '/not-found/via-beforeLoad-target-root' - path: '/via-beforeLoad-target-root' - fullPath: '/not-found/via-beforeLoad-target-root' - preLoaderRoute: typeof NotFoundViaBeforeLoadTargetRootRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/not-found/via-beforeLoad': { - id: '/not-found/via-beforeLoad' - path: '/via-beforeLoad' - fullPath: '/not-found/via-beforeLoad' - preLoaderRoute: typeof NotFoundViaBeforeLoadRouteImport - parentRoute: typeof NotFoundRouteRoute - } - '/multi-cookie-redirect/target': { - id: '/multi-cookie-redirect/target' - path: '/multi-cookie-redirect/target' - fullPath: '/multi-cookie-redirect/target' - preLoaderRoute: typeof MultiCookieRedirectTargetRouteImport + '/specialChars': { + id: '/specialChars' + path: '/specialChars' + fullPath: '/specialChars' + preLoaderRoute: typeof SpecialCharsRouteRouteImport parentRoute: typeof rootRouteImport } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/stream': { + id: '/stream' + path: '/stream' + fullPath: '/stream' + preLoaderRoute: typeof StreamRouteImport + parentRoute: typeof rootRouteImport + } + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/_layout/_layout-2': { @@ -1015,12 +826,33 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LayoutLayout2RouteImport parentRoute: typeof LayoutRoute } - '/specialChars/malformed': { - id: '/specialChars/malformed' - path: '/malformed' - fullPath: '/specialChars/malformed' - preLoaderRoute: typeof SpecialCharsMalformedRouteRouteImport - parentRoute: typeof SpecialCharsRouteRoute + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport + parentRoute: typeof rootRouteImport + } + '/multi-cookie-redirect/': { + id: '/multi-cookie-redirect/' + path: '/multi-cookie-redirect' + fullPath: '/multi-cookie-redirect/' + preLoaderRoute: typeof MultiCookieRedirectIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/multi-cookie-redirect/target': { + id: '/multi-cookie-redirect/target' + path: '/multi-cookie-redirect/target' + fullPath: '/multi-cookie-redirect/target' + preLoaderRoute: typeof MultiCookieRedirectTargetRouteImport + parentRoute: typeof rootRouteImport + } + '/not-found/': { + id: '/not-found/' + path: '/' + fullPath: '/not-found/' + preLoaderRoute: typeof NotFoundIndexRouteImport + parentRoute: typeof NotFoundRouteRoute } '/not-found/parent-boundary': { id: '/not-found/parent-boundary' @@ -1029,6 +861,209 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof NotFoundParentBoundaryRouteRouteImport parentRoute: typeof NotFoundRouteRoute } + '/not-found/via-beforeLoad': { + id: '/not-found/via-beforeLoad' + path: '/via-beforeLoad' + fullPath: '/not-found/via-beforeLoad' + preLoaderRoute: typeof NotFoundViaBeforeLoadRouteImport + parentRoute: typeof NotFoundRouteRoute + } + '/not-found/via-beforeLoad-target-root': { + id: '/not-found/via-beforeLoad-target-root' + path: '/via-beforeLoad-target-root' + fullPath: '/not-found/via-beforeLoad-target-root' + preLoaderRoute: typeof NotFoundViaBeforeLoadTargetRootRouteImport + parentRoute: typeof NotFoundRouteRoute + } + '/not-found/via-loader': { + id: '/not-found/via-loader' + path: '/via-loader' + fullPath: '/not-found/via-loader' + preLoaderRoute: typeof NotFoundViaLoaderRouteImport + parentRoute: typeof NotFoundRouteRoute + } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/raw-stream/': { + id: '/raw-stream/' + path: '/' + fullPath: '/raw-stream/' + preLoaderRoute: typeof RawStreamIndexRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/client-call': { + id: '/raw-stream/client-call' + path: '/client-call' + fullPath: '/raw-stream/client-call' + preLoaderRoute: typeof RawStreamClientCallRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-binary-hint': { + id: '/raw-stream/ssr-binary-hint' + path: '/ssr-binary-hint' + fullPath: '/raw-stream/ssr-binary-hint' + preLoaderRoute: typeof RawStreamSsrBinaryHintRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-mixed': { + id: '/raw-stream/ssr-mixed' + path: '/ssr-mixed' + fullPath: '/raw-stream/ssr-mixed' + preLoaderRoute: typeof RawStreamSsrMixedRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-multiple': { + id: '/raw-stream/ssr-multiple' + path: '/ssr-multiple' + fullPath: '/raw-stream/ssr-multiple' + preLoaderRoute: typeof RawStreamSsrMultipleRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-single': { + id: '/raw-stream/ssr-single' + path: '/ssr-single' + fullPath: '/raw-stream/ssr-single' + preLoaderRoute: typeof RawStreamSsrSingleRouteImport + parentRoute: typeof RawStreamRoute + } + '/raw-stream/ssr-text-hint': { + id: '/raw-stream/ssr-text-hint' + path: '/ssr-text-hint' + fullPath: '/raw-stream/ssr-text-hint' + preLoaderRoute: typeof RawStreamSsrTextHintRouteImport + parentRoute: typeof RawStreamRoute + } + '/redirect/': { + id: '/redirect/' + path: '/redirect' + fullPath: '/redirect/' + preLoaderRoute: typeof RedirectIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect/$target': { + id: '/redirect/$target' + path: '/redirect/$target' + fullPath: '/redirect/$target' + preLoaderRoute: typeof RedirectTargetRouteImport + parentRoute: typeof rootRouteImport + } + '/search-params/': { + id: '/search-params/' + path: '/' + fullPath: '/search-params/' + preLoaderRoute: typeof SearchParamsIndexRouteImport + parentRoute: typeof SearchParamsRouteRoute + } + '/search-params/default': { + id: '/search-params/default' + path: '/default' + fullPath: '/search-params/default' + preLoaderRoute: typeof SearchParamsDefaultRouteImport + parentRoute: typeof SearchParamsRouteRoute + } + '/search-params/loader-throws-redirect': { + id: '/search-params/loader-throws-redirect' + path: '/loader-throws-redirect' + fullPath: '/search-params/loader-throws-redirect' + preLoaderRoute: typeof SearchParamsLoaderThrowsRedirectRouteImport + parentRoute: typeof SearchParamsRouteRoute + } + '/specialChars/$param': { + id: '/specialChars/$param' + path: '/$param' + fullPath: '/specialChars/$param' + preLoaderRoute: typeof SpecialCharsParamRouteImport + parentRoute: typeof SpecialCharsRouteRoute + } + '/specialChars/hash': { + id: '/specialChars/hash' + path: '/hash' + fullPath: '/specialChars/hash' + preLoaderRoute: typeof SpecialCharsHashRouteImport + parentRoute: typeof SpecialCharsRouteRoute + } + '/specialChars/malformed': { + id: '/specialChars/malformed' + path: '/malformed' + fullPath: '/specialChars/malformed' + preLoaderRoute: typeof SpecialCharsMalformedRouteRouteImport + parentRoute: typeof SpecialCharsRouteRoute + } + '/specialChars/search': { + id: '/specialChars/search' + path: '/search' + fullPath: '/specialChars/search' + preLoaderRoute: typeof SpecialCharsSearchRouteImport + parentRoute: typeof SpecialCharsRouteRoute + } + '/specialChars/대한민국': { + id: '/specialChars/대한민국' + path: '/대한민국' + fullPath: '/specialChars/대한민국' + preLoaderRoute: typeof SpecialCharsChar45824Char54620Char48124Char44397RouteImport + parentRoute: typeof SpecialCharsRouteRoute + } + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute + } + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route + } + '/_layout/_layout-2/layout-b': { + id: '/_layout/_layout-2/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport + parentRoute: typeof LayoutLayout2Route + } + '/api/users/$userId': { + id: '/api/users/$userId' + path: '/$userId' + fullPath: '/api/users/$userId' + preLoaderRoute: typeof ApiUsersUserIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/not-found/parent-boundary/via-beforeLoad': { + id: '/not-found/parent-boundary/via-beforeLoad' + path: '/via-beforeLoad' + fullPath: '/not-found/parent-boundary/via-beforeLoad' + preLoaderRoute: typeof NotFoundParentBoundaryViaBeforeLoadRouteImport + parentRoute: typeof NotFoundParentBoundaryRouteRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport + } '/redirect/$target/': { id: '/redirect/$target/' path: '/' @@ -1036,27 +1071,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RedirectTargetIndexRouteImport parentRoute: typeof RedirectTargetRoute } - '/specialChars/malformed/search': { - id: '/specialChars/malformed/search' - path: '/search' - fullPath: '/specialChars/malformed/search' - preLoaderRoute: typeof SpecialCharsMalformedSearchRouteImport - parentRoute: typeof SpecialCharsMalformedRouteRoute - } - '/specialChars/malformed/$param': { - id: '/specialChars/malformed/$param' - path: '/$param' - fullPath: '/specialChars/malformed/$param' - preLoaderRoute: typeof SpecialCharsMalformedParamRouteImport - parentRoute: typeof SpecialCharsMalformedRouteRoute - } - '/redirect/$target/via-loader': { - id: '/redirect/$target/via-loader' - path: '/via-loader' - fullPath: '/redirect/$target/via-loader' - preLoaderRoute: typeof RedirectTargetViaLoaderRouteImport - parentRoute: typeof RedirectTargetRoute - } '/redirect/$target/via-beforeLoad': { id: '/redirect/$target/via-beforeLoad' path: '/via-beforeLoad' @@ -1064,40 +1078,26 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RedirectTargetViaBeforeLoadRouteImport parentRoute: typeof RedirectTargetRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/redirect/$target/via-loader': { + id: '/redirect/$target/via-loader' + path: '/via-loader' + fullPath: '/redirect/$target/via-loader' + preLoaderRoute: typeof RedirectTargetViaLoaderRouteImport + parentRoute: typeof RedirectTargetRoute } - '/not-found/parent-boundary/via-beforeLoad': { - id: '/not-found/parent-boundary/via-beforeLoad' - path: '/via-beforeLoad' - fullPath: '/not-found/parent-boundary/via-beforeLoad' - preLoaderRoute: typeof NotFoundParentBoundaryViaBeforeLoadRouteImport - parentRoute: typeof NotFoundParentBoundaryRouteRoute + '/specialChars/malformed/$param': { + id: '/specialChars/malformed/$param' + path: '/$param' + fullPath: '/specialChars/malformed/$param' + preLoaderRoute: typeof SpecialCharsMalformedParamRouteImport + parentRoute: typeof SpecialCharsMalformedRouteRoute } - '/api/users/$userId': { - id: '/api/users/$userId' - path: '/$userId' - fullPath: '/api/users/$userId' - preLoaderRoute: typeof ApiUsersUserIdRouteImport - parentRoute: typeof ApiUsersRoute - } - '/_layout/_layout-2/layout-b': { - id: '/_layout/_layout-2/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport - parentRoute: typeof LayoutLayout2Route - } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/specialChars/malformed/search': { + id: '/specialChars/malformed/search' + path: '/search' + fullPath: '/specialChars/malformed/search' + preLoaderRoute: typeof SpecialCharsMalformedSearchRouteImport + parentRoute: typeof SpecialCharsMalformedRouteRoute } '/redirect/$target/serverFn/': { id: '/redirect/$target/serverFn/' @@ -1106,11 +1106,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RedirectTargetServerFnIndexRouteImport parentRoute: typeof RedirectTargetRoute } - '/redirect/$target/serverFn/via-useServerFn': { - id: '/redirect/$target/serverFn/via-useServerFn' - path: '/serverFn/via-useServerFn' - fullPath: '/redirect/$target/serverFn/via-useServerFn' - preLoaderRoute: typeof RedirectTargetServerFnViaUseServerFnRouteImport + '/redirect/$target/serverFn/via-beforeLoad': { + id: '/redirect/$target/serverFn/via-beforeLoad' + path: '/serverFn/via-beforeLoad' + fullPath: '/redirect/$target/serverFn/via-beforeLoad' + preLoaderRoute: typeof RedirectTargetServerFnViaBeforeLoadRouteImport parentRoute: typeof RedirectTargetRoute } '/redirect/$target/serverFn/via-loader': { @@ -1120,11 +1120,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RedirectTargetServerFnViaLoaderRouteImport parentRoute: typeof RedirectTargetRoute } - '/redirect/$target/serverFn/via-beforeLoad': { - id: '/redirect/$target/serverFn/via-beforeLoad' - path: '/serverFn/via-beforeLoad' - fullPath: '/redirect/$target/serverFn/via-beforeLoad' - preLoaderRoute: typeof RedirectTargetServerFnViaBeforeLoadRouteImport + '/redirect/$target/serverFn/via-useServerFn': { + id: '/redirect/$target/serverFn/via-useServerFn' + path: '/serverFn/via-useServerFn' + fullPath: '/redirect/$target/serverFn/via-useServerFn' + preLoaderRoute: typeof RedirectTargetServerFnViaUseServerFnRouteImport parentRoute: typeof RedirectTargetRoute } } diff --git a/e2e/vue-start/basic/src/routes/__root.tsx b/e2e/vue-start/basic/src/routes/__root.tsx index 843ec05893..9da2c581fe 100644 --- a/e2e/vue-start/basic/src/routes/__root.tsx +++ b/e2e/vue-start/basic/src/routes/__root.tsx @@ -1,4 +1,5 @@ /// +import { defineComponent } from 'vue' import { Body, ClientOnly, @@ -16,6 +17,119 @@ import { NotFound } from '~/components/NotFound' import '~/styles/app.css' import { seo } from '~/utils/seo' +const RootComponent = defineComponent({ + setup() { + const routerState = useRouterState({ + select: (state) => ({ isLoading: state.isLoading, status: state.status }), + }) + return () => ( + + + + + +
+ + Home + {' '} + + Posts + {' '} + + Users + {' '} + + Layout + {' '} + + Scripts + {' '} + + Inline Scripts + {' '} + + Deferred + {' '} + + redirect + {' '} + + Raw Stream + {' '} + + This Route Does Not Exist + +
+ + + + +
This is an inline styled div
+ + + + + ) + }, +}) + export const Route = createRootRoute({ head: () => ({ meta: [ @@ -62,119 +176,11 @@ export const Route = createRootRoute({ }, ], }), - errorComponent: (props) =>

{props.error.stack}

, + errorComponent: (props) => ( +

+ {props.error instanceof Error ? props.error.stack : String(props.error)} +

+ ), notFoundComponent: () => , component: RootComponent, }) - -function RootComponent() { - const routerState = useRouterState({ - select: (state) => ({ isLoading: state.isLoading, status: state.status }), - }) - - return ( - - - - - -
- - Home - {' '} - - Posts - {' '} - - Users - {' '} - - Layout - {' '} - - Scripts - {' '} - - Inline Scripts - {' '} - - Deferred - {' '} - - redirect - {' '} - - Raw Stream - {' '} - - This Route Does Not Exist - -
- - - - -
This is an inline styled div
- - - - - ) -} diff --git a/e2e/vue-start/basic/src/routes/api/users.$userId.ts b/e2e/vue-start/basic/src/routes/api/users.$userId.ts index 50b9ca995a..24938d51c2 100644 --- a/e2e/vue-start/basic/src/routes/api/users.$userId.ts +++ b/e2e/vue-start/basic/src/routes/api/users.$userId.ts @@ -1,19 +1,15 @@ import { createFileRoute } from '@tanstack/vue-router' import type { User } from '~/utils/users' -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} - export const Route = createFileRoute('/api/users/$userId')({ server: { handlers: { GET: async ({ params, request }) => { console.info(`Fetching users by id=${params.userId}... @`, request.url) try { - const res = await fetch(`${queryURL}/users/${params.userId}`) + const res = await fetch( + `https://jsonplaceholder.typicode.com/users/${params.userId}`, + ) if (!res.ok) { throw new Error('Failed to fetch user') } diff --git a/e2e/vue-start/basic/src/routes/api/users.ts b/e2e/vue-start/basic/src/routes/api/users.ts index 97989b93ca..c6045977b8 100644 --- a/e2e/vue-start/basic/src/routes/api/users.ts +++ b/e2e/vue-start/basic/src/routes/api/users.ts @@ -38,19 +38,13 @@ const testMiddleware = createMiddleware() return result }) -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} - export const Route = createFileRoute('/api/users')({ server: { middleware: [testMiddleware, userLoggerMiddleware, testParentMiddleware], handlers: { GET: async ({ request }) => { console.info('Fetching users... @', request.url) - const res = await fetch(`${queryURL}/users`) + const res = await fetch('https://jsonplaceholder.typicode.com/users') if (!res.ok) { throw new Error('Failed to fetch users') } diff --git a/e2e/vue-start/basic/src/routes/not-found/index.tsx b/e2e/vue-start/basic/src/routes/not-found/index.tsx index 9f7e3b4b33..ecd12d1dad 100644 --- a/e2e/vue-start/basic/src/routes/not-found/index.tsx +++ b/e2e/vue-start/basic/src/routes/not-found/index.tsx @@ -1,9 +1,10 @@ +import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/not-found/')({ - component: () => { +const RouteComponent = defineComponent({ + setup() { const preload = Route.useSearch({ select: (s) => s.preload }) - return ( + return () => (
( +
+
+ {loaderData.value.parentLoaderData} +
+
+ ) + }, +}) + export const Route = createFileRoute('/not-found/parent-boundary')({ loader: () => ({ parentLoaderData: 'ready', @@ -15,15 +29,3 @@ function RouteComponent() {
) } - -function ParentBoundaryNotFoundComponent() { - const loaderData = Route.useLoaderData() - - return ( -
-
- {loaderData.value.parentLoaderData} -
-
- ) -} diff --git a/e2e/vue-start/basic/src/routes/posts.$postId.tsx b/e2e/vue-start/basic/src/routes/posts.$postId.tsx index 4d71080d64..edda7f0017 100644 --- a/e2e/vue-start/basic/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/basic/src/routes/posts.$postId.tsx @@ -1,9 +1,32 @@ +import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '~/utils/posts' import { NotFound } from '~/components/NotFound' import { PostErrorComponent } from '~/components/PostErrorComponent' +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + return () => ( +
+

{post.value.title}

+
{post.value.body}
+ + Deep View + +
+ ) + }, +}) + export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost({ data: postId }), errorComponent: PostErrorComponent, @@ -12,24 +35,3 @@ export const Route = createFileRoute('/posts/$postId')({ return Post not found }, }) - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

{post.value.title}

-
{post.value.body}
- - Deep View - -
- ) -} diff --git a/e2e/vue-start/basic/src/routes/posts.tsx b/e2e/vue-start/basic/src/routes/posts.tsx index 1a9d58a31d..64d4754f2f 100644 --- a/e2e/vue-start/basic/src/routes/posts.tsx +++ b/e2e/vue-start/basic/src/routes/posts.tsx @@ -1,7 +1,36 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '~/utils/posts' +const PostsComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + return () => ( +
+
    + {posts.value.map((post) => ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ))} +
+
+ +
+ ) + }, +}) + export const Route = createFileRoute('/posts')({ head: () => ({ meta: [ @@ -13,30 +42,3 @@ export const Route = createFileRoute('/posts')({ loader: async () => fetchPosts(), component: PostsComponent, }) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {posts.value.map((post) => ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ))} -
-
- -
- ) -} diff --git a/e2e/vue-start/basic/src/routes/posts_.$postId.deep.tsx b/e2e/vue-start/basic/src/routes/posts_.$postId.deep.tsx index a52c6f32f7..f77ae7d3ab 100644 --- a/e2e/vue-start/basic/src/routes/posts_.$postId.deep.tsx +++ b/e2e/vue-start/basic/src/routes/posts_.$postId.deep.tsx @@ -1,24 +1,26 @@ +import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { PostErrorComponent } from '~/components/PostErrorComponent' import { fetchPost } from '~/utils/posts' +const PostDeepComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + return () => ( +
+ + ← All Posts + +

{post.value.title}

+
{post.value.body}
+
+ ) + }, +}) + export const Route = createFileRoute('/posts_/$postId/deep')({ loader: async ({ params: { postId } }) => fetchPost({ data: postId }), errorComponent: PostErrorComponent, component: PostDeepComponent, }) - -function PostDeepComponent() { - const post = Route.useLoaderData() - - return ( -
- - ← All Posts - -

{post.value.title}

-
{post.value.body}
-
- ) -} diff --git a/e2e/vue-start/basic/src/routes/redirect/$target/index.tsx b/e2e/vue-start/basic/src/routes/redirect/$target/index.tsx index a8c3c75b1f..e39bda5bcf 100644 --- a/e2e/vue-start/basic/src/routes/redirect/$target/index.tsx +++ b/e2e/vue-start/basic/src/routes/redirect/$target/index.tsx @@ -1,9 +1,10 @@ +import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' -export const Route = createFileRoute('/redirect/$target/')({ - component: () => { +const RouteComponent = defineComponent({ + setup() { const preload = Route.useSearch({ select: (s) => s.preload }) - return ( + return () => (
{ +const RouteComponent = defineComponent({ + setup() { const params = Route.useParams() - return ( + return () => (

redirect test with server functions (target {params.value.target}) @@ -87,3 +88,7 @@ export const Route = createFileRoute('/redirect/$target/serverFn/')({ ) }, }) + +export const Route = createFileRoute('/redirect/$target/serverFn/')({ + component: RouteComponent, +}) diff --git a/e2e/vue-start/basic/src/routes/redirect/$target/serverFn/via-useServerFn.tsx b/e2e/vue-start/basic/src/routes/redirect/$target/serverFn/via-useServerFn.tsx index 399e8ac995..093a591636 100644 --- a/e2e/vue-start/basic/src/routes/redirect/$target/serverFn/via-useServerFn.tsx +++ b/e2e/vue-start/basic/src/routes/redirect/$target/serverFn/via-useServerFn.tsx @@ -1,13 +1,12 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { RedirectOnClick } from '~/components/RedirectOnClick' -export const Route = createFileRoute( - '/redirect/$target/serverFn/via-useServerFn', -)({ - component: () => { +const RouteComponent = defineComponent({ + setup() { const params = Route.useParams() const search = Route.useSearch() - return ( + return () => ( ( + <> +
{search.value.default}
+
{context.value.hello}
+ + ) + }, +}) + export const Route = createFileRoute('/search-params/default')({ validateSearch: z.object({ default: z.string().default('d1'), @@ -15,14 +29,5 @@ export const Route = createFileRoute('/search-params/default')({ throw new Error('Context hello is not "world"') } }, - component: () => { - const search = Route.useSearch() - const context = Route.useRouteContext() - return ( - <> -
{search.value.default}
-
{context.value.hello}
- - ) - }, + component: RouteComponent, }) diff --git a/e2e/vue-start/basic/src/routes/search-params/loader-throws-redirect.tsx b/e2e/vue-start/basic/src/routes/search-params/loader-throws-redirect.tsx index 14b137abc6..ccd1276387 100644 --- a/e2e/vue-start/basic/src/routes/search-params/loader-throws-redirect.tsx +++ b/e2e/vue-start/basic/src/routes/search-params/loader-throws-redirect.tsx @@ -1,6 +1,19 @@ +import { defineComponent } from 'vue' import { redirect, createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' +const RouteComponent = defineComponent({ + setup() { + const search = Route.useSearch() + return () => ( +
+

SearchParams

+
{search.value.step}
+
+ ) + }, +}) + export const Route = createFileRoute('/search-params/loader-throws-redirect')({ validateSearch: z.object({ step: z.enum(['a', 'b', 'c']).optional(), @@ -14,13 +27,5 @@ export const Route = createFileRoute('/search-params/loader-throws-redirect')({ }) } }, - component: () => { - const search = Route.useSearch() - return ( -
-

SearchParams

-
{search.value.step}
-
- ) - }, + component: RouteComponent, }) diff --git a/e2e/vue-start/basic/src/routes/specialChars/$param.tsx b/e2e/vue-start/basic/src/routes/specialChars/$param.tsx index de3cba0a97..ec315ede1f 100644 --- a/e2e/vue-start/basic/src/routes/specialChars/$param.tsx +++ b/e2e/vue-start/basic/src/routes/specialChars/$param.tsx @@ -1,15 +1,18 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' +const RouteComponent = defineComponent({ + setup() { + const params = Route.useParams() + return () => ( +
+ Hello "/specialChars/$param":{' '} + {params.value.param} +
+ ) + }, +}) + export const Route = createFileRoute('/specialChars/$param')({ component: RouteComponent, }) - -function RouteComponent() { - const params = Route.useParams() - return ( -
- Hello "/specialChars/$param":{' '} - {params.value.param} -
- ) -} diff --git a/e2e/vue-start/basic/src/routes/specialChars/malformed/$param.tsx b/e2e/vue-start/basic/src/routes/specialChars/malformed/$param.tsx index 7160964549..2b19e7e36e 100644 --- a/e2e/vue-start/basic/src/routes/specialChars/malformed/$param.tsx +++ b/e2e/vue-start/basic/src/routes/specialChars/malformed/$param.tsx @@ -1,15 +1,20 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' +const RouteComponent = defineComponent({ + setup() { + const params = Route.useParams() + return () => ( +
+ Hello "/specialChars/malformed/$param":{' '} + + {params.value.param} + +
+ ) + }, +}) + export const Route = createFileRoute('/specialChars/malformed/$param')({ component: RouteComponent, }) - -function RouteComponent() { - const params = Route.useParams() - return ( -
- Hello "/specialChars/malformed/$param":{' '} - {params.value.param} -
- ) -} diff --git a/e2e/vue-start/basic/src/routes/specialChars/malformed/search.tsx b/e2e/vue-start/basic/src/routes/specialChars/malformed/search.tsx index 2438604954..8d6ad5b1dd 100644 --- a/e2e/vue-start/basic/src/routes/specialChars/malformed/search.tsx +++ b/e2e/vue-start/basic/src/routes/specialChars/malformed/search.tsx @@ -1,22 +1,24 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import z from 'zod' +const RouteComponent = defineComponent({ + setup() { + const search = Route.useSearch() + return () => ( +
+ Hello "/specialChars/malformed/search"! + + {search.value.searchParam} + +
+ ) + }, +}) + export const Route = createFileRoute('/specialChars/malformed/search')({ validateSearch: z.object({ searchParam: z.string(), }), component: RouteComponent, }) - -function RouteComponent() { - const search = Route.useSearch() - - return ( -
- Hello "/specialChars/malformed/search"! - - {search.value.searchParam} - -
- ) -} diff --git a/e2e/vue-start/basic/src/routes/specialChars/search.tsx b/e2e/vue-start/basic/src/routes/specialChars/search.tsx index 5ba858e747..b4e022639d 100644 --- a/e2e/vue-start/basic/src/routes/specialChars/search.tsx +++ b/e2e/vue-start/basic/src/routes/specialChars/search.tsx @@ -1,22 +1,24 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import z from 'zod' +const RouteComponent = defineComponent({ + setup() { + const search = Route.useSearch() + return () => ( +
+ Hello "/specialChars/search"! + + {search.value.searchParam} + +
+ ) + }, +}) + export const Route = createFileRoute('/specialChars/search')({ validateSearch: z.object({ searchParam: z.string(), }), component: RouteComponent, }) - -function RouteComponent() { - const search = Route.useSearch() - - return ( -
- Hello "/specialChars/search"! - - {search.value.searchParam} - -
- ) -} diff --git a/e2e/vue-start/basic/src/routes/users.$userId.tsx b/e2e/vue-start/basic/src/routes/users.$userId.tsx index 420b7e4a50..76340cf9fb 100644 --- a/e2e/vue-start/basic/src/routes/users.$userId.tsx +++ b/e2e/vue-start/basic/src/routes/users.$userId.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import axios from 'redaxios' @@ -6,6 +7,18 @@ import type { User } from '~/utils/users' import { NotFound } from '~/components/NotFound' import { UserErrorComponent } from '~/components/UserErrorComponent' +const UserComponent = defineComponent({ + setup() { + const user = Route.useLoaderData() + return () => ( +
+

{user.value.name}

+
{user.value.email}
+
+ ) + }, +}) + export const Route = createFileRoute('/users/$userId')({ loader: async ({ params: { userId } }) => { const router = await getRouterInstance() @@ -22,14 +35,3 @@ export const Route = createFileRoute('/users/$userId')({ return User not found }, }) - -function UserComponent() { - const user = Route.useLoaderData() - - return ( -
-

{user.value.name}

-
{user.value.email}
-
- ) -} diff --git a/e2e/vue-start/basic/src/routes/users.tsx b/e2e/vue-start/basic/src/routes/users.tsx index 1e0b297dd2..3d8ef31598 100644 --- a/e2e/vue-start/basic/src/routes/users.tsx +++ b/e2e/vue-start/basic/src/routes/users.tsx @@ -1,9 +1,41 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { getRouterInstance } from '@tanstack/vue-start' import axios from 'redaxios' import type { User } from '~/utils/users' +const UsersComponent = defineComponent({ + setup() { + const users = Route.useLoaderData() + return () => ( +
+
    + {[ + ...users.value, + { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, + ].map((user) => ( +
  • + +
    {user.name}
    + +
  • + ))} +
+
+ +
+ ) + }, +}) + export const Route = createFileRoute('/users')({ loader: async () => { const router = await getRouterInstance() @@ -16,33 +48,3 @@ export const Route = createFileRoute('/users')({ }, component: UsersComponent, }) - -function UsersComponent() { - const users = Route.useLoaderData() - - return ( -
-
    - {[ - ...users.value, - { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, - ].map((user) => ( -
  • - -
    {user.name}
    - -
  • - ))} -
-
- -
- ) -} diff --git a/e2e/vue-start/basic/src/utils/posts.tsx b/e2e/vue-start/basic/src/utils/posts.tsx index 66cb298f83..d8e2dc7450 100644 --- a/e2e/vue-start/basic/src/utils/posts.tsx +++ b/e2e/vue-start/basic/src/utils/posts.tsx @@ -8,18 +8,12 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} - export const fetchPost = createServerFn({ method: 'GET' }) .validator((postId: string) => postId) .handler(async ({ data: postId }) => { console.info(`Fetching post with id ${postId}...`) const post = await axios - .get(`${queryURL}/posts/${postId}`) + .get(`https://jsonplaceholder.typicode.com/posts/${postId}`) .then((r) => r.data) .catch((err) => { console.error(err) @@ -36,7 +30,7 @@ export const fetchPosts = createServerFn({ method: 'GET' }).handler( async () => { console.info('Fetching posts...') return axios - .get>(`${queryURL}/posts`) + .get>('https://jsonplaceholder.typicode.com/posts') .then((r) => r.data.slice(0, 10)) }, ) diff --git a/e2e/vue-start/basic/src/utils/users.tsx b/e2e/vue-start/basic/src/utils/users.tsx index 46be4b1580..7ba645b383 100644 --- a/e2e/vue-start/basic/src/utils/users.tsx +++ b/e2e/vue-start/basic/src/utils/users.tsx @@ -3,7 +3,3 @@ export type User = { name: string email: string } - -const PORT = process.env.VITE_SERVER_PORT || 3000 - -export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/vue-start/basic/src/vite-env.d.ts b/e2e/vue-start/basic/src/vite-env.d.ts index e8259b1e33..4da6234c8a 100644 --- a/e2e/vue-start/basic/src/vite-env.d.ts +++ b/e2e/vue-start/basic/src/vite-env.d.ts @@ -2,7 +2,6 @@ interface ImportMetaEnv { readonly VITE_NODE_ENV: string - readonly VITE_EXTERNAL_PORT: string readonly VITE_SERVER_PORT: string } diff --git a/e2e/vue-start/basic/tests/fixture-api.spec.ts b/e2e/vue-start/basic/tests/fixture-api.spec.ts new file mode 100644 index 0000000000..6c9b26dc4c --- /dev/null +++ b/e2e/vue-start/basic/tests/fixture-api.spec.ts @@ -0,0 +1,11 @@ +import { expect, test } from '@playwright/test' + +test('server API receives canned users without a fixture listener', async ({ + request, +}) => { + const response = await request.get('/api/users') + expect(response.ok()).toBe(true) + const users = await response.json() + expect(users).toHaveLength(10) + expect(users[0]).toMatchObject({ id: 1, name: 'Leanne Graham' }) +}) diff --git a/e2e/vue-start/basic/tests/redirect.spec.ts b/e2e/vue-start/basic/tests/redirect.spec.ts index 2f6354aa81..8e6ceba5b9 100644 --- a/e2e/vue-start/basic/tests/redirect.spec.ts +++ b/e2e/vue-start/basic/tests/redirect.spec.ts @@ -1,19 +1,14 @@ import queryString from 'node:querystring' -import { expect, type Page } from '@playwright/test' +import { expect } from '@playwright/test' +import { test } from '@tanstack/router-e2e-utils' import combinateImport from 'combinate' -import { - getDummyServerPort, - getTestServerPort, - test, -} from '@tanstack/router-e2e-utils' -import { getE2EPortKey } from './utils/getE2EPortKey.ts' +import type { Page } from '@playwright/test' // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport -const e2ePortKey = getE2EPortKey() -const PORT = await getTestServerPort(e2ePortKey) -const EXTERNAL_HOST_PORT = await getDummyServerPort(e2ePortKey) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const EXTERNAL_ORIGIN = `http://127.0.0.1:${PORT}` const POSTS_URL = `http://localhost:${PORT}/posts` async function waitForRouterIdle(page: Page) { @@ -106,7 +101,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, + externalHost: `${EXTERNAL_ORIGIN}/`, }) if (scenario === 'navigate') { @@ -119,7 +114,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/external/via-${thrower}?${q}`) } - const url = `http://localhost:${EXTERNAL_HOST_PORT}/` + const url = `${EXTERNAL_ORIGIN}/` await page.waitForURL(url) expect(page.url()).toBe(url) @@ -140,7 +135,7 @@ test.describe('redirects', () => { }) => { let fullPageLoad = false const q = queryString.stringify({ - externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, + externalHost: `${EXTERNAL_ORIGIN}/`, reloadDocument, }) @@ -159,10 +154,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/${target}/serverFn/via-${thrower}?${q}`) } - const url = - target === 'internal' - ? POSTS_URL - : `http://localhost:${EXTERNAL_HOST_PORT}/` + const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` await page.waitForURL(url) expect(page.url()).toBe(url) if (target === 'internal' && scenario === 'navigate') { @@ -184,7 +176,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, + externalHost: `${EXTERNAL_ORIGIN}/`, reloadDocument, }) @@ -201,10 +193,7 @@ test.describe('redirects', () => { await button.click() - const url = - target === 'internal' - ? POSTS_URL - : `http://localhost:${EXTERNAL_HOST_PORT}/` + const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` await page.waitForURL(url) expect(page.url()).toBe(url) if (target === 'internal') { diff --git a/e2e/vue-start/basic/tests/setup/global.setup.ts b/e2e/vue-start/basic/tests/setup/global.setup.ts deleted file mode 100644 index cd38c35885..0000000000 --- a/e2e/vue-start/basic/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import { getE2EPortKey } from '../utils/getE2EPortKey.ts' - -export default async function setup() { - await e2eStartDummyServer(getE2EPortKey()) -} diff --git a/e2e/vue-start/basic/tests/setup/global.teardown.ts b/e2e/vue-start/basic/tests/setup/global.teardown.ts deleted file mode 100644 index 36e5c92858..0000000000 --- a/e2e/vue-start/basic/tests/setup/global.teardown.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import { getE2EPortKey } from '../utils/getE2EPortKey.ts' - -export default async function teardown() { - try { - await e2eStopDummyServer(getE2EPortKey()) - } catch {} -} diff --git a/e2e/vue-start/basic/tests/setup/waitForDummyServer.ts b/e2e/vue-start/basic/tests/setup/waitForDummyServer.ts deleted file mode 100644 index 88c18fd79e..0000000000 --- a/e2e/vue-start/basic/tests/setup/waitForDummyServer.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { getDummyServerPort } from '@tanstack/router-e2e-utils' -import { getE2EPortKey } from '../utils/getE2EPortKey.ts' - -const timeoutMs = 10_000 -const retryIntervalMs = 100 - -export default async function waitForDummyServer() { - const port = await getDummyServerPort(getE2EPortKey()) - const deadline = Date.now() + timeoutMs - - while (Date.now() < deadline) { - try { - const response = await fetch(`http://localhost:${port}/`) - - if (response.ok) { - return - } - } catch {} - - await new Promise((resolve) => setTimeout(resolve, retryIntervalMs)) - } - - throw new Error(`Timed out waiting for dummy server on port ${port}`) -} diff --git a/e2e/vue-start/basic/tests/utils/getE2EPortKey.ts b/e2e/vue-start/basic/tests/utils/getE2EPortKey.ts deleted file mode 100644 index 48be6a9027..0000000000 --- a/e2e/vue-start/basic/tests/utils/getE2EPortKey.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { getPackageName } from './getPackageName.ts' - -export function getE2EPortKey() { - return process.env.E2E_PORT_KEY ?? getPackageName() -} diff --git a/e2e/vue-start/css-modules/package.json b/e2e/vue-start/css-modules/package.json index 7e28e9d5a8..3671774644 100644 --- a/e2e/vue-start/css-modules/package.json +++ b/e2e/vue-start/css-modules/package.json @@ -11,7 +11,7 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js", "test:e2e:dev": "MODE=dev playwright test --project=chromium", "test:e2e:prod": "playwright test --project=chromium", - "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:dev" + "test:e2e": "pnpm run test:e2e:dev" }, "dependencies": { "@tanstack/vue-router": "workspace:*", @@ -24,8 +24,9 @@ "@types/node": "^22.10.2", "@vitejs/plugin-vue-jsx": "^5.1.5", "sass": "^1.97.2", - "srvx": "^0.11.9", - "typescript": "^6.0.2", + "srvx": "^1.0.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/e2e/vue-start/css-modules/playwright.config.ts b/e2e/vue-start/css-modules/playwright.config.ts index 0b810d5372..a50ac5ae63 100644 --- a/e2e/vue-start/css-modules/playwright.config.ts +++ b/e2e/vue-start/css-modules/playwright.config.ts @@ -1,10 +1,9 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' const mode = process.env.MODE ?? 'prod' const isDev = mode === 'dev' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -13,16 +12,17 @@ export default defineConfig({ reporter: [['line']], globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', use: { baseURL, }, webServer: { - command: isDev ? `pnpm dev:e2e` : `pnpm build && PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: isDev + ? `pnpm dev:e2e --port 0` + : `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', env: { VITE_NODE_ENV: 'test', diff --git a/e2e/vue-start/css-modules/tests/setup/global.setup.ts b/e2e/vue-start/css-modules/tests/setup/global.setup.ts index 2d3a1db946..17be637f77 100644 --- a/e2e/vue-start/css-modules/tests/setup/global.setup.ts +++ b/e2e/vue-start/css-modules/tests/setup/global.setup.ts @@ -1,17 +1,9 @@ -import { - e2eStartDummyServer, - getTestServerPort, - preOptimizeDevServer, - waitForServer, -} from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } +import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' export default async function setup() { - await e2eStartDummyServer(packageJson.name) - if (process.env.MODE !== 'dev') return - const port = await getTestServerPort(packageJson.name) + const port = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${port}` await waitForServer(baseURL) diff --git a/e2e/vue-start/css-modules/tests/setup/global.teardown.ts b/e2e/vue-start/css-modules/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-start/css-modules/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/custom-basepath/express-server.ts b/e2e/vue-start/custom-basepath/express-server.ts index 1884c5eb5a..b9bf393466 100644 --- a/e2e/vue-start/custom-basepath/express-server.ts +++ b/e2e/vue-start/custom-basepath/express-server.ts @@ -1,5 +1,6 @@ import express from 'express' import { toNodeHandler } from 'srvx/node' +import type { AddressInfo } from 'node:net' import type { NodeHttp1Handler } from 'srvx' const DEVELOPMENT = process.env.NODE_ENV === 'development' @@ -40,7 +41,11 @@ if (DEVELOPMENT) { }) } -app.listen(PORT, (error) => { - if (error) throw error - console.log(`Server is running on http://localhost:${PORT}`) +const httpServer = app.listen(PORT, (error) => { + if (error) { + throw error + } + console.log( + `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, + ) }) diff --git a/e2e/vue-start/custom-basepath/package.json b/e2e/vue-start/custom-basepath/package.json index 3d0208de01..c1032ea88b 100644 --- a/e2e/vue-start/custom-basepath/package.json +++ b/e2e/vue-start/custom-basepath/package.json @@ -8,14 +8,14 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "tsx express-server.ts", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", "express": "^5.2.1", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "vue": "^3.5.25" }, "devDependencies": { @@ -25,10 +25,11 @@ "@types/express": "^5.0.6", "@types/node": "^22.10.2", "cross-env": "^10.0.0", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "tailwindcss": "^4.2.2", "tsx": "^4.20.3", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5" diff --git a/e2e/vue-start/custom-basepath/playwright.config.ts b/e2e/vue-start/custom-basepath/playwright.config.ts index 5095425f47..e113ce64ad 100644 --- a/e2e/vue-start/custom-basepath/playwright.config.ts +++ b/e2e/vue-start/custom-basepath/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}/custom/basepath` /** @@ -18,19 +13,19 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', + env: { + NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, + }, }, projects: [ diff --git a/e2e/vue-start/custom-basepath/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/custom-basepath/src/components/DefaultCatchBoundary.tsx index d06f4a948b..77c03c5afa 100644 --- a/e2e/vue-start/custom-basepath/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/custom-basepath/src/components/DefaultCatchBoundary.tsx @@ -1,3 +1,5 @@ +import { defineComponent } from 'vue' +import type { PropType } from 'vue' import { ErrorComponent, Link, @@ -6,46 +8,54 @@ import { } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - - console.error(error) - - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} +export const DefaultCatchBoundary = defineComponent({ + props: { + error: { + type: Object as PropType, + required: true, + }, + }, + setup(props) { + const router = useRouter() + const isRoot = useLocation({ + select: (location) => location.pathname === '/', + }) + return () => { + console.error(props.error) + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) + } + }, +}) diff --git a/e2e/vue-start/custom-basepath/src/routeTree.gen.ts b/e2e/vue-start/custom-basepath/src/routeTree.gen.ts index ea7e127d8e..605193fbec 100644 --- a/e2e/vue-start/custom-basepath/src/routeTree.gen.ts +++ b/e2e/vue-start/custom-basepath/src/routeTree.gen.ts @@ -9,34 +9,24 @@ // 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 UsersRouteImport } from './routes/users' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as LogoutRouteImport } from './routes/logout' -import { Route as DeferredRouteImport } from './routes/deferred' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as RedirectIndexRouteImport } from './routes/redirect.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as RedirectThrowItRouteImport } from './routes/redirect.throw-it' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as LogoutRouteImport } from './routes/logout' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as UsersRouteImport } from './routes/users' import { Route as ApiUsersRouteImport } from './routes/api/users' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as RedirectIndexRouteImport } from './routes/redirect.index' +import { Route as RedirectThrowItRouteImport } from './routes/redirect.throw-it' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const DeferredRoute = DeferredRouteImport.update({ @@ -44,19 +34,24 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LogoutRoute = LogoutRouteImport.update({ + id: '/logout', + path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, } as any) -const RedirectIndexRoute = RedirectIndexRouteImport.update({ - id: '/redirect/', - path: '/redirect/', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', + getParentRoute: () => rootRouteImport, +} as any) +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ @@ -64,36 +59,41 @@ const PostsIndexRoute = PostsIndexRouteImport.update({ path: '/', getParentRoute: () => PostsRoute, } as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const RedirectIndexRoute = RedirectIndexRouteImport.update({ + id: '/redirect/', + path: '/redirect/', + getParentRoute: () => rootRouteImport, } as any) const RedirectThrowItRoute = RedirectThrowItRouteImport.update({ id: '/redirect/throw-it', path: '/redirect/throw-it', getParentRoute: () => rootRouteImport, } as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', - getParentRoute: () => rootRouteImport, -} as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRoute, } as any) const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', getParentRoute: () => ApiUsersRoute, } as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -205,25 +205,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/deferred': { @@ -233,25 +219,32 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/logout': { + id: '/logout' + path: '/logout' + fullPath: '/logout' + preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport } - '/redirect/': { - id: '/redirect/' - path: '/redirect' - fullPath: '/redirect/' - preLoaderRoute: typeof RedirectIndexRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport + parentRoute: typeof rootRouteImport + } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } '/posts/': { @@ -261,12 +254,19 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsIndexRouteImport parentRoute: typeof PostsRoute } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/redirect/': { + id: '/redirect/' + path: '/redirect' + fullPath: '/redirect/' + preLoaderRoute: typeof RedirectIndexRouteImport + parentRoute: typeof rootRouteImport } '/redirect/throw-it': { id: '/redirect/throw-it' @@ -275,26 +275,19 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RedirectThrowItRouteImport parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport - parentRoute: typeof rootRouteImport - } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute } '/api/users/$userId': { id: '/api/users/$userId' @@ -303,6 +296,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ApiUsersUserIdRouteImport parentRoute: typeof ApiUsersRoute } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/e2e/vue-start/custom-basepath/src/routes/__root.tsx b/e2e/vue-start/custom-basepath/src/routes/__root.tsx index 8bc947b03a..c6d1eb197c 100644 --- a/e2e/vue-start/custom-basepath/src/routes/__root.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/__root.tsx @@ -49,7 +49,11 @@ export const Route = createRootRoute({ { rel: 'icon', href: '/favicon.ico' }, ], }), - errorComponent: (props) =>

{props.error.stack}

, + errorComponent: (props) => ( +

+ {props.error instanceof Error ? props.error.stack : String(props.error)} +

+ ), notFoundComponent: () => , component: RootComponent, }) diff --git a/e2e/vue-start/custom-basepath/src/routes/api/users.$userId.ts b/e2e/vue-start/custom-basepath/src/routes/api/users.$userId.ts index 50b9ca995a..7e3f528d68 100644 --- a/e2e/vue-start/custom-basepath/src/routes/api/users.$userId.ts +++ b/e2e/vue-start/custom-basepath/src/routes/api/users.$userId.ts @@ -1,11 +1,7 @@ import { createFileRoute } from '@tanstack/vue-router' import type { User } from '~/utils/users' -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const Route = createFileRoute('/api/users/$userId')({ server: { diff --git a/e2e/vue-start/custom-basepath/src/routes/api/users.ts b/e2e/vue-start/custom-basepath/src/routes/api/users.ts index 97989b93ca..dfdb5cd844 100644 --- a/e2e/vue-start/custom-basepath/src/routes/api/users.ts +++ b/e2e/vue-start/custom-basepath/src/routes/api/users.ts @@ -38,11 +38,7 @@ const testMiddleware = createMiddleware() return result }) -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const Route = createFileRoute('/api/users')({ server: { diff --git a/e2e/vue-start/custom-basepath/src/routes/posts.$postId.tsx b/e2e/vue-start/custom-basepath/src/routes/posts.$postId.tsx index b4e5a8a6a2..599e0f046e 100644 --- a/e2e/vue-start/custom-basepath/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/posts.$postId.tsx @@ -1,9 +1,32 @@ +import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '~/utils/posts' import { NotFound } from '~/components/NotFound' import { PostErrorComponent } from '~/components/PostErrorComponent' +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + return () => ( +
+

{post.value.title}

+
{post.value.body}
+ + Deep View + +
+ ) + }, +}) + export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost({ data: postId }), errorComponent: PostErrorComponent, @@ -12,24 +35,3 @@ export const Route = createFileRoute('/posts/$postId')({ return Post not found }, }) - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

{post.value.title}

-
{post.value.body}
- - Deep View - -
- ) -} diff --git a/e2e/vue-start/custom-basepath/src/routes/posts.tsx b/e2e/vue-start/custom-basepath/src/routes/posts.tsx index 1a9d58a31d..64d4754f2f 100644 --- a/e2e/vue-start/custom-basepath/src/routes/posts.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/posts.tsx @@ -1,7 +1,36 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '~/utils/posts' +const PostsComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + return () => ( +
+
    + {posts.value.map((post) => ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ))} +
+
+ +
+ ) + }, +}) + export const Route = createFileRoute('/posts')({ head: () => ({ meta: [ @@ -13,30 +42,3 @@ export const Route = createFileRoute('/posts')({ loader: async () => fetchPosts(), component: PostsComponent, }) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {posts.value.map((post) => ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ))} -
-
- -
- ) -} diff --git a/e2e/vue-start/custom-basepath/src/routes/posts_.$postId.deep.tsx b/e2e/vue-start/custom-basepath/src/routes/posts_.$postId.deep.tsx index a52c6f32f7..f77ae7d3ab 100644 --- a/e2e/vue-start/custom-basepath/src/routes/posts_.$postId.deep.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/posts_.$postId.deep.tsx @@ -1,24 +1,26 @@ +import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { PostErrorComponent } from '~/components/PostErrorComponent' import { fetchPost } from '~/utils/posts' +const PostDeepComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + return () => ( +
+ + ← All Posts + +

{post.value.title}

+
{post.value.body}
+
+ ) + }, +}) + export const Route = createFileRoute('/posts_/$postId/deep')({ loader: async ({ params: { postId } }) => fetchPost({ data: postId }), errorComponent: PostErrorComponent, component: PostDeepComponent, }) - -function PostDeepComponent() { - const post = Route.useLoaderData() - - return ( -
- - ← All Posts - -

{post.value.title}

-
{post.value.body}
-
- ) -} diff --git a/e2e/vue-start/custom-basepath/src/routes/users.$userId.tsx b/e2e/vue-start/custom-basepath/src/routes/users.$userId.tsx index fb7fce5f4c..4effec0d5b 100644 --- a/e2e/vue-start/custom-basepath/src/routes/users.$userId.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/users.$userId.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import axios from 'redaxios' @@ -6,6 +7,18 @@ import { NotFound } from '~/components/NotFound' import { UserErrorComponent } from '~/components/UserErrorComponent' import { basepath } from '~/utils/basepath' +const UserComponent = defineComponent({ + setup() { + const user = Route.useLoaderData() + return () => ( +
+

{user.value.name}

+
{user.value.email}
+
+ ) + }, +}) + export const Route = createFileRoute('/users/$userId')({ loader: async ({ params: { userId } }) => { return await axios @@ -21,14 +34,3 @@ export const Route = createFileRoute('/users/$userId')({ return User not found }, }) - -function UserComponent() { - const user = Route.useLoaderData() - - return ( -
-

{user.value.name}

-
{user.value.email}
-
- ) -} diff --git a/e2e/vue-start/custom-basepath/src/routes/users.tsx b/e2e/vue-start/custom-basepath/src/routes/users.tsx index 1432e50451..fe926d0a44 100644 --- a/e2e/vue-start/custom-basepath/src/routes/users.tsx +++ b/e2e/vue-start/custom-basepath/src/routes/users.tsx @@ -1,8 +1,40 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import axios from 'redaxios' import type { User } from '~/utils/users' import { basepath } from '~/utils/basepath' +const UsersComponent = defineComponent({ + setup() { + const users = Route.useLoaderData() + return () => ( +
+
    + {[ + ...users.value, + { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, + ].map((user) => ( +
  • + +
    {user.name}
    + +
  • + ))} +
+
+ +
+ ) + }, +}) + export const Route = createFileRoute('/users')({ loader: async () => { return await axios @@ -14,33 +46,3 @@ export const Route = createFileRoute('/users')({ }, component: UsersComponent, }) - -function UsersComponent() { - const users = Route.useLoaderData() - - return ( -
-
    - {[ - ...users.value, - { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, - ].map((user) => ( -
  • - -
    {user.name}
    - -
  • - ))} -
-
- -
- ) -} diff --git a/e2e/vue-start/custom-basepath/src/utils/posts.tsx b/e2e/vue-start/custom-basepath/src/utils/posts.tsx index 66cb298f83..11d80d08b5 100644 --- a/e2e/vue-start/custom-basepath/src/utils/posts.tsx +++ b/e2e/vue-start/custom-basepath/src/utils/posts.tsx @@ -8,11 +8,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = createServerFn({ method: 'GET' }) .validator((postId: string) => postId) diff --git a/e2e/vue-start/custom-basepath/src/utils/users.tsx b/e2e/vue-start/custom-basepath/src/utils/users.tsx index 46be4b1580..7ba645b383 100644 --- a/e2e/vue-start/custom-basepath/src/utils/users.tsx +++ b/e2e/vue-start/custom-basepath/src/utils/users.tsx @@ -3,7 +3,3 @@ export type User = { name: string email: string } - -const PORT = process.env.VITE_SERVER_PORT || 3000 - -export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/vue-start/custom-basepath/tests/setup/global.setup.ts b/e2e/vue-start/custom-basepath/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-start/custom-basepath/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/custom-basepath/tests/setup/global.teardown.ts b/e2e/vue-start/custom-basepath/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-start/custom-basepath/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/dev-ssr-styles/.gitignore b/e2e/vue-start/dev-ssr-styles/.gitignore new file mode 100644 index 0000000000..950326609c --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/.gitignore @@ -0,0 +1,7 @@ +node_modules +dist +.routeTree.gen.ts +src/routeTree.gen.ts +test-results +playwright-report +port*.txt diff --git a/e2e/vue-start/dev-ssr-styles/package.json b/e2e/vue-start/dev-ssr-styles/package.json new file mode 100644 index 0000000000..0033a0a5cc --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/package.json @@ -0,0 +1,32 @@ +{ + "name": "tanstack-vue-start-e2e-dev-ssr-styles", + "private": true, + "sideEffects": false, + "type": "module", + "scripts": { + "dev": "vite dev --port 3000", + "dev:e2e": "vite dev --port 0", + "build": "vite build && tsc --noEmit", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", + "test:e2e:dev": "MODE=dev playwright test --project=chromium", + "test:e2e": "pnpm run test:e2e:dev && pnpm run test:e2e:dev:bundled-dev", + "test:e2e:dev:bundled-dev": "MODE=dev E2E_VITE_BUNDLED_DEV=true playwright test --project=chromium" + }, + "dependencies": { + "@tanstack/vue-router": "workspace:*", + "@tanstack/vue-start": "workspace:*", + "vue": "^3.5.16" + }, + "devDependencies": { + "@playwright/test": "^1.61.0", + "@tanstack/router-core": "workspace:*", + "@tanstack/router-e2e-utils": "workspace:*", + "@types/node": "^22.10.2", + "@vitejs/plugin-vue": "^6.0.5", + "@vitejs/plugin-vue-jsx": "^5.1.5", + "srvx": "^1.0.0", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "@typescript/native": "npm:typescript@^7.0.2" + } +} diff --git a/e2e/vue-start/dev-ssr-styles/playwright.config.ts b/e2e/vue-start/dev-ssr-styles/playwright.config.ts new file mode 100644 index 0000000000..723cd32789 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/playwright.config.ts @@ -0,0 +1,28 @@ +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}` + +export default defineConfig({ + testDir: './tests', + workers: 1, + reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + use: { baseURL }, + webServer: { + command: 'pnpm dev:e2e', + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + env: { + VITE_NODE_ENV: 'test', + }, + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/vue-start/dev-ssr-styles/src/components/SfcStyledBox.vue b/e2e/vue-start/dev-ssr-styles/src/components/SfcStyledBox.vue new file mode 100644 index 0000000000..bd92215136 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/src/components/SfcStyledBox.vue @@ -0,0 +1,14 @@ + + + diff --git a/e2e/vue-start/dev-ssr-styles/src/router.tsx b/e2e/vue-start/dev-ssr-styles/src/router.tsx new file mode 100644 index 0000000000..c0d7f2b200 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/src/router.tsx @@ -0,0 +1,10 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + return createRouter({ + routeTree, + scrollRestoration: true, + defaultPreload: false, + }) +} diff --git a/e2e/vue-start/dev-ssr-styles/src/routes/__root.tsx b/e2e/vue-start/dev-ssr-styles/src/routes/__root.tsx new file mode 100644 index 0000000000..0dec479a07 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/src/routes/__root.tsx @@ -0,0 +1,27 @@ +import { + Body, + HeadContent, + Html, + Outlet, + Scripts, + createRootRoute, +} from '@tanstack/vue-router' +import '~/styles/app.css' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + ) +} diff --git a/e2e/vue-start/dev-ssr-styles/src/routes/index.tsx b/e2e/vue-start/dev-ssr-styles/src/routes/index.tsx new file mode 100644 index 0000000000..733bc1d559 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/src/routes/index.tsx @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/vue-router' +import SfcStyledBox from '../components/SfcStyledBox.vue' + +export const Route = createFileRoute('/')({ + component: Home, +}) + +function Home() { + return ( +
+

Vue Dev SSR Styles Test

+ +
+ ) +} diff --git a/e2e/vue-start/dev-ssr-styles/src/styles/app.css b/e2e/vue-start/dev-ssr-styles/src/styles/app.css new file mode 100644 index 0000000000..9a67f9b153 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/src/styles/app.css @@ -0,0 +1,5 @@ +body { + font-family: sans-serif; + margin: 0; + padding: 20px; +} diff --git a/e2e/vue-start/dev-ssr-styles/src/vue-shim.d.ts b/e2e/vue-start/dev-ssr-styles/src/vue-shim.d.ts new file mode 100644 index 0000000000..fe00a856b2 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/src/vue-shim.d.ts @@ -0,0 +1,6 @@ +declare module '*.vue' { + import type { DefineComponent } from 'vue' + + const component: DefineComponent + export default component +} diff --git a/e2e/vue-start/dev-ssr-styles/tests/app.spec.ts b/e2e/vue-start/dev-ssr-styles/tests/app.spec.ts new file mode 100644 index 0000000000..0e052441b7 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/tests/app.spec.ts @@ -0,0 +1,61 @@ +import { expect } from '@playwright/test' +import { DEV_STYLES_ATTR } from '@tanstack/router-core' +import { test } from '@tanstack/router-e2e-utils' + +const whitelistErrors = [ + 'Failed to load resource: net::ERR_NAME_NOT_RESOLVED', + 'Failed to load resource: the server responded with a status of 504', +] + +test.describe('dev SSR styles', () => { + test.use({ whitelistErrors }) + + test.describe('with JavaScript disabled', () => { + test.use({ javaScriptEnabled: false, whitelistErrors }) + + test('includes a Vue SFC style block during SSR', async ({ page }) => { + await page.goto('/') + + const element = page.getByTestId('styled-box') + await expect(element).toBeVisible() + await expect(element).toHaveCSS('background-color', 'rgb(126, 34, 206)') + + const href = await page + .locator(`link[${DEV_STYLES_ATTR}]`) + .getAttribute('href') + expect(href).toBeTruthy() + + const response = await page.request.get(new URL(href!, page.url()).href) + expect(response.ok()).toBeTruthy() + const css = await response.text() + expect(css).toContain('--vue-sfc-style-marker') + expect(css).toMatch( + /\/src\/components\/SfcStyledBox\.vue\?vue&type=style[^\n]*&lang\.css/, + ) + }) + }) + + test('keeps CSS output stable after client modules load', async ({ + page, + }) => { + const initialResponsePromise = page.waitForResponse((response) => + new URL(response.url()).pathname.endsWith('/@tanstack-start/styles.css'), + ) + await page.goto('/') + await expect(page.getByTestId('styled-box')).toBeVisible() + const initialResponse = await initialResponsePromise + expect(initialResponse.ok()).toBeTruthy() + const initialCss = await initialResponse.text() + + const reloadedResponsePromise = page.waitForResponse((response) => + new URL(response.url()).pathname.endsWith('/@tanstack-start/styles.css'), + ) + await page.reload() + await expect(page.getByTestId('styled-box')).toBeVisible() + const reloadedResponse = await reloadedResponsePromise + expect(reloadedResponse.ok()).toBeTruthy() + const reloadedCss = await reloadedResponse.text() + + expect(reloadedCss).toBe(initialCss) + }) +}) diff --git a/e2e/vue-start/dev-ssr-styles/tests/setup/global.setup.ts b/e2e/vue-start/dev-ssr-styles/tests/setup/global.setup.ts new file mode 100644 index 0000000000..b03b6485c8 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/tests/setup/global.setup.ts @@ -0,0 +1,15 @@ +import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' + +export default async function setup() { + if (process.env.MODE !== 'dev') { + return + } + + const port = Number(process.env.E2E_APP_PORT ?? 0) + const baseURL = `http://localhost:${port}` + await waitForServer(baseURL) + await preOptimizeDevServer({ + baseURL, + readyTestId: 'home-heading', + }) +} diff --git a/e2e/vue-start/dev-ssr-styles/tsconfig.json b/e2e/vue-start/dev-ssr-styles/tsconfig.json new file mode 100644 index 0000000000..898ea214b1 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/tsconfig.json @@ -0,0 +1,23 @@ +{ + "include": ["**/*.ts", "**/*.tsx", "**/*.vue"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "preserve", + "jsxImportSource": "vue", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "isolatedModules": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "target": "ES2022", + "allowJs": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "~/*": ["./src/*"] + }, + "noEmit": true, + "types": ["vite/client"] + } +} diff --git a/e2e/vue-start/dev-ssr-styles/vite.config.ts b/e2e/vue-start/dev-ssr-styles/vite.config.ts new file mode 100644 index 0000000000..f8b7293af9 --- /dev/null +++ b/e2e/vue-start/dev-ssr-styles/vite.config.ts @@ -0,0 +1,14 @@ +import { defineConfig } from 'vite' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vue from '@vitejs/plugin-vue' +import vueJsx from '@vitejs/plugin-vue-jsx' + +export default defineConfig({ + resolve: { tsconfigPaths: true }, + experimental: + process.env.E2E_VITE_BUNDLED_DEV === 'true' + ? { bundledDev: true } + : undefined, + server: { port: 3000 }, + plugins: [tanstackStart(), vue(), vueJsx()], +}) diff --git a/e2e/vue-start/query-integration/package.json b/e2e/vue-start/query-integration/package.json index 4cb22b48be..617ce4f430 100644 --- a/e2e/vue-start/query-integration/package.json +++ b/e2e/vue-start/query-integration/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-query": "^5.90.0", @@ -30,7 +30,8 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/e2e/vue-start/query-integration/playwright.config.ts b/e2e/vue-start/query-integration/playwright.config.ts index 4d86a1dbe7..82678ac00b 100644 --- a/e2e/vue-start/query-integration/playwright.config.ts +++ b/e2e/vue-start/query-integration/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { derivePort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await derivePort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-start/query-integration/src/routeTree.gen.ts b/e2e/vue-start/query-integration/src/routeTree.gen.ts index d4d30083a0..c5a9f02a7a 100644 --- a/e2e/vue-start/query-integration/src/routeTree.gen.ts +++ b/e2e/vue-start/query-integration/src/routeTree.gen.ts @@ -9,20 +9,20 @@ // 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 UseQueryRouteImport } from './routes/useQuery' import { Route as IndexRouteImport } from './routes/index' +import { Route as UseQueryRouteImport } from './routes/useQuery' import { Route as LoaderFetchQueryTypeRouteImport } from './routes/loader-fetchQuery/$type' -const UseQueryRoute = UseQueryRouteImport.update({ - id: '/useQuery', - path: '/useQuery', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const UseQueryRoute = UseQueryRouteImport.update({ + id: '/useQuery', + path: '/useQuery', + getParentRoute: () => rootRouteImport, +} as any) const LoaderFetchQueryTypeRoute = LoaderFetchQueryTypeRouteImport.update({ id: '/loader-fetchQuery/$type', path: '/loader-fetchQuery/$type', @@ -61,13 +61,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/useQuery': { - id: '/useQuery' - path: '/useQuery' - fullPath: '/useQuery' - preLoaderRoute: typeof UseQueryRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -75,6 +68,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/useQuery': { + id: '/useQuery' + path: '/useQuery' + fullPath: '/useQuery' + preLoaderRoute: typeof UseQueryRouteImport + parentRoute: typeof rootRouteImport + } '/loader-fetchQuery/$type': { id: '/loader-fetchQuery/$type' path: '/loader-fetchQuery/$type' diff --git a/e2e/vue-start/query-integration/src/routes/loader-fetchQuery/$type.tsx b/e2e/vue-start/query-integration/src/routes/loader-fetchQuery/$type.tsx index 9e928feafe..38f1e209dc 100644 --- a/e2e/vue-start/query-integration/src/routes/loader-fetchQuery/$type.tsx +++ b/e2e/vue-start/query-integration/src/routes/loader-fetchQuery/$type.tsx @@ -1,8 +1,29 @@ +import { defineComponent } from 'vue' import { useQuery } from '@tanstack/vue-query' import { createFileRoute } from '@tanstack/vue-router' import z from 'zod' import { makeQueryOptions } from '~/queryOptions' +const RouteComponent = defineComponent({ + setup() { + const loaderData = Route.useLoaderData() + const context = Route.useRouteContext() + const query = useQuery(() => context.value.queryOptions) + return () => ( +
+
+ loader data:{' '} +
{loaderData.value ?? 'undefined'}
+
+
+ query data:{' '} +
{query.data.value ?? 'loading...'}
+
+
+ ) + }, +}) + export const Route = createFileRoute('/loader-fetchQuery/$type')({ component: RouteComponent, params: { @@ -24,21 +45,3 @@ export const Route = createFileRoute('/loader-fetchQuery/$type')({ }, ssr: 'data-only', }) - -function RouteComponent() { - const loaderData = Route.useLoaderData() - const context = Route.useRouteContext() - const query = useQuery(context.value.queryOptions) - return ( -
-
- loader data:{' '} -
{loaderData.value ?? 'undefined'}
-
-
- query data:{' '} -
{query.data.value ?? 'loading...'}
-
-
- ) -} diff --git a/e2e/vue-start/scroll-restoration/package.json b/e2e/vue-start/scroll-restoration/package.json index cbc04f23ec..025b0225be 100644 --- a/e2e/vue-start/scroll-restoration/package.json +++ b/e2e/vue-start/scroll-restoration/package.json @@ -9,13 +9,13 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "vue": "^3.5.25", "zod": "^4.4.3" @@ -28,9 +28,10 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/e2e/vue-start/scroll-restoration/playwright.config.ts b/e2e/vue-start/scroll-restoration/playwright.config.ts index b0c365f8bd..1862174905 100644 --- a/e2e/vue-start/scroll-restoration/playwright.config.ts +++ b/e2e/vue-start/scroll-restoration/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -18,19 +13,19 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', + env: { + NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, + }, }, projects: [ diff --git a/e2e/vue-start/scroll-restoration/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/scroll-restoration/src/components/DefaultCatchBoundary.tsx index d06f4a948b..77c03c5afa 100644 --- a/e2e/vue-start/scroll-restoration/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/scroll-restoration/src/components/DefaultCatchBoundary.tsx @@ -1,3 +1,5 @@ +import { defineComponent } from 'vue' +import type { PropType } from 'vue' import { ErrorComponent, Link, @@ -6,46 +8,54 @@ import { } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - - console.error(error) - - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} +export const DefaultCatchBoundary = defineComponent({ + props: { + error: { + type: Object as PropType, + required: true, + }, + }, + setup(props) { + const router = useRouter() + const isRoot = useLocation({ + select: (location) => location.pathname === '/', + }) + return () => { + console.error(props.error) + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) + } + }, +}) diff --git a/e2e/vue-start/scroll-restoration/src/routeTree.gen.ts b/e2e/vue-start/scroll-restoration/src/routeTree.gen.ts index 86dc966e78..49b34fc68f 100644 --- a/e2e/vue-start/scroll-restoration/src/routeTree.gen.ts +++ b/e2e/vue-start/scroll-restoration/src/routeTree.gen.ts @@ -10,18 +10,18 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as testsWithSearchRouteImport } from './routes/(tests)/with-search' -import { Route as testsWithLoaderRouteImport } from './routes/(tests)/with-loader' import { Route as testsNormalPageRouteImport } from './routes/(tests)/normal-page' +import { Route as testsWithLoaderRouteImport } from './routes/(tests)/with-loader' +import { Route as testsWithSearchRouteImport } from './routes/(tests)/with-search' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const testsWithSearchRoute = testsWithSearchRouteImport.update({ - id: '/(tests)/with-search', - path: '/with-search', +const testsNormalPageRoute = testsNormalPageRouteImport.update({ + id: '/(tests)/normal-page', + path: '/normal-page', getParentRoute: () => rootRouteImport, } as any) const testsWithLoaderRoute = testsWithLoaderRouteImport.update({ @@ -29,9 +29,9 @@ const testsWithLoaderRoute = testsWithLoaderRouteImport.update({ path: '/with-loader', getParentRoute: () => rootRouteImport, } as any) -const testsNormalPageRoute = testsNormalPageRouteImport.update({ - id: '/(tests)/normal-page', - path: '/normal-page', +const testsWithSearchRoute = testsWithSearchRouteImport.update({ + id: '/(tests)/with-search', + path: '/with-search', getParentRoute: () => rootRouteImport, } as any) @@ -83,11 +83,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/(tests)/with-search': { - id: '/(tests)/with-search' - path: '/with-search' - fullPath: '/with-search' - preLoaderRoute: typeof testsWithSearchRouteImport + '/(tests)/normal-page': { + id: '/(tests)/normal-page' + path: '/normal-page' + fullPath: '/normal-page' + preLoaderRoute: typeof testsNormalPageRouteImport parentRoute: typeof rootRouteImport } '/(tests)/with-loader': { @@ -97,11 +97,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof testsWithLoaderRouteImport parentRoute: typeof rootRouteImport } - '/(tests)/normal-page': { - id: '/(tests)/normal-page' - path: '/normal-page' - fullPath: '/normal-page' - preLoaderRoute: typeof testsNormalPageRouteImport + '/(tests)/with-search': { + id: '/(tests)/with-search' + path: '/with-search' + fullPath: '/with-search' + preLoaderRoute: typeof testsWithSearchRouteImport parentRoute: typeof rootRouteImport } } diff --git a/e2e/vue-start/scroll-restoration/src/routes/__root.tsx b/e2e/vue-start/scroll-restoration/src/routes/__root.tsx index a28ab59f79..cd8a558359 100644 --- a/e2e/vue-start/scroll-restoration/src/routes/__root.tsx +++ b/e2e/vue-start/scroll-restoration/src/routes/__root.tsx @@ -53,7 +53,11 @@ export const Route = createRootRoute({ ], }), errorComponent: (props) => { - return

{props.error.stack}

+ return ( +

+ {props.error instanceof Error ? props.error.stack : String(props.error)} +

+ ) }, notFoundComponent: () => , component: RootComponent, diff --git a/e2e/vue-start/scroll-restoration/src/utils/posts.tsx b/e2e/vue-start/scroll-restoration/src/utils/posts.tsx index e45ef52969..c4a2d0dcca 100644 --- a/e2e/vue-start/scroll-restoration/src/utils/posts.tsx +++ b/e2e/vue-start/scroll-restoration/src/utils/posts.tsx @@ -10,11 +10,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export class PostNotFoundError extends Error {} diff --git a/e2e/vue-start/scroll-restoration/src/utils/users.tsx b/e2e/vue-start/scroll-restoration/src/utils/users.tsx index 46be4b1580..7ba645b383 100644 --- a/e2e/vue-start/scroll-restoration/src/utils/users.tsx +++ b/e2e/vue-start/scroll-restoration/src/utils/users.tsx @@ -3,7 +3,3 @@ export type User = { name: string email: string } - -const PORT = process.env.VITE_SERVER_PORT || 3000 - -export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/vue-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts b/e2e/vue-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts new file mode 100644 index 0000000000..df75cba73c --- /dev/null +++ b/e2e/vue-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts @@ -0,0 +1,4 @@ +import { test } from '@tanstack/router-e2e-utils' +import { scrollRestorationLifecycleTests } from '../../../scroll-restoration-lifecycle' + +scrollRestorationLifecycleTests(test) diff --git a/e2e/vue-start/scroll-restoration/tests/setup/global.setup.ts b/e2e/vue-start/scroll-restoration/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-start/scroll-restoration/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/scroll-restoration/tests/setup/global.teardown.ts b/e2e/vue-start/scroll-restoration/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-start/scroll-restoration/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/selective-ssr/package.json b/e2e/vue-start/selective-ssr/package.json index 95c82b2511..b555a01c26 100644 --- a/e2e/vue-start/selective-ssr/package.json +++ b/e2e/vue-start/selective-ssr/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -22,10 +22,11 @@ "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", - "vue-tsc": "^3.1.8" + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-start/selective-ssr/playwright.config.ts b/e2e/vue-start/selective-ssr/playwright.config.ts index badd6db0eb..630989e41f 100644 --- a/e2e/vue-start/selective-ssr/playwright.config.ts +++ b/e2e/vue-start/selective-ssr/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-start/selective-ssr/src/routeTree.gen.ts b/e2e/vue-start/selective-ssr/src/routeTree.gen.ts index 474705b7e7..0d44b648ee 100644 --- a/e2e/vue-start/selective-ssr/src/routeTree.gen.ts +++ b/e2e/vue-start/selective-ssr/src/routeTree.gen.ts @@ -9,20 +9,20 @@ // 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 PostsRouteImport } from './routes/posts' import { Route as IndexRouteImport } from './routes/index' +import { Route as PostsRouteImport } from './routes/posts' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) const PostsPostIdRoute = PostsPostIdRouteImport.update({ id: '/$postId', path: '/$postId', @@ -60,13 +60,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -74,6 +67,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } '/posts/$postId': { id: '/posts/$postId' path: '/$postId' diff --git a/e2e/vue-start/selective-ssr/src/routes/__root.tsx b/e2e/vue-start/selective-ssr/src/routes/__root.tsx index a952abd4e0..9319a0982a 100644 --- a/e2e/vue-start/selective-ssr/src/routes/__root.tsx +++ b/e2e/vue-start/selective-ssr/src/routes/__root.tsx @@ -1,4 +1,5 @@ /// +import { defineComponent } from 'vue' import { Body, ClientOnly, @@ -14,6 +15,93 @@ import { z } from 'zod' import { ssrSchema } from '~/search' import appCss from '~/styles/app.css?url' +const RootDocument = defineComponent({ + setup(_, { slots }) { + const routerState = useRouterState({ + select: (state) => ({ + isLoading: state.isLoading, + status: state.status, + }), + }) + return () => ( + + + + + +
+

Selective SSR E2E Test

+ + Home + +
+
+ +
+ router isLoading:{' '} + + {routerState.value.isLoading ? 'true' : 'false'} + +
+
+ router status:{' '} + {routerState.value.status} +
+
+
+ {slots.default?.()} + + + + ) + }, +}) + +const RouteComponent = defineComponent({ + setup() { + const search = Route.useSearch() + const loaderData = Route.useLoaderData() + const context = Route.useRouteContext() + return () => { + if ( + typeof window === 'undefined' && + search.value.root?.expected?.render === 'client-only' + ) { + const error = `Expected component for ${Route.id} to be executed on the client, but it is running on the server` + console.error(error) + throw new Error(error) + } + return ( +
+

root

+
+ ssr: {JSON.stringify(search.value.root?.ssr ?? 'undefined')} +
+
+ expected data location execution:{' '} + + {search.value.root?.expected?.data} + +
+
+ loader: {loaderData.value.root} +
+
+ context: {context.value.root} +
+
+ +
+ ) + } + }, +}) + export const Route = createRootRoute({ head: () => ({ meta: [ @@ -74,84 +162,5 @@ export const Route = createRootRoute({ return { root: typeof window === 'undefined' ? 'server' : 'client' } }, shellComponent: RootDocument, - component: () => { - const search = Route.useSearch() - if ( - typeof window === 'undefined' && - search.value.root?.expected?.render === 'client-only' - ) { - const error = `Expected component for ${Route.id} to be executed on the client, but it is running on the server` - console.error(error) - throw new Error(error) - } - const loaderData = Route.useLoaderData() - const context = Route.useRouteContext() - return ( -
-

root

-
- ssr: {JSON.stringify(search.value.root?.ssr ?? 'undefined')} -
-
- expected data location execution:{' '} - - {search.value.root?.expected?.data} - -
-
- loader: {loaderData.value.root} -
-
- context: {context.value.root} -
-
- -
- ) - }, + component: RouteComponent, }) - -function RootDocument(_: unknown, { slots }: { slots: any }) { - const routerState = useRouterState({ - select: (state) => ({ - isLoading: state.isLoading, - status: state.status, - }), - }) - return ( - - - - - -
-

Selective SSR E2E Test

- - Home - -
-
- -
- router isLoading:{' '} - - {routerState.value.isLoading ? 'true' : 'false'} - -
-
- router status:{' '} - {routerState.value.status} -
-
-
- {slots.default?.()} - - - - ) -} diff --git a/e2e/vue-start/selective-ssr/src/routes/posts.$postId.tsx b/e2e/vue-start/selective-ssr/src/routes/posts.$postId.tsx index 4e7065cc48..522b5e9b8e 100644 --- a/e2e/vue-start/selective-ssr/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/selective-ssr/src/routes/posts.$postId.tsx @@ -1,7 +1,47 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import z from 'zod' import { ssrSchema } from '~/search' +const RouteComponent = defineComponent({ + setup() { + const search = Route.useSearch() + const loaderData = Route.useLoaderData() + const context = Route.useRouteContext() + return () => { + if ( + typeof window === 'undefined' && + search.value.postId?.expected?.render === 'client-only' + ) { + const error = `Expected component for ${Route.id} to be executed on the client, but it is running on the server` + console.error(error) + throw new Error(error) + } + return ( +
+

postId

+
+ ssr:{' '} + {JSON.stringify(search.value.postId?.ssr ?? 'undefined')} +
+
+ expected data location execution:{' '} + + {search.value.postId?.expected?.data} + +
+
+ loader: {loaderData.value.postId} +
+
+ context: {context.value.postId} +
+
+ ) + } + }, +}) + export const Route = createFileRoute('/posts/$postId')({ validateSearch: z.object({ postId: ssrSchema }), ssr: ({ search }) => { @@ -46,37 +86,5 @@ export const Route = createFileRoute('/posts/$postId')({ } return { postId: typeof window === 'undefined' ? 'server' : 'client' } }, - component: () => { - const search = Route.useSearch() - const loaderData = Route.useLoaderData() - const context = Route.useRouteContext() - if ( - typeof window === 'undefined' && - search.value.postId?.expected?.render === 'client-only' - ) { - const error = `Expected component for ${Route.id} to be executed on the client, but it is running on the server` - console.error(error) - throw new Error(error) - } - return ( -
-

postId

-
- ssr: {JSON.stringify(search.value.postId?.ssr ?? 'undefined')} -
-
- expected data location execution:{' '} - - {search.value.postId?.expected?.data} - -
-
- loader: {loaderData.value.postId} -
-
- context: {context.value.postId} -
-
- ) - }, + component: RouteComponent, }) diff --git a/e2e/vue-start/selective-ssr/src/routes/posts.tsx b/e2e/vue-start/selective-ssr/src/routes/posts.tsx index 6c4e490dde..514628b229 100644 --- a/e2e/vue-start/selective-ssr/src/routes/posts.tsx +++ b/e2e/vue-start/selective-ssr/src/routes/posts.tsx @@ -1,7 +1,48 @@ +import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import z from 'zod' import { ssrSchema } from '~/search' +const RouteComponent = defineComponent({ + setup() { + const search = Route.useSearch() + const loaderData = Route.useLoaderData() + const context = Route.useRouteContext() + return () => { + if ( + typeof window === 'undefined' && + search.value.posts?.expected?.render === 'client-only' + ) { + const error = `Expected component for ${Route.id} to be executed on the client, but it is running on the server` + console.error(error) + throw new Error(error) + } + return ( +
+

posts

+
+ ssr: {JSON.stringify(search.value.posts?.ssr ?? 'undefined')} +
+
+ expected data location execution:{' '} + + {search.value.posts?.expected?.data} + +
+
+ loader: {loaderData.value.posts} +
+
+ context: {context.value.posts} +
+
+ +
+ ) + } + }, +}) + export const Route = createFileRoute('/posts')({ validateSearch: z.object({ posts: ssrSchema }), ssr: ({ search }) => { @@ -46,39 +87,5 @@ export const Route = createFileRoute('/posts')({ } return { posts: typeof window === 'undefined' ? 'server' : 'client' } }, - component: () => { - const search = Route.useSearch() - const loaderData = Route.useLoaderData() - const context = Route.useRouteContext() - if ( - typeof window === 'undefined' && - search.value.posts?.expected?.render === 'client-only' - ) { - const error = `Expected component for ${Route.id} to be executed on the client, but it is running on the server` - console.error(error) - throw new Error(error) - } - return ( -
-

posts

-
- ssr: {JSON.stringify(search.value.posts?.ssr ?? 'undefined')} -
-
- expected data location execution:{' '} - - {search.value.posts?.expected?.data} - -
-
- loader: {loaderData.value.posts} -
-
- context: {context.value.posts} -
-
- -
- ) - }, + component: RouteComponent, }) diff --git a/e2e/vue-start/serialization-adapters/package.json b/e2e/vue-start/serialization-adapters/package.json index d854c0bb7c..a056e21da3 100644 --- a/e2e/vue-start/serialization-adapters/package.json +++ b/e2e/vue-start/serialization-adapters/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -23,10 +23,11 @@ "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", - "vue-tsc": "^3.1.8" + "vue-tsc": "^3.3.8" } } diff --git a/e2e/vue-start/serialization-adapters/playwright.config.ts b/e2e/vue-start/serialization-adapters/playwright.config.ts index badd6db0eb..630989e41f 100644 --- a/e2e/vue-start/serialization-adapters/playwright.config.ts +++ b/e2e/vue-start/serialization-adapters/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-start/serialization-adapters/src/routeTree.gen.ts b/e2e/vue-start/serialization-adapters/src/routeTree.gen.ts index 79b17ac82b..c684bbc82c 100644 --- a/e2e/vue-start/serialization-adapters/src/routeTree.gen.ts +++ b/e2e/vue-start/serialization-adapters/src/routeTree.gen.ts @@ -10,43 +10,43 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as SsrStreamRouteImport } from './routes/ssr/stream' -import { Route as SsrNestedRouteImport } from './routes/ssr/nested' -import { Route as SsrDataOnlyRouteImport } from './routes/ssr/data-only' -import { Route as ServerFunctionNestedRouteImport } from './routes/server-function/nested' import { Route as ServerFunctionCustomErrorRouteImport } from './routes/server-function/custom-error' +import { Route as ServerFunctionNestedRouteImport } from './routes/server-function/nested' +import { Route as SsrDataOnlyRouteImport } from './routes/ssr/data-only' +import { Route as SsrNestedRouteImport } from './routes/ssr/nested' +import { Route as SsrStreamRouteImport } from './routes/ssr/stream' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const SsrStreamRoute = SsrStreamRouteImport.update({ - id: '/ssr/stream', - path: '/ssr/stream', - getParentRoute: () => rootRouteImport, -} as any) -const SsrNestedRoute = SsrNestedRouteImport.update({ - id: '/ssr/nested', - path: '/ssr/nested', - getParentRoute: () => rootRouteImport, -} as any) -const SsrDataOnlyRoute = SsrDataOnlyRouteImport.update({ - id: '/ssr/data-only', - path: '/ssr/data-only', - getParentRoute: () => rootRouteImport, -} as any) -const ServerFunctionNestedRoute = ServerFunctionNestedRouteImport.update({ - id: '/server-function/nested', - path: '/server-function/nested', - getParentRoute: () => rootRouteImport, -} as any) const ServerFunctionCustomErrorRoute = ServerFunctionCustomErrorRouteImport.update({ id: '/server-function/custom-error', path: '/server-function/custom-error', getParentRoute: () => rootRouteImport, } as any) +const ServerFunctionNestedRoute = ServerFunctionNestedRouteImport.update({ + id: '/server-function/nested', + path: '/server-function/nested', + getParentRoute: () => rootRouteImport, +} as any) +const SsrDataOnlyRoute = SsrDataOnlyRouteImport.update({ + id: '/ssr/data-only', + path: '/ssr/data-only', + getParentRoute: () => rootRouteImport, +} as any) +const SsrNestedRoute = SsrNestedRouteImport.update({ + id: '/ssr/nested', + path: '/ssr/nested', + getParentRoute: () => rootRouteImport, +} as any) +const SsrStreamRoute = SsrStreamRouteImport.update({ + id: '/ssr/stream', + path: '/ssr/stream', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -118,25 +118,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/ssr/stream': { - id: '/ssr/stream' - path: '/ssr/stream' - fullPath: '/ssr/stream' - preLoaderRoute: typeof SsrStreamRouteImport - parentRoute: typeof rootRouteImport - } - '/ssr/nested': { - id: '/ssr/nested' - path: '/ssr/nested' - fullPath: '/ssr/nested' - preLoaderRoute: typeof SsrNestedRouteImport - parentRoute: typeof rootRouteImport - } - '/ssr/data-only': { - id: '/ssr/data-only' - path: '/ssr/data-only' - fullPath: '/ssr/data-only' - preLoaderRoute: typeof SsrDataOnlyRouteImport + '/server-function/custom-error': { + id: '/server-function/custom-error' + path: '/server-function/custom-error' + fullPath: '/server-function/custom-error' + preLoaderRoute: typeof ServerFunctionCustomErrorRouteImport parentRoute: typeof rootRouteImport } '/server-function/nested': { @@ -146,11 +132,25 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ServerFunctionNestedRouteImport parentRoute: typeof rootRouteImport } - '/server-function/custom-error': { - id: '/server-function/custom-error' - path: '/server-function/custom-error' - fullPath: '/server-function/custom-error' - preLoaderRoute: typeof ServerFunctionCustomErrorRouteImport + '/ssr/data-only': { + id: '/ssr/data-only' + path: '/ssr/data-only' + fullPath: '/ssr/data-only' + preLoaderRoute: typeof SsrDataOnlyRouteImport + parentRoute: typeof rootRouteImport + } + '/ssr/nested': { + id: '/ssr/nested' + path: '/ssr/nested' + fullPath: '/ssr/nested' + preLoaderRoute: typeof SsrNestedRouteImport + parentRoute: typeof rootRouteImport + } + '/ssr/stream': { + id: '/ssr/stream' + path: '/ssr/stream' + fullPath: '/ssr/stream' + preLoaderRoute: typeof SsrStreamRouteImport parentRoute: typeof rootRouteImport } } diff --git a/e2e/vue-start/serialization-adapters/src/routes/__root.tsx b/e2e/vue-start/serialization-adapters/src/routes/__root.tsx index 96911d2500..3ea36c7d46 100644 --- a/e2e/vue-start/serialization-adapters/src/routes/__root.tsx +++ b/e2e/vue-start/serialization-adapters/src/routes/__root.tsx @@ -1,4 +1,5 @@ /// +import { defineComponent } from 'vue' import { Body, ClientOnly, @@ -12,6 +13,51 @@ import { import { TanStackRouterDevtoolsInProd } from '@tanstack/vue-router-devtools' import appCss from '~/styles/app.css?url' +const RootDocument = defineComponent({ + setup(_, { slots }) { + const routerState = useRouterState({ + select: (state) => ({ isLoading: state.isLoading, status: state.status }), + }) + return () => ( + + + + + +
+

Serialization Adapters E2E Test

+ + Home + +
+
+ +
+ router isLoading:{' '} + + {routerState.value.isLoading ? 'true' : 'false'} + +
+
+ router status:{' '} + {routerState.value.status} +
+
+
+ {slots.default?.()} + + + + + ) + }, +}) + export const Route = createRootRoute({ head: () => ({ meta: [ @@ -31,46 +77,3 @@ export const Route = createRootRoute({ shellComponent: RootDocument, notFoundComponent: (e) =>
404 - Not Found {JSON.stringify(e.data)}
, }) - -function RootDocument(_: unknown, { slots }: { slots: any }) { - const routerState = useRouterState({ - select: (state) => ({ isLoading: state.isLoading, status: state.status }), - }) - return ( - - - - - -
-

Serialization Adapters E2E Test

- - Home - -
-
- -
- router isLoading:{' '} - - {routerState.value.isLoading ? 'true' : 'false'} - -
-
- router status:{' '} - {routerState.value.status} -
-
-
- {slots.default?.()} - - - - - ) -} diff --git a/e2e/vue-start/serialization-adapters/src/routes/index.tsx b/e2e/vue-start/serialization-adapters/src/routes/index.tsx index 2d90e4b073..d6bacefdc0 100644 --- a/e2e/vue-start/serialization-adapters/src/routes/index.tsx +++ b/e2e/vue-start/serialization-adapters/src/routes/index.tsx @@ -2,7 +2,9 @@ import { Link, createFileRoute } from '@tanstack/vue-router' export const Route = createFileRoute('/')({ component: Home, - errorComponent: (e) =>
{e.error.message}
, + errorComponent: (e) => ( +
{e.error instanceof Error ? e.error.message : String(e.error)}
+ ), }) function Home() { diff --git a/e2e/vue-start/serialization-adapters/src/routes/ssr/data-only.tsx b/e2e/vue-start/serialization-adapters/src/routes/ssr/data-only.tsx index ecb35d0a55..e71906f03e 100644 --- a/e2e/vue-start/serialization-adapters/src/routes/ssr/data-only.tsx +++ b/e2e/vue-start/serialization-adapters/src/routes/ssr/data-only.tsx @@ -1,6 +1,47 @@ +import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' import { RenderData, makeData } from '~/data' +const RouteComponent = defineComponent({ + setup() { + const context = Route.useRouteContext() + const loaderData = Route.useLoaderData() + return () => { + const localData = makeData() + const expectedHonkState = localData.car.singleInstance.honk() + const honkState = loaderData.value.car.singleInstance.honk() + return ( +
+

data-only

+
+ context: +
+
+ loader: +
+
+

honk

+
+ expected:{' '} +
+ {JSON.stringify(expectedHonkState)} +
+
+
+ actual:{' '} +
+ {JSON.stringify(honkState)} +
+
+
+
+ +
+ ) + } + }, +}) + export const Route = createFileRoute('/ssr/data-only')({ ssr: 'data-only', beforeLoad: () => { @@ -9,43 +50,6 @@ export const Route = createFileRoute('/ssr/data-only')({ loader: ({ context }) => { return context }, - component: () => { - const context = Route.useRouteContext() - const loaderData = Route.useLoaderData() - - const localData = makeData() - const expectedHonkState = localData.car.singleInstance.honk() - - const honkState = loaderData.value.car.singleInstance.honk() - - return ( -
-

data-only

-
- context: -
-
- loader: -
-
-

honk

-
- expected:{' '} -
- {JSON.stringify(expectedHonkState)} -
-
-
- actual:{' '} -
- {JSON.stringify(honkState)} -
-
-
-
- -
- ) - }, + component: RouteComponent, pendingComponent: () =>
posts Loading...
, }) diff --git a/e2e/vue-start/serialization-adapters/src/routes/ssr/nested.tsx b/e2e/vue-start/serialization-adapters/src/routes/ssr/nested.tsx index bbc240b96d..b4f7fd8f23 100644 --- a/e2e/vue-start/serialization-adapters/src/routes/ssr/nested.tsx +++ b/e2e/vue-start/serialization-adapters/src/routes/ssr/nested.tsx @@ -1,6 +1,14 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { RenderNestedData, makeNested } from '~/data' +const RouteComponent = defineComponent({ + setup() { + const loaderData = Route.useLoaderData() + return () => + }, +}) + export const Route = createFileRoute('/ssr/nested')({ beforeLoad: () => { return { nested: makeNested() } @@ -8,8 +16,5 @@ export const Route = createFileRoute('/ssr/nested')({ loader: ({ context }) => { return context }, - component: () => { - const loaderData = Route.useLoaderData() - return - }, + component: RouteComponent, }) diff --git a/e2e/vue-start/serialization-adapters/src/routes/ssr/stream.tsx b/e2e/vue-start/serialization-adapters/src/routes/ssr/stream.tsx index 4fce3271f8..f6056699af 100644 --- a/e2e/vue-start/serialization-adapters/src/routes/ssr/stream.tsx +++ b/e2e/vue-start/serialization-adapters/src/routes/ssr/stream.tsx @@ -1,7 +1,32 @@ import { Await, createFileRoute } from '@tanstack/vue-router' -import { Suspense } from 'vue' +import { defineComponent, Suspense } from 'vue' import { RenderData, makeData } from '~/data' +const RouteComponent = defineComponent({ + setup() { + const loaderData = Route.useLoaderData() + return () => ( +
+

Stream

+
{loaderData.value.someString}
+ + {{ + default: () => ( + ) => ( + + )} + /> + ), + fallback: () =>
Loading...
, + }} +
+
+ ) + }, +}) + export const Route = createFileRoute('/ssr/stream')({ loader: () => { const dataPromise = new Promise>((r) => @@ -13,29 +38,8 @@ export const Route = createFileRoute('/ssr/stream')({ } }, - errorComponent: (e) =>
{e.error.message}
, + errorComponent: (e) => ( +
{e.error instanceof Error ? e.error.message : String(e.error)}
+ ), component: RouteComponent, }) - -function RouteComponent() { - const loaderData = Route.useLoaderData() - return ( -
-

Stream

-
{loaderData.value.someString}
- - {{ - default: () => ( - ) => ( - - )} - /> - ), - fallback: () =>
Loading...
, - }} -
-
- ) -} diff --git a/e2e/vue-start/server-functions/package.json b/e2e/vue-start/server-functions/package.json index 5752c48b73..dd1a7a9c6b 100644 --- a/e2e/vue-start/server-functions/package.json +++ b/e2e/vue-start/server-functions/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-query": "^5.90.9", @@ -18,7 +18,7 @@ "@tanstack/vue-router-ssr-query": "workspace:^", "@tanstack/vue-start": "workspace:^", "js-cookie": "^3.0.5", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "vue": "^3.5.25", "zod": "^4.4.3" @@ -32,9 +32,10 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/e2e/vue-start/server-functions/playwright.config.ts b/e2e/vue-start/server-functions/playwright.config.ts index cb1da03b94..48e14683f4 100644 --- a/e2e/vue-start/server-functions/playwright.config.ts +++ b/e2e/vue-start/server-functions/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -export const PORT = await getTestServerPort(packageJson.name) +export const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,8 +20,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-start/server-functions/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/server-functions/src/components/DefaultCatchBoundary.tsx index d06f4a948b..77c03c5afa 100644 --- a/e2e/vue-start/server-functions/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/server-functions/src/components/DefaultCatchBoundary.tsx @@ -1,3 +1,5 @@ +import { defineComponent } from 'vue' +import type { PropType } from 'vue' import { ErrorComponent, Link, @@ -6,46 +8,54 @@ import { } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - - console.error(error) - - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} +export const DefaultCatchBoundary = defineComponent({ + props: { + error: { + type: Object as PropType, + required: true, + }, + }, + setup(props) { + const router = useRouter() + const isRoot = useLocation({ + select: (location) => location.pathname === '/', + }) + return () => { + console.error(props.error) + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) + } + }, +}) diff --git a/e2e/vue-start/server-functions/src/routeTree.gen.ts b/e2e/vue-start/server-functions/src/routeTree.gen.ts index 43a6eb4ae6..96e5b7ba29 100644 --- a/e2e/vue-start/server-functions/src/routeTree.gen.ts +++ b/e2e/vue-start/server-functions/src/routeTree.gen.ts @@ -9,89 +9,39 @@ // 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 SubmitPostFormdataRouteImport } from './routes/submit-post-formdata' -import { Route as StatusRouteImport } from './routes/status' -import { Route as SerializeFormDataRouteImport } from './routes/serialize-form-data' -import { Route as ReturnNullRouteImport } from './routes/return-null' -import { Route as RawResponseRouteImport } from './routes/raw-response' -import { Route as MultipartRouteImport } from './routes/multipart' -import { Route as IsomorphicFnsRouteImport } from './routes/isomorphic-fns' -import { Route as HeadersRouteImport } from './routes/headers' -import { Route as EnvOnlyRouteImport } from './routes/env-only' -import { Route as DeadCodePreserveRouteImport } from './routes/dead-code-preserve' -import { Route as ConsistentRouteImport } from './routes/consistent' -import { Route as AbortSignalRouteImport } from './routes/abort-signal' import { Route as IndexRouteImport } from './routes/index' -import { Route as RedirectTestIndexRouteImport } from './routes/redirect-test/index' -import { Route as RedirectTestSsrIndexRouteImport } from './routes/redirect-test-ssr/index' -import { Route as PrimitivesIndexRouteImport } from './routes/primitives/index' -import { Route as MiddlewareIndexRouteImport } from './routes/middleware/index' -import { Route as FunctionMethodIndexRouteImport } from './routes/function-method/index' -import { Route as FunctionMetadataIndexRouteImport } from './routes/function-metadata/index' -import { Route as FormdataRedirectIndexRouteImport } from './routes/formdata-redirect/index' -import { Route as FactoryIndexRouteImport } from './routes/factory/index' +import { Route as AbortSignalRouteImport } from './routes/abort-signal' +import { Route as ConsistentRouteImport } from './routes/consistent' +import { Route as DeadCodePreserveRouteImport } from './routes/dead-code-preserve' +import { Route as EnvOnlyRouteImport } from './routes/env-only' +import { Route as HeadersRouteImport } from './routes/headers' +import { Route as IsomorphicFnsRouteImport } from './routes/isomorphic-fns' +import { Route as MultipartRouteImport } from './routes/multipart' +import { Route as RawResponseRouteImport } from './routes/raw-response' +import { Route as ReturnNullRouteImport } from './routes/return-null' +import { Route as SerializeFormDataRouteImport } from './routes/serialize-form-data' +import { Route as StatusRouteImport } from './routes/status' +import { Route as SubmitPostFormdataRouteImport } from './routes/submit-post-formdata' import { Route as CookiesIndexRouteImport } from './routes/cookies/index' -import { Route as RedirectTestTargetRouteImport } from './routes/redirect-test/target' -import { Route as RedirectTestSsrTargetRouteImport } from './routes/redirect-test-ssr/target' -import { Route as MiddlewareSendServerFnRouteImport } from './routes/middleware/send-serverFn' -import { Route as MiddlewareRequestMiddlewareRouteImport } from './routes/middleware/request-middleware' -import { Route as MiddlewareClientMiddlewareRouterRouteImport } from './routes/middleware/client-middleware-router' import { Route as CookiesSetRouteImport } from './routes/cookies/set' +import { Route as FactoryIndexRouteImport } from './routes/factory/index' +import { Route as FormdataRedirectIndexRouteImport } from './routes/formdata-redirect/index' +import { Route as FunctionMetadataIndexRouteImport } from './routes/function-metadata/index' +import { Route as FunctionMethodIndexRouteImport } from './routes/function-method/index' +import { Route as MiddlewareIndexRouteImport } from './routes/middleware/index' +import { Route as MiddlewareClientMiddlewareRouterRouteImport } from './routes/middleware/client-middleware-router' +import { Route as MiddlewareRequestMiddlewareRouteImport } from './routes/middleware/request-middleware' +import { Route as MiddlewareSendServerFnRouteImport } from './routes/middleware/send-serverFn' +import { Route as PrimitivesIndexRouteImport } from './routes/primitives/index' +import { Route as RedirectTestSsrIndexRouteImport } from './routes/redirect-test-ssr/index' +import { Route as RedirectTestSsrTargetRouteImport } from './routes/redirect-test-ssr/target' +import { Route as RedirectTestIndexRouteImport } from './routes/redirect-test/index' +import { Route as RedirectTestTargetRouteImport } from './routes/redirect-test/target' import { Route as FormdataRedirectTargetNameRouteImport } from './routes/formdata-redirect/target.$name' -const SubmitPostFormdataRoute = SubmitPostFormdataRouteImport.update({ - id: '/submit-post-formdata', - path: '/submit-post-formdata', - getParentRoute: () => rootRouteImport, -} as any) -const StatusRoute = StatusRouteImport.update({ - id: '/status', - path: '/status', - getParentRoute: () => rootRouteImport, -} as any) -const SerializeFormDataRoute = SerializeFormDataRouteImport.update({ - id: '/serialize-form-data', - path: '/serialize-form-data', - getParentRoute: () => rootRouteImport, -} as any) -const ReturnNullRoute = ReturnNullRouteImport.update({ - id: '/return-null', - path: '/return-null', - getParentRoute: () => rootRouteImport, -} as any) -const RawResponseRoute = RawResponseRouteImport.update({ - id: '/raw-response', - path: '/raw-response', - getParentRoute: () => rootRouteImport, -} as any) -const MultipartRoute = MultipartRouteImport.update({ - id: '/multipart', - path: '/multipart', - getParentRoute: () => rootRouteImport, -} as any) -const IsomorphicFnsRoute = IsomorphicFnsRouteImport.update({ - id: '/isomorphic-fns', - path: '/isomorphic-fns', - getParentRoute: () => rootRouteImport, -} as any) -const HeadersRoute = HeadersRouteImport.update({ - id: '/headers', - path: '/headers', - getParentRoute: () => rootRouteImport, -} as any) -const EnvOnlyRoute = EnvOnlyRouteImport.update({ - id: '/env-only', - path: '/env-only', - getParentRoute: () => rootRouteImport, -} as any) -const DeadCodePreserveRoute = DeadCodePreserveRouteImport.update({ - id: '/dead-code-preserve', - path: '/dead-code-preserve', - getParentRoute: () => rootRouteImport, -} as any) -const ConsistentRoute = ConsistentRouteImport.update({ - id: '/consistent', - path: '/consistent', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AbortSignalRoute = AbortSignalRouteImport.update({ @@ -99,49 +49,59 @@ const AbortSignalRoute = AbortSignalRouteImport.update({ path: '/abort-signal', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ConsistentRoute = ConsistentRouteImport.update({ + id: '/consistent', + path: '/consistent', getParentRoute: () => rootRouteImport, } as any) -const RedirectTestIndexRoute = RedirectTestIndexRouteImport.update({ - id: '/redirect-test/', - path: '/redirect-test/', +const DeadCodePreserveRoute = DeadCodePreserveRouteImport.update({ + id: '/dead-code-preserve', + path: '/dead-code-preserve', getParentRoute: () => rootRouteImport, } as any) -const RedirectTestSsrIndexRoute = RedirectTestSsrIndexRouteImport.update({ - id: '/redirect-test-ssr/', - path: '/redirect-test-ssr/', +const EnvOnlyRoute = EnvOnlyRouteImport.update({ + id: '/env-only', + path: '/env-only', getParentRoute: () => rootRouteImport, } as any) -const PrimitivesIndexRoute = PrimitivesIndexRouteImport.update({ - id: '/primitives/', - path: '/primitives/', +const HeadersRoute = HeadersRouteImport.update({ + id: '/headers', + path: '/headers', getParentRoute: () => rootRouteImport, } as any) -const MiddlewareIndexRoute = MiddlewareIndexRouteImport.update({ - id: '/middleware/', - path: '/middleware/', +const IsomorphicFnsRoute = IsomorphicFnsRouteImport.update({ + id: '/isomorphic-fns', + path: '/isomorphic-fns', getParentRoute: () => rootRouteImport, } as any) -const FunctionMethodIndexRoute = FunctionMethodIndexRouteImport.update({ - id: '/function-method/', - path: '/function-method/', +const MultipartRoute = MultipartRouteImport.update({ + id: '/multipart', + path: '/multipart', getParentRoute: () => rootRouteImport, } as any) -const FunctionMetadataIndexRoute = FunctionMetadataIndexRouteImport.update({ - id: '/function-metadata/', - path: '/function-metadata/', +const RawResponseRoute = RawResponseRouteImport.update({ + id: '/raw-response', + path: '/raw-response', getParentRoute: () => rootRouteImport, } as any) -const FormdataRedirectIndexRoute = FormdataRedirectIndexRouteImport.update({ - id: '/formdata-redirect/', - path: '/formdata-redirect/', +const ReturnNullRoute = ReturnNullRouteImport.update({ + id: '/return-null', + path: '/return-null', getParentRoute: () => rootRouteImport, } as any) -const FactoryIndexRoute = FactoryIndexRouteImport.update({ - id: '/factory/', - path: '/factory/', +const SerializeFormDataRoute = SerializeFormDataRouteImport.update({ + id: '/serialize-form-data', + path: '/serialize-form-data', + getParentRoute: () => rootRouteImport, +} as any) +const StatusRoute = StatusRouteImport.update({ + id: '/status', + path: '/status', + getParentRoute: () => rootRouteImport, +} as any) +const SubmitPostFormdataRoute = SubmitPostFormdataRouteImport.update({ + id: '/submit-post-formdata', + path: '/submit-post-formdata', getParentRoute: () => rootRouteImport, } as any) const CookiesIndexRoute = CookiesIndexRouteImport.update({ @@ -149,9 +109,61 @@ const CookiesIndexRoute = CookiesIndexRouteImport.update({ path: '/cookies/', getParentRoute: () => rootRouteImport, } as any) -const RedirectTestTargetRoute = RedirectTestTargetRouteImport.update({ - id: '/redirect-test/target', - path: '/redirect-test/target', +const CookiesSetRoute = CookiesSetRouteImport.update({ + id: '/cookies/set', + path: '/cookies/set', + getParentRoute: () => rootRouteImport, +} as any) +const FactoryIndexRoute = FactoryIndexRouteImport.update({ + id: '/factory/', + path: '/factory/', + getParentRoute: () => rootRouteImport, +} as any) +const FormdataRedirectIndexRoute = FormdataRedirectIndexRouteImport.update({ + id: '/formdata-redirect/', + path: '/formdata-redirect/', + getParentRoute: () => rootRouteImport, +} as any) +const FunctionMetadataIndexRoute = FunctionMetadataIndexRouteImport.update({ + id: '/function-metadata/', + path: '/function-metadata/', + getParentRoute: () => rootRouteImport, +} as any) +const FunctionMethodIndexRoute = FunctionMethodIndexRouteImport.update({ + id: '/function-method/', + path: '/function-method/', + getParentRoute: () => rootRouteImport, +} as any) +const MiddlewareIndexRoute = MiddlewareIndexRouteImport.update({ + id: '/middleware/', + path: '/middleware/', + getParentRoute: () => rootRouteImport, +} as any) +const MiddlewareClientMiddlewareRouterRoute = + MiddlewareClientMiddlewareRouterRouteImport.update({ + id: '/middleware/client-middleware-router', + path: '/middleware/client-middleware-router', + getParentRoute: () => rootRouteImport, + } as any) +const MiddlewareRequestMiddlewareRoute = + MiddlewareRequestMiddlewareRouteImport.update({ + id: '/middleware/request-middleware', + path: '/middleware/request-middleware', + getParentRoute: () => rootRouteImport, + } as any) +const MiddlewareSendServerFnRoute = MiddlewareSendServerFnRouteImport.update({ + id: '/middleware/send-serverFn', + path: '/middleware/send-serverFn', + getParentRoute: () => rootRouteImport, +} as any) +const PrimitivesIndexRoute = PrimitivesIndexRouteImport.update({ + id: '/primitives/', + path: '/primitives/', + getParentRoute: () => rootRouteImport, +} as any) +const RedirectTestSsrIndexRoute = RedirectTestSsrIndexRouteImport.update({ + id: '/redirect-test-ssr/', + path: '/redirect-test-ssr/', getParentRoute: () => rootRouteImport, } as any) const RedirectTestSsrTargetRoute = RedirectTestSsrTargetRouteImport.update({ @@ -159,26 +171,14 @@ const RedirectTestSsrTargetRoute = RedirectTestSsrTargetRouteImport.update({ path: '/redirect-test-ssr/target', getParentRoute: () => rootRouteImport, } as any) -const MiddlewareSendServerFnRoute = MiddlewareSendServerFnRouteImport.update({ - id: '/middleware/send-serverFn', - path: '/middleware/send-serverFn', +const RedirectTestIndexRoute = RedirectTestIndexRouteImport.update({ + id: '/redirect-test/', + path: '/redirect-test/', getParentRoute: () => rootRouteImport, } as any) -const MiddlewareRequestMiddlewareRoute = - MiddlewareRequestMiddlewareRouteImport.update({ - id: '/middleware/request-middleware', - path: '/middleware/request-middleware', - getParentRoute: () => rootRouteImport, - } as any) -const MiddlewareClientMiddlewareRouterRoute = - MiddlewareClientMiddlewareRouterRouteImport.update({ - id: '/middleware/client-middleware-router', - path: '/middleware/client-middleware-router', - getParentRoute: () => rootRouteImport, - } as any) -const CookiesSetRoute = CookiesSetRouteImport.update({ - id: '/cookies/set', - path: '/cookies/set', +const RedirectTestTargetRoute = RedirectTestTargetRouteImport.update({ + id: '/redirect-test/target', + path: '/redirect-test/target', getParentRoute: () => rootRouteImport, } as any) const FormdataRedirectTargetNameRoute = @@ -412,81 +412,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/submit-post-formdata': { - id: '/submit-post-formdata' - path: '/submit-post-formdata' - fullPath: '/submit-post-formdata' - preLoaderRoute: typeof SubmitPostFormdataRouteImport - parentRoute: typeof rootRouteImport - } - '/status': { - id: '/status' - path: '/status' - fullPath: '/status' - preLoaderRoute: typeof StatusRouteImport - parentRoute: typeof rootRouteImport - } - '/serialize-form-data': { - id: '/serialize-form-data' - path: '/serialize-form-data' - fullPath: '/serialize-form-data' - preLoaderRoute: typeof SerializeFormDataRouteImport - parentRoute: typeof rootRouteImport - } - '/return-null': { - id: '/return-null' - path: '/return-null' - fullPath: '/return-null' - preLoaderRoute: typeof ReturnNullRouteImport - parentRoute: typeof rootRouteImport - } - '/raw-response': { - id: '/raw-response' - path: '/raw-response' - fullPath: '/raw-response' - preLoaderRoute: typeof RawResponseRouteImport - parentRoute: typeof rootRouteImport - } - '/multipart': { - id: '/multipart' - path: '/multipart' - fullPath: '/multipart' - preLoaderRoute: typeof MultipartRouteImport - parentRoute: typeof rootRouteImport - } - '/isomorphic-fns': { - id: '/isomorphic-fns' - path: '/isomorphic-fns' - fullPath: '/isomorphic-fns' - preLoaderRoute: typeof IsomorphicFnsRouteImport - parentRoute: typeof rootRouteImport - } - '/headers': { - id: '/headers' - path: '/headers' - fullPath: '/headers' - preLoaderRoute: typeof HeadersRouteImport - parentRoute: typeof rootRouteImport - } - '/env-only': { - id: '/env-only' - path: '/env-only' - fullPath: '/env-only' - preLoaderRoute: typeof EnvOnlyRouteImport - parentRoute: typeof rootRouteImport - } - '/dead-code-preserve': { - id: '/dead-code-preserve' - path: '/dead-code-preserve' - fullPath: '/dead-code-preserve' - preLoaderRoute: typeof DeadCodePreserveRouteImport - parentRoute: typeof rootRouteImport - } - '/consistent': { - id: '/consistent' - path: '/consistent' - fullPath: '/consistent' - preLoaderRoute: typeof ConsistentRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/abort-signal': { @@ -496,67 +426,81 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof AbortSignalRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/consistent': { + id: '/consistent' + path: '/consistent' + fullPath: '/consistent' + preLoaderRoute: typeof ConsistentRouteImport parentRoute: typeof rootRouteImport } - '/redirect-test/': { - id: '/redirect-test/' - path: '/redirect-test' - fullPath: '/redirect-test/' - preLoaderRoute: typeof RedirectTestIndexRouteImport + '/dead-code-preserve': { + id: '/dead-code-preserve' + path: '/dead-code-preserve' + fullPath: '/dead-code-preserve' + preLoaderRoute: typeof DeadCodePreserveRouteImport parentRoute: typeof rootRouteImport } - '/redirect-test-ssr/': { - id: '/redirect-test-ssr/' - path: '/redirect-test-ssr' - fullPath: '/redirect-test-ssr/' - preLoaderRoute: typeof RedirectTestSsrIndexRouteImport + '/env-only': { + id: '/env-only' + path: '/env-only' + fullPath: '/env-only' + preLoaderRoute: typeof EnvOnlyRouteImport parentRoute: typeof rootRouteImport } - '/primitives/': { - id: '/primitives/' - path: '/primitives' - fullPath: '/primitives/' - preLoaderRoute: typeof PrimitivesIndexRouteImport + '/headers': { + id: '/headers' + path: '/headers' + fullPath: '/headers' + preLoaderRoute: typeof HeadersRouteImport parentRoute: typeof rootRouteImport } - '/middleware/': { - id: '/middleware/' - path: '/middleware' - fullPath: '/middleware/' - preLoaderRoute: typeof MiddlewareIndexRouteImport + '/isomorphic-fns': { + id: '/isomorphic-fns' + path: '/isomorphic-fns' + fullPath: '/isomorphic-fns' + preLoaderRoute: typeof IsomorphicFnsRouteImport parentRoute: typeof rootRouteImport } - '/function-method/': { - id: '/function-method/' - path: '/function-method' - fullPath: '/function-method/' - preLoaderRoute: typeof FunctionMethodIndexRouteImport + '/multipart': { + id: '/multipart' + path: '/multipart' + fullPath: '/multipart' + preLoaderRoute: typeof MultipartRouteImport parentRoute: typeof rootRouteImport } - '/function-metadata/': { - id: '/function-metadata/' - path: '/function-metadata' - fullPath: '/function-metadata/' - preLoaderRoute: typeof FunctionMetadataIndexRouteImport + '/raw-response': { + id: '/raw-response' + path: '/raw-response' + fullPath: '/raw-response' + preLoaderRoute: typeof RawResponseRouteImport parentRoute: typeof rootRouteImport } - '/formdata-redirect/': { - id: '/formdata-redirect/' - path: '/formdata-redirect' - fullPath: '/formdata-redirect/' - preLoaderRoute: typeof FormdataRedirectIndexRouteImport + '/return-null': { + id: '/return-null' + path: '/return-null' + fullPath: '/return-null' + preLoaderRoute: typeof ReturnNullRouteImport parentRoute: typeof rootRouteImport } - '/factory/': { - id: '/factory/' - path: '/factory' - fullPath: '/factory/' - preLoaderRoute: typeof FactoryIndexRouteImport + '/serialize-form-data': { + id: '/serialize-form-data' + path: '/serialize-form-data' + fullPath: '/serialize-form-data' + preLoaderRoute: typeof SerializeFormDataRouteImport + parentRoute: typeof rootRouteImport + } + '/status': { + id: '/status' + path: '/status' + fullPath: '/status' + preLoaderRoute: typeof StatusRouteImport + parentRoute: typeof rootRouteImport + } + '/submit-post-formdata': { + id: '/submit-post-formdata' + path: '/submit-post-formdata' + fullPath: '/submit-post-formdata' + preLoaderRoute: typeof SubmitPostFormdataRouteImport parentRoute: typeof rootRouteImport } '/cookies/': { @@ -566,32 +510,46 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof CookiesIndexRouteImport parentRoute: typeof rootRouteImport } - '/redirect-test/target': { - id: '/redirect-test/target' - path: '/redirect-test/target' - fullPath: '/redirect-test/target' - preLoaderRoute: typeof RedirectTestTargetRouteImport + '/cookies/set': { + id: '/cookies/set' + path: '/cookies/set' + fullPath: '/cookies/set' + preLoaderRoute: typeof CookiesSetRouteImport parentRoute: typeof rootRouteImport } - '/redirect-test-ssr/target': { - id: '/redirect-test-ssr/target' - path: '/redirect-test-ssr/target' - fullPath: '/redirect-test-ssr/target' - preLoaderRoute: typeof RedirectTestSsrTargetRouteImport + '/factory/': { + id: '/factory/' + path: '/factory' + fullPath: '/factory/' + preLoaderRoute: typeof FactoryIndexRouteImport parentRoute: typeof rootRouteImport } - '/middleware/send-serverFn': { - id: '/middleware/send-serverFn' - path: '/middleware/send-serverFn' - fullPath: '/middleware/send-serverFn' - preLoaderRoute: typeof MiddlewareSendServerFnRouteImport + '/formdata-redirect/': { + id: '/formdata-redirect/' + path: '/formdata-redirect' + fullPath: '/formdata-redirect/' + preLoaderRoute: typeof FormdataRedirectIndexRouteImport parentRoute: typeof rootRouteImport } - '/middleware/request-middleware': { - id: '/middleware/request-middleware' - path: '/middleware/request-middleware' - fullPath: '/middleware/request-middleware' - preLoaderRoute: typeof MiddlewareRequestMiddlewareRouteImport + '/function-metadata/': { + id: '/function-metadata/' + path: '/function-metadata' + fullPath: '/function-metadata/' + preLoaderRoute: typeof FunctionMetadataIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/function-method/': { + id: '/function-method/' + path: '/function-method' + fullPath: '/function-method/' + preLoaderRoute: typeof FunctionMethodIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/middleware/': { + id: '/middleware/' + path: '/middleware' + fullPath: '/middleware/' + preLoaderRoute: typeof MiddlewareIndexRouteImport parentRoute: typeof rootRouteImport } '/middleware/client-middleware-router': { @@ -601,11 +559,53 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof MiddlewareClientMiddlewareRouterRouteImport parentRoute: typeof rootRouteImport } - '/cookies/set': { - id: '/cookies/set' - path: '/cookies/set' - fullPath: '/cookies/set' - preLoaderRoute: typeof CookiesSetRouteImport + '/middleware/request-middleware': { + id: '/middleware/request-middleware' + path: '/middleware/request-middleware' + fullPath: '/middleware/request-middleware' + preLoaderRoute: typeof MiddlewareRequestMiddlewareRouteImport + parentRoute: typeof rootRouteImport + } + '/middleware/send-serverFn': { + id: '/middleware/send-serverFn' + path: '/middleware/send-serverFn' + fullPath: '/middleware/send-serverFn' + preLoaderRoute: typeof MiddlewareSendServerFnRouteImport + parentRoute: typeof rootRouteImport + } + '/primitives/': { + id: '/primitives/' + path: '/primitives' + fullPath: '/primitives/' + preLoaderRoute: typeof PrimitivesIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect-test-ssr/': { + id: '/redirect-test-ssr/' + path: '/redirect-test-ssr' + fullPath: '/redirect-test-ssr/' + preLoaderRoute: typeof RedirectTestSsrIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect-test-ssr/target': { + id: '/redirect-test-ssr/target' + path: '/redirect-test-ssr/target' + fullPath: '/redirect-test-ssr/target' + preLoaderRoute: typeof RedirectTestSsrTargetRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect-test/': { + id: '/redirect-test/' + path: '/redirect-test' + fullPath: '/redirect-test/' + preLoaderRoute: typeof RedirectTestIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect-test/target': { + id: '/redirect-test/target' + path: '/redirect-test/target' + fullPath: '/redirect-test/target' + preLoaderRoute: typeof RedirectTestTargetRouteImport parentRoute: typeof rootRouteImport } '/formdata-redirect/target/$name': { diff --git a/e2e/vue-start/server-functions/src/routes/__root.tsx b/e2e/vue-start/server-functions/src/routes/__root.tsx index 342f7a79b3..a52b12deae 100644 --- a/e2e/vue-start/server-functions/src/routes/__root.tsx +++ b/e2e/vue-start/server-functions/src/routes/__root.tsx @@ -25,7 +25,11 @@ export const Route = createRootRoute({ links: [{ rel: 'stylesheet', href: appCss }], }), errorComponent: (props) => { - return

{props.error.stack}

+ return ( +

+ {props.error instanceof Error ? props.error.stack : String(props.error)} +

+ ) }, notFoundComponent: () => , component: RootComponent, diff --git a/e2e/vue-start/server-functions/src/routes/cookies/index.tsx b/e2e/vue-start/server-functions/src/routes/cookies/index.tsx index d7fef10223..90dddad0af 100644 --- a/e2e/vue-start/server-functions/src/routes/cookies/index.tsx +++ b/e2e/vue-start/server-functions/src/routes/cookies/index.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' import { z } from 'zod' @@ -5,21 +6,23 @@ const cookieSchema = z .object({ value: z.string().default(() => `CLIENT-${Date.now()}`) }) .prefault({}) .catch(() => ({ value: `CLIENT-${Date.now()}` })) +const RouteComponent = defineComponent({ + setup() { + const search = Route.useSearch() + return () => ( + + got to route that sets the cookies with {JSON.stringify(search.value)} + + ) + }, +}) + export const Route = createFileRoute('/cookies/')({ validateSearch: cookieSchema, component: RouteComponent, }) - -function RouteComponent() { - const search = Route.useSearch() - return ( - - got to route that sets the cookies with {JSON.stringify(search.value)} - - ) -} diff --git a/e2e/vue-start/server-functions/src/routes/formdata-redirect/index.tsx b/e2e/vue-start/server-functions/src/routes/formdata-redirect/index.tsx index 8b0c623b8c..8bfcc55ca3 100644 --- a/e2e/vue-start/server-functions/src/routes/formdata-redirect/index.tsx +++ b/e2e/vue-start/server-functions/src/routes/formdata-redirect/index.tsx @@ -1,7 +1,51 @@ +import { defineComponent } from 'vue' import { createFileRoute, redirect } from '@tanstack/vue-router' import { createServerFn, useServerFn } from '@tanstack/vue-start' import { z } from 'zod' +const SubmitPostFormDataFn = defineComponent({ + setup() { + const mode = Route.useSearch({ select: (search) => search.mode }) + const greetUserFn = useServerFn(greetUser) + return () => ( +
+

Submit POST FormData Fn Call

+
+ It should return redirect to /formdata-redirect/target/ + {testValues.name} and greet the user with their name: + +
+              {testValues.name}
+            
+
+
+
{ + if (mode.value === 'js') { + evt.preventDefault() + const data = new FormData(evt.currentTarget as HTMLFormElement) + await greetUserFn({ data }) + } + }} + > + + +
+
+ ) + }, +}) + export const Route = createFileRoute('/formdata-redirect/')({ component: SubmitPostFormDataFn, validateSearch: z.object({ @@ -31,44 +75,3 @@ export const greetUser = createServerFn({ method: 'POST' }) .handler(({ data: { name } }) => { throw redirect({ to: '/formdata-redirect/target/$name', params: { name } }) }) - -function SubmitPostFormDataFn() { - const mode = Route.useSearch({ select: (search) => search.mode }) - const greetUserFn = useServerFn(greetUser) - return ( -
-

Submit POST FormData Fn Call

-
- It should return redirect to /formdata-redirect/target/{testValues.name}{' '} - and greet the user with their name: - -
-            {testValues.name}
-          
-
-
-
{ - if (mode.value === 'js') { - evt.preventDefault() - const data = new FormData(evt.currentTarget as HTMLFormElement) - await greetUserFn({ data }) - } - }} - > - - -
-
- ) -} diff --git a/e2e/vue-start/server-functions/src/routes/formdata-redirect/target.$name.tsx b/e2e/vue-start/server-functions/src/routes/formdata-redirect/target.$name.tsx index 958aeaf617..099a8665bf 100644 --- a/e2e/vue-start/server-functions/src/routes/formdata-redirect/target.$name.tsx +++ b/e2e/vue-start/server-functions/src/routes/formdata-redirect/target.$name.tsx @@ -1,18 +1,21 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' +const RouteComponent = defineComponent({ + setup() { + const params = Route.useParams() + return () => ( +
+ Hello{' '} + + {params.value.name} + + ! +
+ ) + }, +}) + export const Route = createFileRoute('/formdata-redirect/target/$name')({ component: RouteComponent, }) - -function RouteComponent() { - const params = Route.useParams() - return ( -
- Hello{' '} - - {params.value.name} - - ! -
- ) -} diff --git a/e2e/vue-start/server-routes/package.json b/e2e/vue-start/server-routes/package.json index 4f9db26152..6a8e1babed 100644 --- a/e2e/vue-start/server-routes/package.json +++ b/e2e/vue-start/server-routes/package.json @@ -18,7 +18,7 @@ "@tanstack/vue-router-ssr-query": "workspace:^", "@tanstack/vue-start": "workspace:^", "js-cookie": "^3.0.5", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "vue": "^3.5.25", "zod": "^4.4.3" @@ -32,9 +32,10 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/e2e/vue-start/server-routes/playwright.config.ts b/e2e/vue-start/server-routes/playwright.config.ts index cb1da03b94..48e14683f4 100644 --- a/e2e/vue-start/server-routes/playwright.config.ts +++ b/e2e/vue-start/server-routes/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -export const PORT = await getTestServerPort(packageJson.name) +export const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,8 +20,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-start/server-routes/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/server-routes/src/components/DefaultCatchBoundary.tsx index d06f4a948b..77c03c5afa 100644 --- a/e2e/vue-start/server-routes/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/server-routes/src/components/DefaultCatchBoundary.tsx @@ -1,3 +1,5 @@ +import { defineComponent } from 'vue' +import type { PropType } from 'vue' import { ErrorComponent, Link, @@ -6,46 +8,54 @@ import { } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - - console.error(error) - - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} +export const DefaultCatchBoundary = defineComponent({ + props: { + error: { + type: Object as PropType, + required: true, + }, + }, + setup(props) { + const router = useRouter() + const isRoot = useLocation({ + select: (location) => location.pathname === '/', + }) + return () => { + console.error(props.error) + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) + } + }, +}) diff --git a/e2e/vue-start/server-routes/src/routeTree.gen.ts b/e2e/vue-start/server-routes/src/routeTree.gen.ts index 7d9d463772..603560da2a 100644 --- a/e2e/vue-start/server-routes/src/routeTree.gen.ts +++ b/e2e/vue-start/server-routes/src/routeTree.gen.ts @@ -9,16 +9,21 @@ // 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 MergeMiddlewareContextRouteImport } from './routes/merge-middleware-context' import { Route as MethodsRouteRouteImport } from './routes/methods/route' -import { Route as IndexRouteImport } from './routes/index' +import { Route as ApiMiddlewareContextRouteImport } from './routes/api/middleware-context' +import { Route as ApiOnlyAnyRouteImport } from './routes/api/only-any' import { Route as MethodsIndexRouteImport } from './routes/methods/index' import { Route as MethodsOnlyAnyRouteImport } from './routes/methods/only-any' -import { Route as ApiOnlyAnyRouteImport } from './routes/api/only-any' -import { Route as ApiMiddlewareContextRouteImport } from './routes/api/middleware-context' import { Route as ApiParamsFooRouteRouteImport } from './routes/api/params/$foo/route' import { Route as ApiParamsFooBarRouteImport } from './routes/api/params/$foo/$bar' +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const MergeMiddlewareContextRoute = MergeMiddlewareContextRouteImport.update({ id: '/merge-middleware-context', path: '/merge-middleware-context', @@ -29,9 +34,14 @@ const MethodsRouteRoute = MethodsRouteRouteImport.update({ path: '/methods', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ApiMiddlewareContextRoute = ApiMiddlewareContextRouteImport.update({ + id: '/api/middleware-context', + path: '/api/middleware-context', + getParentRoute: () => rootRouteImport, +} as any) +const ApiOnlyAnyRoute = ApiOnlyAnyRouteImport.update({ + id: '/api/only-any', + path: '/api/only-any', getParentRoute: () => rootRouteImport, } as any) const MethodsIndexRoute = MethodsIndexRouteImport.update({ @@ -44,16 +54,6 @@ const MethodsOnlyAnyRoute = MethodsOnlyAnyRouteImport.update({ path: '/only-any', getParentRoute: () => MethodsRouteRoute, } as any) -const ApiOnlyAnyRoute = ApiOnlyAnyRouteImport.update({ - id: '/api/only-any', - path: '/api/only-any', - getParentRoute: () => rootRouteImport, -} as any) -const ApiMiddlewareContextRoute = ApiMiddlewareContextRouteImport.update({ - id: '/api/middleware-context', - path: '/api/middleware-context', - getParentRoute: () => rootRouteImport, -} as any) const ApiParamsFooRouteRoute = ApiParamsFooRouteRouteImport.update({ id: '/api/params/$foo', path: '/api/params/$foo', @@ -144,6 +144,13 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/merge-middleware-context': { id: '/merge-middleware-context' path: '/merge-middleware-context' @@ -158,11 +165,18 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof MethodsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/api/middleware-context': { + id: '/api/middleware-context' + path: '/api/middleware-context' + fullPath: '/api/middleware-context' + preLoaderRoute: typeof ApiMiddlewareContextRouteImport + parentRoute: typeof rootRouteImport + } + '/api/only-any': { + id: '/api/only-any' + path: '/api/only-any' + fullPath: '/api/only-any' + preLoaderRoute: typeof ApiOnlyAnyRouteImport parentRoute: typeof rootRouteImport } '/methods/': { @@ -179,20 +193,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof MethodsOnlyAnyRouteImport parentRoute: typeof MethodsRouteRoute } - '/api/only-any': { - id: '/api/only-any' - path: '/api/only-any' - fullPath: '/api/only-any' - preLoaderRoute: typeof ApiOnlyAnyRouteImport - parentRoute: typeof rootRouteImport - } - '/api/middleware-context': { - id: '/api/middleware-context' - path: '/api/middleware-context' - fullPath: '/api/middleware-context' - preLoaderRoute: typeof ApiMiddlewareContextRouteImport - parentRoute: typeof rootRouteImport - } '/api/params/$foo': { id: '/api/params/$foo' path: '/api/params/$foo' diff --git a/e2e/vue-start/server-routes/src/routes/__root.tsx b/e2e/vue-start/server-routes/src/routes/__root.tsx index 999d80fff1..aa4b1f31fa 100644 --- a/e2e/vue-start/server-routes/src/routes/__root.tsx +++ b/e2e/vue-start/server-routes/src/routes/__root.tsx @@ -25,7 +25,11 @@ export const Route = createRootRoute({ links: [{ rel: 'stylesheet', href: appCss }], }), errorComponent: (props) => { - return

{props.error.stack}

+ return ( +

+ {props.error instanceof Error ? props.error.stack : String(props.error)} +

+ ) }, notFoundComponent: () => , component: RootComponent, diff --git a/e2e/vue-start/spa-mode/package.json b/e2e/vue-start/spa-mode/package.json index 1795d2d5c4..c4270cfccd 100644 --- a/e2e/vue-start/spa-mode/package.json +++ b/e2e/vue-start/spa-mode/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "npx serve dist/client", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -24,7 +24,8 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/e2e/vue-start/spa-mode/playwright.config.ts b/e2e/vue-start/spa-mode/playwright.config.ts index badd6db0eb..630989e41f 100644 --- a/e2e/vue-start/spa-mode/playwright.config.ts +++ b/e2e/vue-start/spa-mode/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -20,8 +19,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-start/spa-mode/src/routeTree.gen.ts b/e2e/vue-start/spa-mode/src/routeTree.gen.ts index 474705b7e7..0d44b648ee 100644 --- a/e2e/vue-start/spa-mode/src/routeTree.gen.ts +++ b/e2e/vue-start/spa-mode/src/routeTree.gen.ts @@ -9,20 +9,20 @@ // 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 PostsRouteImport } from './routes/posts' import { Route as IndexRouteImport } from './routes/index' +import { Route as PostsRouteImport } from './routes/posts' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) const PostsPostIdRoute = PostsPostIdRouteImport.update({ id: '/$postId', path: '/$postId', @@ -60,13 +60,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -74,6 +67,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } '/posts/$postId': { id: '/posts/$postId' path: '/$postId' diff --git a/e2e/vue-start/spa-mode/src/routes/__root.tsx b/e2e/vue-start/spa-mode/src/routes/__root.tsx index 1e38664739..45aee73c06 100644 --- a/e2e/vue-start/spa-mode/src/routes/__root.tsx +++ b/e2e/vue-start/spa-mode/src/routes/__root.tsx @@ -1,4 +1,5 @@ /// +import { defineComponent } from 'vue' import { Body, ClientOnly, @@ -13,6 +14,71 @@ import { import { TanStackRouterDevtools } from '@tanstack/vue-router-devtools' import appCss from '~/styles/app.css?url' +const RootDocument = defineComponent({ + setup(_, { slots }) { + const routerState = useRouterState({ + select: (state) => ({ isLoading: state.isLoading, status: state.status }), + }) + return () => ( + + + + + +
+

SPA Mode E2E Test

+ + Home + +
+
+ +
+ router isLoading:{' '} + + {routerState.value.isLoading ? 'true' : 'false'} + +
+
+ router status:{' '} + {routerState.value.status} +
+
+
+ {slots.default?.()} + + + + + ) + }, +}) + +const RouteComponent = defineComponent({ + setup() { + const loaderData = Route.useLoaderData() + const context = Route.useRouteContext() + return () => ( +
+

root

+
+ loader: {loaderData.value.root} +
+
+ context: {context.value.root} +
+
+ +
+ ) + }, +}) + export const Route = createRootRoute({ head: () => ({ meta: [ @@ -44,65 +110,6 @@ export const Route = createRootRoute({ return { root: typeof window === 'undefined' ? 'server' : 'client' } }, shellComponent: RootDocument, - component: () => { - const loaderData = Route.useLoaderData() - const context = Route.useRouteContext() - return ( -
-

root

-
- loader: {loaderData.value.root} -
-
- context: {context.value.root} -
-
- -
- ) - }, + component: RouteComponent, pendingComponent: () =>
__root Loading...
, }) - -function RootDocument(_: unknown, { slots }: { slots: any }) { - const routerState = useRouterState({ - select: (state) => ({ isLoading: state.isLoading, status: state.status }), - }) - return ( - - - - - -
-

SPA Mode E2E Test

- - Home - -
-
- -
- router isLoading:{' '} - - {routerState.value.isLoading ? 'true' : 'false'} - -
-
- router status:{' '} - {routerState.value.status} -
-
-
- {slots.default?.()} - - - - - ) -} diff --git a/e2e/vue-start/spa-mode/src/routes/posts.$postId.tsx b/e2e/vue-start/spa-mode/src/routes/posts.$postId.tsx index 6733ef7436..9c25cbad25 100644 --- a/e2e/vue-start/spa-mode/src/routes/posts.$postId.tsx +++ b/e2e/vue-start/spa-mode/src/routes/posts.$postId.tsx @@ -1,5 +1,24 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' +const RouteComponent = defineComponent({ + setup() { + const loaderData = Route.useLoaderData() + const context = Route.useRouteContext() + return () => ( +
+

postId

+
+ loader: {loaderData.value.postId} +
+
+ context: {context.value.postId} +
+
+ ) + }, +}) + export const Route = createFileRoute('/posts/$postId')({ beforeLoad: () => { console.log( @@ -15,20 +34,6 @@ export const Route = createFileRoute('/posts/$postId')({ ) return { postId: typeof window === 'undefined' ? 'server' : 'client' } }, - component: () => { - const loaderData = Route.useLoaderData() - const context = Route.useRouteContext() - return ( -
-

postId

-
- loader: {loaderData.value.postId} -
-
- context: {context.value.postId} -
-
- ) - }, + component: RouteComponent, pendingComponent: () =>
$postId Loading...
, }) diff --git a/e2e/vue-start/spa-mode/src/routes/posts.tsx b/e2e/vue-start/spa-mode/src/routes/posts.tsx index e69ae1ea86..44c536adc4 100644 --- a/e2e/vue-start/spa-mode/src/routes/posts.tsx +++ b/e2e/vue-start/spa-mode/src/routes/posts.tsx @@ -1,5 +1,26 @@ +import { defineComponent } from 'vue' import { Outlet, createFileRoute } from '@tanstack/vue-router' +const RouteComponent = defineComponent({ + setup() { + const loaderData = Route.useLoaderData() + const context = Route.useRouteContext() + return () => ( +
+

posts

+
+ loader: {loaderData.value.posts} +
+
+ context: {context.value.posts} +
+
+ +
+ ) + }, +}) + export const Route = createFileRoute('/posts')({ beforeLoad: () => { console.log( @@ -16,22 +37,6 @@ export const Route = createFileRoute('/posts')({ return { posts: typeof window === 'undefined' ? 'server' : 'client' } }, - component: () => { - const loaderData = Route.useLoaderData() - const context = Route.useRouteContext() - return ( -
-

posts

-
- loader: {loaderData.value.posts} -
-
- context: {context.value.posts} -
-
- -
- ) - }, + component: RouteComponent, pendingComponent: () =>
posts Loading...
, }) diff --git a/e2e/vue-start/start-manifest/package.json b/e2e/vue-start/start-manifest/package.json index 358e8e0c04..ae682f7a9d 100644 --- a/e2e/vue-start/start-manifest/package.json +++ b/e2e/vue-start/start-manifest/package.json @@ -19,8 +19,9 @@ "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^0.11.9", - "typescript": "^6.0.2", + "srvx": "^1.0.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" }, "nx": { diff --git a/e2e/vue-start/start-manifest/playwright.config.ts b/e2e/vue-start/start-manifest/playwright.config.ts index b9f835c16a..653e08253f 100644 --- a/e2e/vue-start/start-manifest/playwright.config.ts +++ b/e2e/vue-start/start-manifest/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -16,8 +15,8 @@ export default defineConfig({ webServer: { command: `pnpm build && PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-start/start-manifest/src/routeTree.gen.ts b/e2e/vue-start/start-manifest/src/routeTree.gen.ts index 357d3be62b..fc42a1e404 100644 --- a/e2e/vue-start/start-manifest/src/routeTree.gen.ts +++ b/e2e/vue-start/start-manifest/src/routeTree.gen.ts @@ -9,79 +9,24 @@ // 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 SharedCRouteImport } from './routes/shared-c' -import { Route as SharedBRouteImport } from './routes/shared-b' -import { Route as SharedARouteImport } from './routes/shared-a' -import { Route as R6RouteImport } from './routes/r6' -import { Route as R5RouteImport } from './routes/r5' -import { Route as R4RouteImport } from './routes/r4' -import { Route as R3RouteImport } from './routes/r3' -import { Route as R2RouteImport } from './routes/r2' -import { Route as R1RouteImport } from './routes/r1' -import { Route as LazyCssStaticRouteImport } from './routes/lazy-css-static' -import { Route as LazyCssLazyRouteImport } from './routes/lazy-css-lazy' -import { Route as BRouteImport } from './routes/b' -import { Route as ARouteImport } from './routes/a' import { Route as IndexRouteImport } from './routes/index' +import { Route as ARouteImport } from './routes/a' +import { Route as BRouteImport } from './routes/b' +import { Route as LazyCssLazyRouteImport } from './routes/lazy-css-lazy' +import { Route as LazyCssStaticRouteImport } from './routes/lazy-css-static' +import { Route as R1RouteImport } from './routes/r1' +import { Route as R2RouteImport } from './routes/r2' +import { Route as R3RouteImport } from './routes/r3' +import { Route as R4RouteImport } from './routes/r4' +import { Route as R5RouteImport } from './routes/r5' +import { Route as R6RouteImport } from './routes/r6' +import { Route as SharedARouteImport } from './routes/shared-a' +import { Route as SharedBRouteImport } from './routes/shared-b' +import { Route as SharedCRouteImport } from './routes/shared-c' -const SharedCRoute = SharedCRouteImport.update({ - id: '/shared-c', - path: '/shared-c', - getParentRoute: () => rootRouteImport, -} as any) -const SharedBRoute = SharedBRouteImport.update({ - id: '/shared-b', - path: '/shared-b', - getParentRoute: () => rootRouteImport, -} as any) -const SharedARoute = SharedARouteImport.update({ - id: '/shared-a', - path: '/shared-a', - getParentRoute: () => rootRouteImport, -} as any) -const R6Route = R6RouteImport.update({ - id: '/r6', - path: '/r6', - getParentRoute: () => rootRouteImport, -} as any) -const R5Route = R5RouteImport.update({ - id: '/r5', - path: '/r5', - getParentRoute: () => rootRouteImport, -} as any) -const R4Route = R4RouteImport.update({ - id: '/r4', - path: '/r4', - getParentRoute: () => rootRouteImport, -} as any) -const R3Route = R3RouteImport.update({ - id: '/r3', - path: '/r3', - getParentRoute: () => rootRouteImport, -} as any) -const R2Route = R2RouteImport.update({ - id: '/r2', - path: '/r2', - getParentRoute: () => rootRouteImport, -} as any) -const R1Route = R1RouteImport.update({ - id: '/r1', - path: '/r1', - getParentRoute: () => rootRouteImport, -} as any) -const LazyCssStaticRoute = LazyCssStaticRouteImport.update({ - id: '/lazy-css-static', - path: '/lazy-css-static', - getParentRoute: () => rootRouteImport, -} as any) -const LazyCssLazyRoute = LazyCssLazyRouteImport.update({ - id: '/lazy-css-lazy', - path: '/lazy-css-lazy', - getParentRoute: () => rootRouteImport, -} as any) -const BRoute = BRouteImport.update({ - id: '/b', - path: '/b', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const ARoute = ARouteImport.update({ @@ -89,9 +34,64 @@ const ARoute = ARouteImport.update({ path: '/a', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const BRoute = BRouteImport.update({ + id: '/b', + path: '/b', + getParentRoute: () => rootRouteImport, +} as any) +const LazyCssLazyRoute = LazyCssLazyRouteImport.update({ + id: '/lazy-css-lazy', + path: '/lazy-css-lazy', + getParentRoute: () => rootRouteImport, +} as any) +const LazyCssStaticRoute = LazyCssStaticRouteImport.update({ + id: '/lazy-css-static', + path: '/lazy-css-static', + getParentRoute: () => rootRouteImport, +} as any) +const R1Route = R1RouteImport.update({ + id: '/r1', + path: '/r1', + getParentRoute: () => rootRouteImport, +} as any) +const R2Route = R2RouteImport.update({ + id: '/r2', + path: '/r2', + getParentRoute: () => rootRouteImport, +} as any) +const R3Route = R3RouteImport.update({ + id: '/r3', + path: '/r3', + getParentRoute: () => rootRouteImport, +} as any) +const R4Route = R4RouteImport.update({ + id: '/r4', + path: '/r4', + getParentRoute: () => rootRouteImport, +} as any) +const R5Route = R5RouteImport.update({ + id: '/r5', + path: '/r5', + getParentRoute: () => rootRouteImport, +} as any) +const R6Route = R6RouteImport.update({ + id: '/r6', + path: '/r6', + getParentRoute: () => rootRouteImport, +} as any) +const SharedARoute = SharedARouteImport.update({ + id: '/shared-a', + path: '/shared-a', + getParentRoute: () => rootRouteImport, +} as any) +const SharedBRoute = SharedBRouteImport.update({ + id: '/shared-b', + path: '/shared-b', + getParentRoute: () => rootRouteImport, +} as any) +const SharedCRoute = SharedCRouteImport.update({ + id: '/shared-c', + path: '/shared-c', getParentRoute: () => rootRouteImport, } as any) @@ -214,88 +214,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/shared-c': { - id: '/shared-c' - path: '/shared-c' - fullPath: '/shared-c' - preLoaderRoute: typeof SharedCRouteImport - parentRoute: typeof rootRouteImport - } - '/shared-b': { - id: '/shared-b' - path: '/shared-b' - fullPath: '/shared-b' - preLoaderRoute: typeof SharedBRouteImport - parentRoute: typeof rootRouteImport - } - '/shared-a': { - id: '/shared-a' - path: '/shared-a' - fullPath: '/shared-a' - preLoaderRoute: typeof SharedARouteImport - parentRoute: typeof rootRouteImport - } - '/r6': { - id: '/r6' - path: '/r6' - fullPath: '/r6' - preLoaderRoute: typeof R6RouteImport - parentRoute: typeof rootRouteImport - } - '/r5': { - id: '/r5' - path: '/r5' - fullPath: '/r5' - preLoaderRoute: typeof R5RouteImport - parentRoute: typeof rootRouteImport - } - '/r4': { - id: '/r4' - path: '/r4' - fullPath: '/r4' - preLoaderRoute: typeof R4RouteImport - parentRoute: typeof rootRouteImport - } - '/r3': { - id: '/r3' - path: '/r3' - fullPath: '/r3' - preLoaderRoute: typeof R3RouteImport - parentRoute: typeof rootRouteImport - } - '/r2': { - id: '/r2' - path: '/r2' - fullPath: '/r2' - preLoaderRoute: typeof R2RouteImport - parentRoute: typeof rootRouteImport - } - '/r1': { - id: '/r1' - path: '/r1' - fullPath: '/r1' - preLoaderRoute: typeof R1RouteImport - parentRoute: typeof rootRouteImport - } - '/lazy-css-static': { - id: '/lazy-css-static' - path: '/lazy-css-static' - fullPath: '/lazy-css-static' - preLoaderRoute: typeof LazyCssStaticRouteImport - parentRoute: typeof rootRouteImport - } - '/lazy-css-lazy': { - id: '/lazy-css-lazy' - path: '/lazy-css-lazy' - fullPath: '/lazy-css-lazy' - preLoaderRoute: typeof LazyCssLazyRouteImport - parentRoute: typeof rootRouteImport - } - '/b': { - id: '/b' - path: '/b' - fullPath: '/b' - preLoaderRoute: typeof BRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/a': { @@ -305,11 +228,88 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ARouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/b': { + id: '/b' + path: '/b' + fullPath: '/b' + preLoaderRoute: typeof BRouteImport + parentRoute: typeof rootRouteImport + } + '/lazy-css-lazy': { + id: '/lazy-css-lazy' + path: '/lazy-css-lazy' + fullPath: '/lazy-css-lazy' + preLoaderRoute: typeof LazyCssLazyRouteImport + parentRoute: typeof rootRouteImport + } + '/lazy-css-static': { + id: '/lazy-css-static' + path: '/lazy-css-static' + fullPath: '/lazy-css-static' + preLoaderRoute: typeof LazyCssStaticRouteImport + parentRoute: typeof rootRouteImport + } + '/r1': { + id: '/r1' + path: '/r1' + fullPath: '/r1' + preLoaderRoute: typeof R1RouteImport + parentRoute: typeof rootRouteImport + } + '/r2': { + id: '/r2' + path: '/r2' + fullPath: '/r2' + preLoaderRoute: typeof R2RouteImport + parentRoute: typeof rootRouteImport + } + '/r3': { + id: '/r3' + path: '/r3' + fullPath: '/r3' + preLoaderRoute: typeof R3RouteImport + parentRoute: typeof rootRouteImport + } + '/r4': { + id: '/r4' + path: '/r4' + fullPath: '/r4' + preLoaderRoute: typeof R4RouteImport + parentRoute: typeof rootRouteImport + } + '/r5': { + id: '/r5' + path: '/r5' + fullPath: '/r5' + preLoaderRoute: typeof R5RouteImport + parentRoute: typeof rootRouteImport + } + '/r6': { + id: '/r6' + path: '/r6' + fullPath: '/r6' + preLoaderRoute: typeof R6RouteImport + parentRoute: typeof rootRouteImport + } + '/shared-a': { + id: '/shared-a' + path: '/shared-a' + fullPath: '/shared-a' + preLoaderRoute: typeof SharedARouteImport + parentRoute: typeof rootRouteImport + } + '/shared-b': { + id: '/shared-b' + path: '/shared-b' + fullPath: '/shared-b' + preLoaderRoute: typeof SharedBRouteImport + parentRoute: typeof rootRouteImport + } + '/shared-c': { + id: '/shared-c' + path: '/shared-c' + fullPath: '/shared-c' + preLoaderRoute: typeof SharedCRouteImport parentRoute: typeof rootRouteImport } } diff --git a/e2e/vue-start/start-manifest/tests/start-manifest.spec.ts b/e2e/vue-start/start-manifest/tests/start-manifest.spec.ts index 6c0f0d15ab..4d5bea0a33 100644 --- a/e2e/vue-start/start-manifest/tests/start-manifest.spec.ts +++ b/e2e/vue-start/start-manifest/tests/start-manifest.spec.ts @@ -372,24 +372,19 @@ test('shared widget CSS stays applied when navigating from static to lazy route' const widget = page.getByTestId('shared-widget') await expect(widget).toBeVisible() - expect(await getBackgroundColor('shared-widget', page)).toBe(SHARED_WIDGET_BG) - expect( - await widget.evaluate( - (element) => getComputedStyle(element).borderTopColor, - ), - ).toBe(SHARED_WIDGET_BORDER) + await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) + await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) await expect(page.getByTestId('lazy-css-static-hydrated')).toBeVisible() await page.getByTestId('nav-/lazy-css-lazy').click() await page.waitForURL('**/lazy-css-lazy') + // Both routes render `shared-widget`: wait for the destination route before + // asserting on it, so the assertions cannot match the departing widget. await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() - await expect - .poll(() => getBackgroundColor('shared-widget', page), { - timeout: 5_000, - }) - .toBe(SHARED_WIDGET_BG) + await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) + await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) }) test('shared widget CSS stays applied when navigating from lazy to static route', async ({ @@ -399,27 +394,19 @@ test('shared widget CSS stays applied when navigating from lazy to static route' await page.goto(buildUrl(baseURL!, '/lazy-css-lazy')) await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() - await expect - .poll(() => getBackgroundColor('shared-widget', page), { - timeout: 5_000, - }) - .toBe(SHARED_WIDGET_BG) + const widget = page.getByTestId('shared-widget') + await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) + await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) await page.getByTestId('nav-/lazy-css-static').click() await page.waitForURL('**/lazy-css-static') + // The URL updates before the lazy route unmounts, and both routes render + // `shared-widget`: wait for a marker only the static route renders. + await expect(page.getByTestId('lazy-css-static-hydrated')).toBeVisible() - const widget = page.getByTestId('shared-widget') await expect(widget).toBeVisible() - await expect - .poll(() => getBackgroundColor('shared-widget', page), { - timeout: 5_000, - }) - .toBe(SHARED_WIDGET_BG) - expect( - await widget.evaluate( - (element) => getComputedStyle(element).borderTopColor, - ), - ).toBe(SHARED_WIDGET_BORDER) + await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) + await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) }) test('shared widget CSS is applied on direct navigation to lazy route', async ({ @@ -431,17 +418,8 @@ test('shared widget CSS is applied on direct navigation to lazy route', async ({ const widget = page.getByTestId('shared-widget') await expect(widget).toBeVisible() - - await expect - .poll(() => getBackgroundColor('shared-widget', page), { - timeout: 5_000, - }) - .toBe(SHARED_WIDGET_BG) - expect( - await widget.evaluate( - (element) => getComputedStyle(element).borderTopColor, - ), - ).toBe(SHARED_WIDGET_BORDER) + await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) + await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) }) test('shared widget CSS persists after navigating away from lazy and back', async ({ @@ -451,19 +429,21 @@ test('shared widget CSS persists after navigating away from lazy and back', asyn await page.goto(buildUrl(baseURL!, '/lazy-css-static')) await expect(page.getByTestId('lazy-css-static-hydrated')).toBeVisible() + const widget = page.getByTestId('shared-widget') + await page.getByTestId('nav-/lazy-css-lazy').click() await page.waitForURL('**/lazy-css-lazy') - await expect(page.getByTestId('shared-widget')).toBeVisible() + await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() + await expect(widget).toBeVisible() await page.getByTestId('nav-home').click() - await page.waitForURL(/\/([^/]*)(\/)?($|\?)/) + await page.waitForURL((url) => url.pathname === '/') + await expect(page.getByTestId('home-copy')).toBeVisible() await page.getByTestId('nav-/lazy-css-lazy').click() await page.waitForURL('**/lazy-css-lazy') + await expect(page.getByTestId('lazy-css-lazy-heading')).toBeVisible() - await expect - .poll(() => getBackgroundColor('shared-widget', page), { - timeout: 5_000, - }) - .toBe(SHARED_WIDGET_BG) + await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) + await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) }) diff --git a/e2e/vue-start/streaming-ssr/package.json b/e2e/vue-start/streaming-ssr/package.json new file mode 100644 index 0000000000..382120860a --- /dev/null +++ b/e2e/vue-start/streaming-ssr/package.json @@ -0,0 +1,59 @@ +{ + "name": "tanstack-vue-start-e2e-streaming-ssr", + "private": true, + "sideEffects": false, + "type": "module", + "scripts": { + "dev": "vite dev --port 3000", + "dev:e2e": "vite dev", + "build": "vite build && tsc --noEmit", + "start": "pnpx srvx --prod -s ../client dist/server/server.js", + "preview": "vite preview", + "test:e2e": "playwright test --project=chromium", + "test:e2e:preview": "MODE=preview playwright test preview-streaming.spec.ts --project=chromium" + }, + "dependencies": { + "@tanstack/vue-query": "^5.90.0", + "@tanstack/vue-router": "workspace:^", + "@tanstack/vue-router-ssr-query": "workspace:^", + "@tanstack/vue-start": "workspace:^", + "vue": "^3.5.16" + }, + "devDependencies": { + "@playwright/test": "^1.61.0", + "@tanstack/router-e2e-utils": "workspace:^", + "@types/node": "^22.10.2", + "@vitejs/plugin-vue-jsx": "^5.1.5", + "srvx": "^1.0.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" + }, + "nx": { + "targets": { + "build": { + "inputs": [ + "buildProduction", + "^buildProduction", + "dependentTaskOutputs", + "streamingSsrTests" + ] + }, + "test:e2e": { + "inputs": [ + "default", + "^production", + "dependentTaskOutputs", + "streamingSsrTests" + ] + }, + "test:e2e:preview": { + "inputs": [ + "default", + "^production", + "streamingSsrTests" + ] + } + } + } +} diff --git a/e2e/vue-start/streaming-ssr/playwright.config.ts b/e2e/vue-start/streaming-ssr/playwright.config.ts new file mode 100644 index 0000000000..c2f3b67a0c --- /dev/null +++ b/e2e/vue-start/streaming-ssr/playwright.config.ts @@ -0,0 +1,39 @@ +import { defineConfig, devices } from '@playwright/test' +import { appServerReady } from '@tanstack/router-e2e-utils' + +const isPreview = process.env.MODE === 'preview' + +const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const baseURL = `http://localhost:${PORT}` + +const ssrCommand = `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start` +const previewCommand = `VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}` + +/** + * See https://playwright.dev/docs/test-configuration. + */ +export default defineConfig({ + testDir: './tests', + workers: 1, + + reporter: [['line']], + + use: { + /* Base URL to use in actions like `await page.goto('/')`. */ + baseURL, + }, + + webServer: { + command: isPreview ? previewCommand : ssrCommand, + wait: appServerReady, + reuseExistingServer: false, + stdout: 'pipe', + }, + + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + ], +}) diff --git a/e2e/vue-start/streaming-ssr/src/routeTree.gen.ts b/e2e/vue-start/streaming-ssr/src/routeTree.gen.ts new file mode 100644 index 0000000000..ac4c9ab156 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routeTree.gen.ts @@ -0,0 +1,282 @@ +/* eslint-disable */ + +// @ts-nocheck + +// 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 ConcurrentRouteImport } from './routes/concurrent' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as DeferredRejectionRouteImport } from './routes/deferred-rejection' +import { Route as FastSerialRouteImport } from './routes/fast-serial' +import { Route as ManyPromisesRouteImport } from './routes/many-promises' +import { Route as NestedDeferredRouteImport } from './routes/nested-deferred' +import { Route as QueryHeavyRouteImport } from './routes/query-heavy' +import { Route as SlowRenderRouteImport } from './routes/slow-render' +import { Route as StreamRouteImport } from './routes/stream' +import { Route as SyncOnlyRouteImport } from './routes/sync-only' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const ConcurrentRoute = ConcurrentRouteImport.update({ + id: '/concurrent', + path: '/concurrent', + getParentRoute: () => rootRouteImport, +} as any) +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', + getParentRoute: () => rootRouteImport, +} as any) +const DeferredRejectionRoute = DeferredRejectionRouteImport.update({ + id: '/deferred-rejection', + path: '/deferred-rejection', + getParentRoute: () => rootRouteImport, +} as any) +const FastSerialRoute = FastSerialRouteImport.update({ + id: '/fast-serial', + path: '/fast-serial', + getParentRoute: () => rootRouteImport, +} as any) +const ManyPromisesRoute = ManyPromisesRouteImport.update({ + id: '/many-promises', + path: '/many-promises', + getParentRoute: () => rootRouteImport, +} as any) +const NestedDeferredRoute = NestedDeferredRouteImport.update({ + id: '/nested-deferred', + path: '/nested-deferred', + getParentRoute: () => rootRouteImport, +} as any) +const QueryHeavyRoute = QueryHeavyRouteImport.update({ + id: '/query-heavy', + path: '/query-heavy', + getParentRoute: () => rootRouteImport, +} as any) +const SlowRenderRoute = SlowRenderRouteImport.update({ + id: '/slow-render', + path: '/slow-render', + getParentRoute: () => rootRouteImport, +} as any) +const StreamRoute = StreamRouteImport.update({ + id: '/stream', + path: '/stream', + getParentRoute: () => rootRouteImport, +} as any) +const SyncOnlyRoute = SyncOnlyRouteImport.update({ + id: '/sync-only', + path: '/sync-only', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/concurrent': typeof ConcurrentRoute + '/deferred': typeof DeferredRoute + '/deferred-rejection': typeof DeferredRejectionRoute + '/fast-serial': typeof FastSerialRoute + '/many-promises': typeof ManyPromisesRoute + '/nested-deferred': typeof NestedDeferredRoute + '/query-heavy': typeof QueryHeavyRoute + '/slow-render': typeof SlowRenderRoute + '/stream': typeof StreamRoute + '/sync-only': typeof SyncOnlyRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/concurrent': typeof ConcurrentRoute + '/deferred': typeof DeferredRoute + '/deferred-rejection': typeof DeferredRejectionRoute + '/fast-serial': typeof FastSerialRoute + '/many-promises': typeof ManyPromisesRoute + '/nested-deferred': typeof NestedDeferredRoute + '/query-heavy': typeof QueryHeavyRoute + '/slow-render': typeof SlowRenderRoute + '/stream': typeof StreamRoute + '/sync-only': typeof SyncOnlyRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/concurrent': typeof ConcurrentRoute + '/deferred': typeof DeferredRoute + '/deferred-rejection': typeof DeferredRejectionRoute + '/fast-serial': typeof FastSerialRoute + '/many-promises': typeof ManyPromisesRoute + '/nested-deferred': typeof NestedDeferredRoute + '/query-heavy': typeof QueryHeavyRoute + '/slow-render': typeof SlowRenderRoute + '/stream': typeof StreamRoute + '/sync-only': typeof SyncOnlyRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/concurrent' + | '/deferred' + | '/deferred-rejection' + | '/fast-serial' + | '/many-promises' + | '/nested-deferred' + | '/query-heavy' + | '/slow-render' + | '/stream' + | '/sync-only' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/concurrent' + | '/deferred' + | '/deferred-rejection' + | '/fast-serial' + | '/many-promises' + | '/nested-deferred' + | '/query-heavy' + | '/slow-render' + | '/stream' + | '/sync-only' + id: + | '__root__' + | '/' + | '/concurrent' + | '/deferred' + | '/deferred-rejection' + | '/fast-serial' + | '/many-promises' + | '/nested-deferred' + | '/query-heavy' + | '/slow-render' + | '/stream' + | '/sync-only' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + ConcurrentRoute: typeof ConcurrentRoute + DeferredRoute: typeof DeferredRoute + DeferredRejectionRoute: typeof DeferredRejectionRoute + FastSerialRoute: typeof FastSerialRoute + ManyPromisesRoute: typeof ManyPromisesRoute + NestedDeferredRoute: typeof NestedDeferredRoute + QueryHeavyRoute: typeof QueryHeavyRoute + SlowRenderRoute: typeof SlowRenderRoute + StreamRoute: typeof StreamRoute + SyncOnlyRoute: typeof SyncOnlyRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/concurrent': { + id: '/concurrent' + path: '/concurrent' + fullPath: '/concurrent' + preLoaderRoute: typeof ConcurrentRouteImport + parentRoute: typeof rootRouteImport + } + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/deferred-rejection': { + id: '/deferred-rejection' + path: '/deferred-rejection' + fullPath: '/deferred-rejection' + preLoaderRoute: typeof DeferredRejectionRouteImport + parentRoute: typeof rootRouteImport + } + '/fast-serial': { + id: '/fast-serial' + path: '/fast-serial' + fullPath: '/fast-serial' + preLoaderRoute: typeof FastSerialRouteImport + parentRoute: typeof rootRouteImport + } + '/many-promises': { + id: '/many-promises' + path: '/many-promises' + fullPath: '/many-promises' + preLoaderRoute: typeof ManyPromisesRouteImport + parentRoute: typeof rootRouteImport + } + '/nested-deferred': { + id: '/nested-deferred' + path: '/nested-deferred' + fullPath: '/nested-deferred' + preLoaderRoute: typeof NestedDeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/query-heavy': { + id: '/query-heavy' + path: '/query-heavy' + fullPath: '/query-heavy' + preLoaderRoute: typeof QueryHeavyRouteImport + parentRoute: typeof rootRouteImport + } + '/slow-render': { + id: '/slow-render' + path: '/slow-render' + fullPath: '/slow-render' + preLoaderRoute: typeof SlowRenderRouteImport + parentRoute: typeof rootRouteImport + } + '/stream': { + id: '/stream' + path: '/stream' + fullPath: '/stream' + preLoaderRoute: typeof StreamRouteImport + parentRoute: typeof rootRouteImport + } + '/sync-only': { + id: '/sync-only' + path: '/sync-only' + fullPath: '/sync-only' + preLoaderRoute: typeof SyncOnlyRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + ConcurrentRoute: ConcurrentRoute, + DeferredRoute: DeferredRoute, + DeferredRejectionRoute: DeferredRejectionRoute, + FastSerialRoute: FastSerialRoute, + ManyPromisesRoute: ManyPromisesRoute, + NestedDeferredRoute: NestedDeferredRoute, + QueryHeavyRoute: QueryHeavyRoute, + SlowRenderRoute: SlowRenderRoute, + StreamRoute: StreamRoute, + SyncOnlyRoute: SyncOnlyRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { createStart } from '@tanstack/vue-start' +declare module '@tanstack/vue-start' { + interface Register { + ssr: true + router: Awaited> + } +} diff --git a/e2e/vue-start/streaming-ssr/src/router.tsx b/e2e/vue-start/streaming-ssr/src/router.tsx new file mode 100644 index 0000000000..257eb8dac9 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/router.tsx @@ -0,0 +1,18 @@ +import { QueryClient } from '@tanstack/vue-query' +import { createRouter } from '@tanstack/vue-router' +import { setupRouterSsrQueryIntegration } from '@tanstack/vue-router-ssr-query' +import { routeTree } from './routeTree.gen' + +export function getRouter() { + const queryClient = new QueryClient() + const router = createRouter({ + routeTree, + context: { queryClient }, + scrollRestoration: true, + }) + setupRouterSsrQueryIntegration({ + router, + queryClient, + }) + return router +} diff --git a/e2e/vue-start/streaming-ssr/src/routes/__root.tsx b/e2e/vue-start/streaming-ssr/src/routes/__root.tsx new file mode 100644 index 0000000000..d3b3339720 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/__root.tsx @@ -0,0 +1,103 @@ +import { + Body, + HeadContent, + Html, + Link, + Outlet, + Scripts, + createRootRouteWithContext, +} from '@tanstack/vue-router' +import { defineComponent, ref } from 'vue' +import type { QueryClient } from '@tanstack/vue-query' + +export const Route = createRootRouteWithContext<{ + queryClient: QueryClient +}>()({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { title: 'Streaming SSR Tests' }, + ], + }), + component: RootComponent, +}) + +function RootComponent() { + return ( + + + + + + + + + + + + ) +} + +const HydrationCheck = defineComponent({ + setup() { + const status = ref<'pending' | 'hydrated'>('pending') + + return () => ( +
+ + + {status.value} + +
+ ) + }, +}) diff --git a/e2e/vue-start/streaming-ssr/src/routes/concurrent.tsx b/e2e/vue-start/streaming-ssr/src/routes/concurrent.tsx new file mode 100644 index 0000000000..5fed8ab517 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/concurrent.tsx @@ -0,0 +1,54 @@ +import { Await, createFileRoute } from '@tanstack/vue-router' +import { Suspense } from 'vue' +import { createConcurrentLoaderData } from '../../../../streaming-ssr-fixtures' + +export const Route = createFileRoute('/concurrent')({ + loader: async () => createConcurrentLoaderData(), + component: Concurrent, +}) + +function PromiseItem(props: { promise: Promise; testId: string }) { + return ( + + {{ + default: () => ( + ( +
{value}
+ )} + /> + ), + fallback: () => ( +
Loading...
+ ), + }} +
+ ) +} + +function Concurrent() { + const data = Route.useLoaderData() + + return ( +
+

Concurrent Resolution Test (15 promises in 3 batches)

+

Tests multiple promises resolving at the exact same instant.

+ + + + + + + + + + + + + + + +
+ ) +} diff --git a/e2e/vue-start/streaming-ssr/src/routes/deferred-rejection.tsx b/e2e/vue-start/streaming-ssr/src/routes/deferred-rejection.tsx new file mode 100644 index 0000000000..5018f9e07c --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/deferred-rejection.tsx @@ -0,0 +1,49 @@ +import { Await, createFileRoute } from '@tanstack/vue-router' +import { Suspense } from 'vue' +import { + deferredDataDelay, + deferredErrorMessage, +} from '../../../../streaming-ssr-fixtures' + +export const Route = createFileRoute('/deferred-rejection')({ + loader: async () => { + return { + deferredData: new Promise((_resolve, reject) => { + setTimeout(() => { + reject(new Error(deferredErrorMessage)) + }, deferredDataDelay) + }), + } + }, + errorComponent: ({ error }) => ( +
+ {error instanceof Error ? error.message : String(error)} +
+ ), + component: DeferredRejection, +}) + +function DeferredRejection() { + const data = Route.useLoaderData() + + return ( +
+

Deferred Rejection Test

+ + {{ + default: () => ( + ( +
{value}
+ )} + /> + ), + fallback: () => ( +
Loading deferred...
+ ), + }} +
+
+ ) +} diff --git a/e2e/vue-start/streaming-ssr/src/routes/deferred.tsx b/e2e/vue-start/streaming-ssr/src/routes/deferred.tsx new file mode 100644 index 0000000000..6a8affe1b4 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/deferred.tsx @@ -0,0 +1,100 @@ +import { Await, createFileRoute } from '@tanstack/vue-router' +import { createServerFn } from '@tanstack/vue-start' +import { Suspense } from 'vue' +import { + deferredDataDelay, + deferredDataMessage, + deferredImmediateName, + deferredServerDelay, + deferredSlowName, + delay, + makeDeferredMessage, + makeServerData, + sourceMarker, +} from '../../../../streaming-ssr-fixtures' + +const getImmediateData = createServerFn({ method: 'GET' }) + .validator((data: { name: string }) => data) + .handler(({ data }) => makeServerData(data.name)) + +const getSlowData = createServerFn({ method: 'GET' }) + .validator((data: { name: string; delay: number }) => data) + .handler(async ({ data }) => { + await delay(data.delay) + return makeServerData(data.name) + }) + +export const Route = createFileRoute('/deferred')({ + loader: async () => { + return { + deferredData: makeDeferredMessage(deferredDataMessage, deferredDataDelay), + deferredServerData: getSlowData({ + data: { name: deferredSlowName, delay: deferredServerDelay }, + }), + immediateData: await getImmediateData({ + data: { name: deferredImmediateName }, + }), + loaderSource: sourceMarker(), + } + }, + component: Deferred, +}) + +function Deferred() { + const data = Route.useLoaderData() + + return ( +
+

Deferred Data Test

+
+ Immediate: {data.value.immediateData.name} @{' '} + {data.value.immediateData.timestamp} +
+
+ Immediate source: {data.value.immediateData.source} +
+
+ Loader source: {data.value.loaderSource} +
+ + {{ + default: () => ( + ( +
+ {value.message} (source: {value.source}) +
+ )} + /> + ), + fallback: () => ( +
Loading deferred...
+ ), + }} +
+ + {{ + default: () => ( + ( +
+ Server: {value.name} @ {value.timestamp} (source:{' '} + {value.source}) +
+ )} + /> + ), + fallback: () => ( +
Loading server data...
+ ), + }} +
+
+ ) +} diff --git a/e2e/vue-start/streaming-ssr/src/routes/fast-serial.tsx b/e2e/vue-start/streaming-ssr/src/routes/fast-serial.tsx new file mode 100644 index 0000000000..ac004b041c --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/fast-serial.tsx @@ -0,0 +1,49 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { createServerFn } from '@tanstack/vue-start' +import { + fastSerialStaticData, + makeFastSerialSmallData, + sourceMarker, +} from '../../../../streaming-ssr-fixtures' + +const getSmallData = createServerFn({ method: 'GET' }).handler(() => + makeFastSerialSmallData(), +) + +export const Route = createFileRoute('/fast-serial')({ + loader: async () => { + const data = await getSmallData() + return { + serverData: data, + staticData: fastSerialStaticData, + timestamp: Date.now(), + loaderSource: sourceMarker(), + } + }, + component: FastSerial, +}) + +function FastSerial() { + const data = Route.useLoaderData() + + return ( +
+

Fast Serialization Test

+

This route tests when serialization completes before render.

+
+ Server: {data.value.serverData.value} @{' '} + {data.value.serverData.timestamp} +
+
+ Server function source: {data.value.serverData.source} +
+
+ Loader source: {data.value.loaderSource} +
+
Static: {data.value.staticData}
+
+ Loader timestamp: {data.value.timestamp} +
+
+ ) +} diff --git a/e2e/vue-start/streaming-ssr/src/routes/index.tsx b/e2e/vue-start/streaming-ssr/src/routes/index.tsx new file mode 100644 index 0000000000..0350eb5d4a --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/index.tsx @@ -0,0 +1,58 @@ +import { Link, createFileRoute } from '@tanstack/vue-router' + +export const Route = createFileRoute('/')({ + component: Index, +}) + +function Index() { + return ( +
+

Streaming SSR Test Scenarios

+

This e2e project tests various SSR streaming scenarios:

+
    +
  • + + Sync Only + {' '} + - Tests synchronous serialization with no deferred/streaming data +
  • +
  • + + Deferred Data + {' '} + - Tests deferred promises resolving after initial render +
  • +
  • + + Deferred Rejection + {' '} + - Tests deferred promise rejections render through the error boundary +
  • +
  • + + ReadableStream + {' '} + - Tests streaming data via ReadableStream +
  • +
  • + + Fast Serialization + {' '} + - Tests when serialization completes before render finishes +
  • +
  • + + Slow Render + {' '} + - Tests when render takes longer than serialization +
  • +
  • + + Nested Deferred + {' '} + - Tests nested components with deferred data +
  • +
+
+ ) +} diff --git a/e2e/vue-start/streaming-ssr/src/routes/many-promises.tsx b/e2e/vue-start/streaming-ssr/src/routes/many-promises.tsx new file mode 100644 index 0000000000..4361696107 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/many-promises.tsx @@ -0,0 +1,94 @@ +import { Await, createFileRoute } from '@tanstack/vue-router' +import { Suspense } from 'vue' +import { createManyPromises } from '../../../../streaming-ssr-fixtures' + +export const Route = createFileRoute('/many-promises')({ + loader: async () => createManyPromises(), + component: ManyPromises, +}) + +function PromiseItem(props: { + promise: Promise + testId: string + label: string +}) { + return ( + + {{ + default: () => ( + ( +
+ {props.label}: {value} +
+ )} + /> + ), + fallback: () => ( +
+ Loading {props.label}... +
+ ), + }} +
+ ) +} + +function ManyPromises() { + const data = Route.useLoaderData() + + return ( +
+

Many Promises Test (15 deferred)

+

Tests streaming with many concurrent deferred promises.

+ + + + + + + + + + + + + + + +
+ ) +} diff --git a/e2e/vue-start/streaming-ssr/src/routes/nested-deferred.tsx b/e2e/vue-start/streaming-ssr/src/routes/nested-deferred.tsx new file mode 100644 index 0000000000..b24336ec40 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/nested-deferred.tsx @@ -0,0 +1,143 @@ +import { Await, createFileRoute } from '@tanstack/vue-router' +import { createServerFn } from '@tanstack/vue-start' +import { Suspense } from 'vue' +import { + delay, + makeDeferred, + makeLevelData, + nestedLevelDelays, + nestedPlainDelay, + nestedPlainMessage, +} from '../../../../streaming-ssr-fixtures' + +const getLevel1Data = createServerFn({ method: 'GET' }).handler(async () => { + await delay(nestedLevelDelays[0]) + return makeLevelData(1) +}) + +const getLevel2Data = createServerFn({ method: 'GET' }).handler(async () => { + await delay(nestedLevelDelays[1]) + return makeLevelData(2) +}) + +const getLevel3Data = createServerFn({ method: 'GET' }).handler(async () => { + await delay(nestedLevelDelays[2]) + return makeLevelData(3) +}) + +export const Route = createFileRoute('/nested-deferred')({ + loader: async () => { + return { + level1: getLevel1Data(), + level2: getLevel2Data(), + level3: getLevel3Data(), + plainDeferred: makeDeferred(nestedPlainMessage, nestedPlainDelay), + } + }, + component: NestedDeferred, +}) + +function Level2Content(props: { + level3: Promise<{ level: number; timestamp: number }> +}) { + return ( +
+ + {{ + default: () => ( + ( +
+ Level 3: {value.level} @ {value.timestamp} +
+ )} + /> + ), + fallback: () => ( +
Loading level 3...
+ ), + }} +
+
+ ) +} + +function Level1Content(props: { + level2: Promise<{ level: number; timestamp: number }> + level3: Promise<{ level: number; timestamp: number }> +}) { + return ( +
+ + {{ + default: () => ( + ( +
+ Level 2: {value.level} @ {value.timestamp} + +
+ )} + /> + ), + fallback: () => ( +
Loading level 2...
+ ), + }} +
+
+ ) +} + +function NestedDeferred() { + const data = Route.useLoaderData() + + return ( +
+

Nested Deferred Test

+

+ Tests multiple nested deferred promises resolving at different times. +

+ + {{ + default: () => ( + ( +
{value}
+ )} + /> + ), + fallback: () => ( +
Loading plain...
+ ), + }} +
+
+ + {{ + default: () => ( + ( +
+ Level 1: {value.level} @ {value.timestamp} + +
+ )} + /> + ), + fallback: () => ( +
Loading level 1...
+ ), + }} +
+
+
+ ) +} diff --git a/e2e/vue-start/streaming-ssr/src/routes/query-heavy.tsx b/e2e/vue-start/streaming-ssr/src/routes/query-heavy.tsx new file mode 100644 index 0000000000..b22154b78e --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/query-heavy.tsx @@ -0,0 +1,168 @@ +import { queryOptions, useQuery } from '@tanstack/vue-query' +import { createFileRoute } from '@tanstack/vue-router' +import { Suspense, defineComponent } from 'vue' +import type { PropType } from 'vue' + +import { + delay, + makeQueryData, + queryHeavyItems, +} from '../../../../streaming-ssr-fixtures' +import type { QueryData } from '../../../../streaming-ssr-fixtures' + +function makeQueryOptions(item: (typeof queryHeavyItems)[number]) { + return queryOptions({ + queryKey: ['streaming-ssr-query-heavy', item.type, item.id], + queryFn: async (): Promise => { + if (item.delayMs > 0) { + await delay(item.delayMs) + } + + return makeQueryData(item) + }, + staleTime: Infinity, + }) +} + +const syncQuery1 = makeQueryOptions(queryHeavyItems[0]) +const syncQuery2 = makeQueryOptions(queryHeavyItems[1]) +const syncQuery3 = makeQueryOptions(queryHeavyItems[2]) +const fastAsyncQuery1 = makeQueryOptions(queryHeavyItems[3]) +const fastAsyncQuery2 = makeQueryOptions(queryHeavyItems[4]) +const fastAsyncQuery3 = makeQueryOptions(queryHeavyItems[5]) +const slowAsyncQuery1 = makeQueryOptions(queryHeavyItems[6]) +const slowAsyncQuery2 = makeQueryOptions(queryHeavyItems[7]) +const slowAsyncQuery3 = makeQueryOptions(queryHeavyItems[8]) + +type QueryOptions = ReturnType + +const QueryDisplay = defineComponent({ + props: { + queryOpts: { + type: Object as PropType, + required: true, + }, + testId: { + type: String, + required: true, + }, + }, + async setup(props) { + const query = useQuery(props.queryOpts) + await query.suspense() + + return () => { + const data = query.data.value + + return ( +
+ {data?.value} (source: {data?.source}) +
+ ) + } + }, +}) + +function QuerySuspense(props: { + queryOpts: QueryOptions + testId: string + fallback: string +}) { + return ( + + {{ + default: () => ( + + ), + fallback: () => ( +
{props.fallback}
+ ), + }} +
+ ) +} + +const QueryHeavy = defineComponent({ + setup() { + return () => ( +
+

Query Heavy Test (9 useQuery calls)

+

Tests multiple useQuery with mixed sync/async queryFn.

+

+ All queries should show "source: server" if SSR streaming works + correctly. +

+ +
+
+

Sync Queries (immediate)

+ + + +
+ +
+

Fast Async Queries (50-100ms)

+ + + +
+ +
+

Slow Async Queries (200-400ms)

+ + + +
+
+
+ ) + }, +}) + +export const Route = createFileRoute('/query-heavy')({ + component: QueryHeavy, +}) diff --git a/e2e/vue-start/streaming-ssr/src/routes/slow-render.tsx b/e2e/vue-start/streaming-ssr/src/routes/slow-render.tsx new file mode 100644 index 0000000000..f897e03ff0 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/slow-render.tsx @@ -0,0 +1,77 @@ +import { Await, createFileRoute } from '@tanstack/vue-router' +import { createServerFn } from '@tanstack/vue-start' +import { Suspense } from 'vue' +import { + makeDeferredMessage, + makeServerData, + slowRenderComponents, + slowRenderDeferredDelay, + slowRenderDeferredMessage, + slowRenderQuickName, + sourceMarker, +} from '../../../../streaming-ssr-fixtures' + +const getQuickData = createServerFn({ method: 'GET' }).handler(() => + makeServerData(slowRenderQuickName), +) + +function SlowComponent(props: { data: string; index: number }) { + const startTime = Date.now() + while (Date.now() - startTime < 100) { + // Simulate slow render work. + } + return
{props.data}
+} + +export const Route = createFileRoute('/slow-render')({ + loader: async () => { + const quickData = await getQuickData() + return { + quickData, + deferredData: makeDeferredMessage( + slowRenderDeferredMessage, + slowRenderDeferredDelay, + ), + loaderSource: sourceMarker(), + } + }, + component: SlowRender, +}) + +function SlowRender() { + const data = Route.useLoaderData() + + return ( +
+

Slow Render Test

+

Tests when render takes longer than serialization.

+
+ Quick: {data.value.quickData.name} @ {data.value.quickData.timestamp} +
+
+ Quick data source: {data.value.quickData.source} +
+
+ Loader source: {data.value.loaderSource} +
+ + {{ + default: () => ( + ( +
+ {value.message} (source: {value.source}) +
+ )} + /> + ), + fallback: () =>
Loading...
, + }} +
+ {slowRenderComponents.map((data, index) => ( + + ))} +
+ ) +} diff --git a/e2e/vue-start/streaming-ssr/src/routes/stream.tsx b/e2e/vue-start/streaming-ssr/src/routes/stream.tsx new file mode 100644 index 0000000000..31368bedfc --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/stream.tsx @@ -0,0 +1,171 @@ +import { Await, createFileRoute, useRouter } from '@tanstack/vue-router' +import { + Suspense, + defineComponent, + onMounted, + onUnmounted, + ref, + watch, +} from 'vue' +import { + createChunkStream, + createStreamPromise, +} from '../../../../streaming-ssr-fixtures' + +export const Route = createFileRoute('/stream')({ + component: () => , + loader() { + return { + promise: createStreamPromise(), + stream: createChunkStream(), + } + }, +}) + +const decoder = new TextDecoder('utf-8') + +const StreamRoute = defineComponent({ + setup() { + const data = Route.useLoaderData() + const router = useRouter() + const streamData = ref>([]) + const streamComplete = ref(false) + const streamReadCount = ref(0) + let reader: ReadableStreamDefaultReader | undefined + let mounted = false + let activeStream: ReadableStream | undefined + let reading = false + let readTimer: ReturnType | undefined + + function clearReadTimer() { + if (readTimer) { + clearTimeout(readTimer) + readTimer = undefined + } + } + + function scheduleRead(delay = 0) { + if (!mounted || reading) { + return + } + + clearReadTimer() + readTimer = setTimeout(() => { + readTimer = undefined + void readStream() + }, delay) + } + + async function readStream() { + const stream = data.value.stream + if (!mounted || reading || activeStream === stream) { + return + } + + if (stream.locked) { + scheduleRead(10) + return + } + + streamData.value = [] + streamComplete.value = false + + let activeReader: ReadableStreamDefaultReader | undefined + + try { + const currentReader = stream.getReader() + activeReader = currentReader + reader = currentReader + activeStream = stream + reading = true + streamReadCount.value++ + + let chunk + while (!(chunk = await currentReader.read()).done) { + let value = chunk.value + if (typeof value !== 'string') { + value = decoder.decode(value, { stream: !chunk.done }) + } + streamData.value = [...streamData.value, value] + } + streamComplete.value = true + } catch (e) { + const message = String(e) + if (e instanceof TypeError && message.includes('locked')) { + activeStream = undefined + scheduleRead(10) + } else if (!(e instanceof TypeError && message.includes('cancelled'))) { + console.error('Stream error:', e) + } + } finally { + activeReader?.releaseLock() + if (reader === activeReader) { + reader = undefined + } + reading = false + if (activeStream !== data.value.stream) { + scheduleRead() + } + } + } + + onMounted(() => { + mounted = true + scheduleRead() + }) + watch( + () => data.value.stream, + () => { + activeStream = undefined + scheduleRead() + }, + ) + onUnmounted(() => { + mounted = false + clearReadTimer() + reader?.cancel().catch(() => {}) + reader = undefined + }) + + return () => ( +
+

ReadableStream Test

+ + + {{ + default: () => ( + ( +
{value}
+ )} + /> + ), + fallback: () => ( +
Loading promise...
+ ), + }} +
+
+

Stream chunks:

+
+ {streamData.value.map((chunk, i) => ( +
{chunk}
+ ))} +
+ {streamComplete.value && ( +
Stream complete!
+ )} +
+
+ ) + }, +}) diff --git a/e2e/vue-start/streaming-ssr/src/routes/sync-only.tsx b/e2e/vue-start/streaming-ssr/src/routes/sync-only.tsx new file mode 100644 index 0000000000..bbad10839e --- /dev/null +++ b/e2e/vue-start/streaming-ssr/src/routes/sync-only.tsx @@ -0,0 +1,25 @@ +import { createFileRoute } from '@tanstack/vue-router' +import { makeSyncOnlyData } from '../../../../streaming-ssr-fixtures' + +export const Route = createFileRoute('/sync-only')({ + loader: async () => makeSyncOnlyData(), + component: SyncOnly, +}) + +function SyncOnly() { + const data = Route.useLoaderData() + + return ( +
+

Synchronous Serialization Test

+

{data.value.message}

+

Loaded at: {data.value.timestamp}

+

Source: {data.value.source}

+
    + {data.value.items.map((item: string) => ( +
  • {item}
  • + ))} +
+
+ ) +} diff --git a/e2e/vue-start/streaming-ssr/tests/client-navigation.spec.ts b/e2e/vue-start/streaming-ssr/tests/client-navigation.spec.ts new file mode 100644 index 0000000000..8b9b3a8dcc --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/client-navigation.spec.ts @@ -0,0 +1 @@ +import '../../../streaming-ssr-specs/client-navigation' diff --git a/e2e/vue-start/streaming-ssr/tests/concurrent.spec.ts b/e2e/vue-start/streaming-ssr/tests/concurrent.spec.ts new file mode 100644 index 0000000000..8625473a58 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/concurrent.spec.ts @@ -0,0 +1 @@ +import '../../../streaming-ssr-specs/concurrent' diff --git a/e2e/vue-start/streaming-ssr/tests/deferred-rejection.spec.ts b/e2e/vue-start/streaming-ssr/tests/deferred-rejection.spec.ts new file mode 100644 index 0000000000..355b5019bc --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/deferred-rejection.spec.ts @@ -0,0 +1 @@ +import '../../../streaming-ssr-specs/deferred-rejection' diff --git a/e2e/vue-start/streaming-ssr/tests/deferred.spec.ts b/e2e/vue-start/streaming-ssr/tests/deferred.spec.ts new file mode 100644 index 0000000000..3145897d7b --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/deferred.spec.ts @@ -0,0 +1 @@ +import '../../../streaming-ssr-specs/deferred' diff --git a/e2e/vue-start/streaming-ssr/tests/fast-serial.spec.ts b/e2e/vue-start/streaming-ssr/tests/fast-serial.spec.ts new file mode 100644 index 0000000000..95df0555e2 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/fast-serial.spec.ts @@ -0,0 +1 @@ +import '../../../streaming-ssr-specs/fast-serial' diff --git a/e2e/vue-start/streaming-ssr/tests/home.spec.ts b/e2e/vue-start/streaming-ssr/tests/home.spec.ts new file mode 100644 index 0000000000..5d49d34a56 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/home.spec.ts @@ -0,0 +1 @@ +import '../../../streaming-ssr-specs/home' diff --git a/e2e/vue-start/streaming-ssr/tests/many-promises.spec.ts b/e2e/vue-start/streaming-ssr/tests/many-promises.spec.ts new file mode 100644 index 0000000000..b747bd7d0a --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/many-promises.spec.ts @@ -0,0 +1 @@ +import '../../../streaming-ssr-specs/many-promises' diff --git a/e2e/vue-start/streaming-ssr/tests/nested-deferred.spec.ts b/e2e/vue-start/streaming-ssr/tests/nested-deferred.spec.ts new file mode 100644 index 0000000000..8df20a8a95 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/nested-deferred.spec.ts @@ -0,0 +1 @@ +import '../../../streaming-ssr-specs/nested-deferred' diff --git a/e2e/vue-start/streaming-ssr/tests/preview-streaming.spec.ts b/e2e/vue-start/streaming-ssr/tests/preview-streaming.spec.ts new file mode 100644 index 0000000000..34241cfbaa --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/preview-streaming.spec.ts @@ -0,0 +1 @@ +import '../../../streaming-ssr-specs/preview-streaming' diff --git a/e2e/vue-start/streaming-ssr/tests/query-heavy.spec.ts b/e2e/vue-start/streaming-ssr/tests/query-heavy.spec.ts new file mode 100644 index 0000000000..d15c092f6e --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/query-heavy.spec.ts @@ -0,0 +1 @@ +import '../../../streaming-ssr-specs/query-heavy' diff --git a/e2e/vue-start/streaming-ssr/tests/slow-render.spec.ts b/e2e/vue-start/streaming-ssr/tests/slow-render.spec.ts new file mode 100644 index 0000000000..0d5a87363f --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/slow-render.spec.ts @@ -0,0 +1 @@ +import '../../../streaming-ssr-specs/slow-render' diff --git a/e2e/vue-start/streaming-ssr/tests/stream.spec.ts b/e2e/vue-start/streaming-ssr/tests/stream.spec.ts new file mode 100644 index 0000000000..9dfc6820ad --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/stream.spec.ts @@ -0,0 +1,22 @@ +import { expect, testWithHydration } from '../../../streaming-ssr-assertions' +import '../../../streaming-ssr-specs/stream' + +testWithHydration( + 'reads a replacement stream after an active read', + async ({ page }) => { + await page.goto('/') + await page.waitForLoadState('networkidle') + await page.getByRole('link', { name: 'Stream' }).first().click() + await expect(page.getByTestId('stream-chunk-0')).toHaveText('chunk-0') + await expect(page.getByTestId('stream-complete')).toHaveCount(0) + + await page.getByTestId('refresh-stream').click() + + const streamData = page.getByTestId('stream-data') + await expect(streamData).toHaveAttribute('data-read-count', '2') + await expect(page.getByTestId('stream-complete')).toBeVisible() + await expect( + streamData.locator('[data-testid^="stream-chunk-"]'), + ).toHaveText(['chunk-0', 'chunk-1', 'chunk-2', 'chunk-3', 'chunk-4']) + }, +) diff --git a/e2e/vue-start/streaming-ssr/tests/sync-only.spec.ts b/e2e/vue-start/streaming-ssr/tests/sync-only.spec.ts new file mode 100644 index 0000000000..b25572f615 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tests/sync-only.spec.ts @@ -0,0 +1,7 @@ +import '../../../streaming-ssr-specs/sync-only' +import { expect, test } from '../../../streaming-ssr-assertions' + +test('Vue renders an unwrapped document root', async ({ request }) => { + const response = await request.get('/sync-only') + expect(await response.text()).toMatch(/^)/) +}) diff --git a/e2e/vue-start/streaming-ssr/tsconfig.json b/e2e/vue-start/streaming-ssr/tsconfig.json new file mode 100644 index 0000000000..390dad84c0 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/tsconfig.json @@ -0,0 +1,22 @@ +{ + "include": ["**/*.ts", "**/*.tsx"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "preserve", + "jsxImportSource": "vue", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["DOM", "DOM.Iterable", "ES2022"], + "isolatedModules": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "target": "ES2022", + "allowJs": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "~/*": ["./src/*"] + }, + "noEmit": true + } +} diff --git a/e2e/vue-start/streaming-ssr/vite.config.ts b/e2e/vue-start/streaming-ssr/vite.config.ts new file mode 100644 index 0000000000..6519ec54c8 --- /dev/null +++ b/e2e/vue-start/streaming-ssr/vite.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from 'vite' +import { tanstackStart } from '@tanstack/vue-start/plugin/vite' +import vueJsx from '@vitejs/plugin-vue-jsx' + +export default defineConfig({ + server: { + port: 3000, + }, + plugins: [tanstackStart(), vueJsx()], +}) diff --git a/e2e/vue-start/virtual-routes/package.json b/e2e/vue-start/virtual-routes/package.json index 6c2011e1ea..90f09ce911 100644 --- a/e2e/vue-start/virtual-routes/package.json +++ b/e2e/vue-start/virtual-routes/package.json @@ -9,14 +9,14 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/virtual-file-routes": "workspace:^", "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "vue": "^3.5.25", "zod": "^4.4.3" @@ -29,9 +29,10 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/e2e/vue-start/virtual-routes/playwright.config.ts b/e2e/vue-start/virtual-routes/playwright.config.ts index b0c365f8bd..1862174905 100644 --- a/e2e/vue-start/virtual-routes/playwright.config.ts +++ b/e2e/vue-start/virtual-routes/playwright.config.ts @@ -1,12 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { - getDummyServerPort, - getTestServerPort, -} from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) -const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -18,19 +13,19 @@ export default defineConfig({ reporter: [['line']], - globalSetup: './tests/setup/global.setup.ts', - globalTeardown: './tests/setup/global.teardown.ts', - use: { /* Base URL to use in actions like `await page.goto('/')`. */ baseURL, }, webServer: { - command: `VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} pnpm build && VITE_NODE_ENV="test" VITE_EXTERNAL_PORT=${EXTERNAL_PORT} VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `pnpm build && PORT=${PORT} pnpm start`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', + env: { + NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, + }, }, projects: [ diff --git a/e2e/vue-start/virtual-routes/src/posts.tsx b/e2e/vue-start/virtual-routes/src/posts.tsx index 1b4c92b41d..f7a1941605 100644 --- a/e2e/vue-start/virtual-routes/src/posts.tsx +++ b/e2e/vue-start/virtual-routes/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-start/virtual-routes/src/routeTree.gen.ts b/e2e/vue-start/virtual-routes/src/routeTree.gen.ts index 94664b2e5b..1a1bc2d27b 100644 --- a/e2e/vue-start/virtual-routes/src/routeTree.gen.ts +++ b/e2e/vue-start/virtual-routes/src/routeTree.gen.ts @@ -9,23 +9,27 @@ // 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 pipeRouteImport } from './routes/pipe' -import { Route as postsPostsRouteImport } from './routes/posts/posts' -import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' import { Route as homeRouteImport } from './routes/home' -import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' +import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' +import { Route as postsPostsRouteImport } from './routes/posts/posts' +import { Route as pipeRouteImport } from './routes/pipe' import { Route as layoutSecondLayoutRouteImport } from './routes/layout/second-layout' -import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' import { Route as ClassicHelloRouteRouteImport } from './routes/file-based-subtree/hello/route' +import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' +import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' import { Route as ClassicHelloIndexRouteImport } from './routes/file-based-subtree/hello/index' -import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' import { Route as ClassicHelloUniverseRouteImport } from './routes/file-based-subtree/hello/universe' -import { Route as bRouteImport } from './routes/b' +import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' import { Route as aRouteImport } from './routes/a' +import { Route as bRouteImport } from './routes/b' -const pipeRoute = pipeRouteImport.update({ - id: '/special|pipe', - path: '/special|pipe', +const homeRoute = homeRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const layoutFirstLayoutRoute = layoutFirstLayoutRouteImport.update({ + id: '/_first', getParentRoute: () => rootRouteImport, } as any) const postsPostsRoute = postsPostsRouteImport.update({ @@ -33,59 +37,55 @@ const postsPostsRoute = postsPostsRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const layoutFirstLayoutRoute = layoutFirstLayoutRouteImport.update({ - id: '/_first', +const pipeRoute = pipeRouteImport.update({ + id: '/special|pipe', + path: '/special|pipe', getParentRoute: () => rootRouteImport, } as any) -const homeRoute = homeRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const postsPostsDetailRoute = postsPostsDetailRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => postsPostsRoute, -} as any) const layoutSecondLayoutRoute = layoutSecondLayoutRouteImport.update({ id: '/_second-layout', getParentRoute: () => layoutFirstLayoutRoute, } as any) -const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => postsPostsRoute, -} as any) const ClassicHelloRouteRoute = ClassicHelloRouteRouteImport.update({ id: '/classic/hello', path: '/classic/hello', getParentRoute: () => rootRouteImport, } as any) +const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => postsPostsRoute, +} as any) +const postsPostsDetailRoute = postsPostsDetailRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => postsPostsRoute, +} as any) const ClassicHelloIndexRoute = ClassicHelloIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ - id: '/world', - path: '/world', - getParentRoute: () => ClassicHelloRouteRoute, -} as any) const ClassicHelloUniverseRoute = ClassicHelloUniverseRouteImport.update({ id: '/universe', path: '/universe', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const bRoute = bRouteImport.update({ - id: '/route-without-file/layout-b', - path: '/route-without-file/layout-b', - getParentRoute: () => layoutSecondLayoutRoute, +const ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ + id: '/world', + path: '/world', + getParentRoute: () => ClassicHelloRouteRoute, } as any) const aRoute = aRouteImport.update({ id: '/route-without-file/layout-a', path: '/route-without-file/layout-a', getParentRoute: () => layoutSecondLayoutRoute, } as any) +const bRoute = bRouteImport.update({ + id: '/route-without-file/layout-b', + path: '/route-without-file/layout-b', + getParentRoute: () => layoutSecondLayoutRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof homeRoute @@ -179,18 +179,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/special|pipe': { - id: '/special|pipe' - path: '/special|pipe' - fullPath: '/special|pipe' - preLoaderRoute: typeof pipeRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof postsPostsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof homeRouteImport parentRoute: typeof rootRouteImport } '/_first': { @@ -200,19 +193,19 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof layoutFirstLayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof homeRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof postsPostsRouteImport parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof postsPostsDetailRouteImport - parentRoute: typeof postsPostsRoute + '/special|pipe': { + id: '/special|pipe' + path: '/special|pipe' + fullPath: '/special|pipe' + preLoaderRoute: typeof pipeRouteImport + parentRoute: typeof rootRouteImport } '/_first/_second-layout': { id: '/_first/_second-layout' @@ -221,13 +214,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof layoutSecondLayoutRouteImport parentRoute: typeof layoutFirstLayoutRoute } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof postsPostsHomeRouteImport - parentRoute: typeof postsPostsRoute - } '/classic/hello': { id: '/classic/hello' path: '/classic/hello' @@ -235,6 +221,20 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ClassicHelloRouteRouteImport parentRoute: typeof rootRouteImport } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof postsPostsHomeRouteImport + parentRoute: typeof postsPostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof postsPostsDetailRouteImport + parentRoute: typeof postsPostsRoute + } '/classic/hello/': { id: '/classic/hello/' path: '/' @@ -242,13 +242,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ClassicHelloIndexRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/classic/hello/world': { - id: '/classic/hello/world' - path: '/world' - fullPath: '/classic/hello/world' - preLoaderRoute: typeof ClassicHelloWorldRouteImport - parentRoute: typeof ClassicHelloRouteRoute - } '/classic/hello/universe': { id: '/classic/hello/universe' path: '/universe' @@ -256,12 +249,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ClassicHelloUniverseRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/_first/_second-layout/route-without-file/layout-b': { - id: '/_first/_second-layout/route-without-file/layout-b' - path: '/route-without-file/layout-b' - fullPath: '/route-without-file/layout-b' - preLoaderRoute: typeof bRouteImport - parentRoute: typeof layoutSecondLayoutRoute + '/classic/hello/world': { + id: '/classic/hello/world' + path: '/world' + fullPath: '/classic/hello/world' + preLoaderRoute: typeof ClassicHelloWorldRouteImport + parentRoute: typeof ClassicHelloRouteRoute } '/_first/_second-layout/route-without-file/layout-a': { id: '/_first/_second-layout/route-without-file/layout-a' @@ -270,6 +263,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof aRouteImport parentRoute: typeof layoutSecondLayoutRoute } + '/_first/_second-layout/route-without-file/layout-b': { + id: '/_first/_second-layout/route-without-file/layout-b' + path: '/route-without-file/layout-b' + fullPath: '/route-without-file/layout-b' + preLoaderRoute: typeof bRouteImport + parentRoute: typeof layoutSecondLayoutRoute + } } } diff --git a/e2e/vue-start/virtual-routes/src/routes/posts/posts-detail.tsx b/e2e/vue-start/virtual-routes/src/routes/posts/posts-detail.tsx index 5086e3ad88..4bc3824f62 100644 --- a/e2e/vue-start/virtual-routes/src/routes/posts/posts-detail.tsx +++ b/e2e/vue-start/virtual-routes/src/routes/posts/posts-detail.tsx @@ -1,7 +1,20 @@ +import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import { fetchPost } from '../../posts' import type { ErrorComponentProps } from '@tanstack/vue-router' +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + return () => ( +
+

{post.value.title}

+
{post.value.body}
+
+ ) + }, +}) + export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), errorComponent: PostErrorComponent, @@ -14,14 +27,3 @@ export const Route = createFileRoute('/posts/$postId')({ function PostErrorComponent({ error }: ErrorComponentProps) { return } - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

{post.value.title}

-
{post.value.body}
-
- ) -} diff --git a/e2e/vue-start/virtual-routes/src/routes/posts/posts.tsx b/e2e/vue-start/virtual-routes/src/routes/posts/posts.tsx index f56d6550a6..dd380aa353 100644 --- a/e2e/vue-start/virtual-routes/src/routes/posts/posts.tsx +++ b/e2e/vue-start/virtual-routes/src/routes/posts/posts.tsx @@ -1,37 +1,39 @@ +import { defineComponent } from 'vue' import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' import { fetchPosts } from '../../posts' +const PostsComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + return () => ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ))} +
+
+ +
+ ) + }, +}) + export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ))} -
-
- -
- ) -} diff --git a/e2e/vue-start/virtual-routes/src/utils/posts.tsx b/e2e/vue-start/virtual-routes/src/utils/posts.tsx index 66cb298f83..11d80d08b5 100644 --- a/e2e/vue-start/virtual-routes/src/utils/posts.tsx +++ b/e2e/vue-start/virtual-routes/src/utils/posts.tsx @@ -8,11 +8,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = createServerFn({ method: 'GET' }) .validator((postId: string) => postId) diff --git a/e2e/vue-start/virtual-routes/src/utils/users.tsx b/e2e/vue-start/virtual-routes/src/utils/users.tsx index 46be4b1580..7ba645b383 100644 --- a/e2e/vue-start/virtual-routes/src/utils/users.tsx +++ b/e2e/vue-start/virtual-routes/src/utils/users.tsx @@ -3,7 +3,3 @@ export type User = { name: string email: string } - -const PORT = process.env.VITE_SERVER_PORT || 3000 - -export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/vue-start/virtual-routes/tests/app.spec.ts b/e2e/vue-start/virtual-routes/tests/app.spec.ts index 3182febfa0..e9db98e3f3 100644 --- a/e2e/vue-start/virtual-routes/tests/app.spec.ts +++ b/e2e/vue-start/virtual-routes/tests/app.spec.ts @@ -1,4 +1,5 @@ -import { expect, test } from '@playwright/test' +import { expect } from '@playwright/test' +import { apiTest as test } from '@tanstack/router-e2e-utils' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/vue-start/virtual-routes/tests/setup/global.setup.ts b/e2e/vue-start/virtual-routes/tests/setup/global.setup.ts deleted file mode 100644 index 3593d10ab9..0000000000 --- a/e2e/vue-start/virtual-routes/tests/setup/global.setup.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function setup() { - await e2eStartDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/virtual-routes/tests/setup/global.teardown.ts b/e2e/vue-start/virtual-routes/tests/setup/global.teardown.ts deleted file mode 100644 index 62fd79911c..0000000000 --- a/e2e/vue-start/virtual-routes/tests/setup/global.teardown.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' -import packageJson from '../../package.json' with { type: 'json' } - -export default async function teardown() { - await e2eStopDummyServer(packageJson.name) -} diff --git a/e2e/vue-start/website/package.json b/e2e/vue-start/website/package.json index bfbb042de5..6c30b1500f 100644 --- a/e2e/vue-start/website/package.json +++ b/e2e/vue-start/website/package.json @@ -9,13 +9,13 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "pnpx srvx --prod -s ../client dist/server/server.js", - "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" + "test:e2e": "playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "vue": "^3.5.25", "zod": "^4.4.3" @@ -27,9 +27,10 @@ "@types/node": "^22.10.2", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/e2e/vue-start/website/playwright.config.ts b/e2e/vue-start/website/playwright.config.ts index f6dd61ba6c..e6b92ce385 100644 --- a/e2e/vue-start/website/playwright.config.ts +++ b/e2e/vue-start/website/playwright.config.ts @@ -1,8 +1,7 @@ import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } +import { appServerReady } from '@tanstack/router-e2e-utils' -const PORT = await getTestServerPort(packageJson.name) +const PORT = Number(process.env.E2E_APP_PORT ?? 0) const baseURL = `http://localhost:${PORT}` /** @@ -21,8 +20,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - url: baseURL, - reuseExistingServer: !process.env.CI, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, diff --git a/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx b/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx index d06f4a948b..77c03c5afa 100644 --- a/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx +++ b/e2e/vue-start/website/src/components/DefaultCatchBoundary.tsx @@ -1,3 +1,5 @@ +import { defineComponent } from 'vue' +import type { PropType } from 'vue' import { ErrorComponent, Link, @@ -6,46 +8,54 @@ import { } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' -export function DefaultCatchBoundary({ error }: ErrorComponentProps) { - const router = useRouter() - const isRoot = useLocation({ - select: (location) => location.pathname === '/', - }) - - console.error(error) - - return ( -
- -
- - {isRoot.value ? ( - - Home - - ) : ( - { - e.preventDefault() - window.history.back() - }} - > - Go Back - - )} -
-
- ) -} +export const DefaultCatchBoundary = defineComponent({ + props: { + error: { + type: Object as PropType, + required: true, + }, + }, + setup(props) { + const router = useRouter() + const isRoot = useLocation({ + select: (location) => location.pathname === '/', + }) + return () => { + console.error(props.error) + return ( +
+ +
+ + {isRoot.value ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) + } + }, +}) diff --git a/e2e/vue-start/website/src/routeTree.gen.ts b/e2e/vue-start/website/src/routeTree.gen.ts index e7b58aae2a..0909725a4b 100644 --- a/e2e/vue-start/website/src/routeTree.gen.ts +++ b/e2e/vue-start/website/src/routeTree.gen.ts @@ -10,11 +10,11 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as LibraryRouteImport } from './routes/_library' -import { Route as LibraryIndexRouteImport } from './routes/_library.index' import { Route as ProjectIndexRouteImport } from './routes/$project.index' +import { Route as LibraryIndexRouteImport } from './routes/_library.index' import { Route as LibraryProjectRouteImport } from './routes/_library.$project' -import { Route as LibraryProjectVersionIndexRouteImport } from './routes/_library.$project.$version.index' import { Route as ProjectVersionDocsIndexRouteImport } from './routes/$project.$version.docs.index' +import { Route as LibraryProjectVersionIndexRouteImport } from './routes/_library.$project.$version.index' import { Route as ProjectVersionDocsFrameworkFrameworkRouteImport } from './routes/$project.$version.docs.framework.$framework' import { Route as ProjectVersionDocsFrameworkFrameworkIndexRouteImport } from './routes/$project.$version.docs.framework.$framework.index' import { Route as ProjectVersionDocsFrameworkFrameworkSplatRouteImport } from './routes/$project.$version.docs.framework.$framework.$' @@ -24,32 +24,32 @@ const LibraryRoute = LibraryRouteImport.update({ id: '/_library', getParentRoute: () => rootRouteImport, } as any) -const LibraryIndexRoute = LibraryIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => LibraryRoute, -} as any) const ProjectIndexRoute = ProjectIndexRouteImport.update({ id: '/$project/', path: '/$project/', getParentRoute: () => rootRouteImport, } as any) +const LibraryIndexRoute = LibraryIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => LibraryRoute, +} as any) const LibraryProjectRoute = LibraryProjectRouteImport.update({ id: '/$project', path: '/$project', getParentRoute: () => LibraryRoute, } as any) +const ProjectVersionDocsIndexRoute = ProjectVersionDocsIndexRouteImport.update({ + id: '/$project/$version/docs/', + path: '/$project/$version/docs/', + getParentRoute: () => rootRouteImport, +} as any) const LibraryProjectVersionIndexRoute = LibraryProjectVersionIndexRouteImport.update({ id: '/$version/', path: '/$version/', getParentRoute: () => LibraryProjectRoute, } as any) -const ProjectVersionDocsIndexRoute = ProjectVersionDocsIndexRouteImport.update({ - id: '/$project/$version/docs/', - path: '/$project/$version/docs/', - getParentRoute: () => rootRouteImport, -} as any) const ProjectVersionDocsFrameworkFrameworkRoute = ProjectVersionDocsFrameworkFrameworkRouteImport.update({ id: '/$project/$version/docs/framework/$framework', @@ -159,13 +159,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LibraryRouteImport parentRoute: typeof rootRouteImport } - '/_library/': { - id: '/_library/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof LibraryIndexRouteImport - parentRoute: typeof LibraryRoute - } '/$project/': { id: '/$project/' path: '/$project' @@ -173,6 +166,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ProjectIndexRouteImport parentRoute: typeof rootRouteImport } + '/_library/': { + id: '/_library/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof LibraryIndexRouteImport + parentRoute: typeof LibraryRoute + } '/_library/$project': { id: '/_library/$project' path: '/$project' @@ -180,13 +180,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LibraryProjectRouteImport parentRoute: typeof LibraryRoute } - '/_library/$project/$version/': { - id: '/_library/$project/$version/' - path: '/$version' - fullPath: '/$project/$version/' - preLoaderRoute: typeof LibraryProjectVersionIndexRouteImport - parentRoute: typeof LibraryProjectRoute - } '/$project/$version/docs/': { id: '/$project/$version/docs/' path: '/$project/$version/docs' @@ -194,6 +187,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ProjectVersionDocsIndexRouteImport parentRoute: typeof rootRouteImport } + '/_library/$project/$version/': { + id: '/_library/$project/$version/' + path: '/$version' + fullPath: '/$project/$version/' + preLoaderRoute: typeof LibraryProjectVersionIndexRouteImport + parentRoute: typeof LibraryProjectRoute + } '/$project/$version/docs/framework/$framework': { id: '/$project/$version/docs/framework/$framework' path: '/$project/$version/docs/framework/$framework' diff --git a/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.$.tsx b/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.$.tsx index f56c911b88..1d9173f200 100644 --- a/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.$.tsx +++ b/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.$.tsx @@ -1,9 +1,27 @@ +import { defineComponent } from 'vue' import { ErrorComponent, createFileRoute } from '@tanstack/vue-router' import type { ErrorComponentProps } from '@tanstack/vue-router' import { NotFound } from '~/components/NotFound' import { getDocument } from '~/server/document' import { capitalize, seo } from '~/utils/seo' +const Page = defineComponent({ + setup() { + const post = Route.useLoaderData() + return () => ( +
+

+ {post.value.title} +

+
{post.value.content}
+
+ ) + }, +}) + export const Route = createFileRoute( '/$project/$version/docs/framework/$framework/$', )({ @@ -26,19 +44,3 @@ export const Route = createFileRoute( function PostErrorComponent({ error }: ErrorComponentProps) { return } - -function Page() { - const post = Route.useLoaderData() - - return ( -
-

- {post.value.title} -

-
{post.value.content}
-
- ) -} diff --git a/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.examples.$.tsx b/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.examples.$.tsx index 97f8fdd49a..1ca9e97cbe 100644 --- a/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.examples.$.tsx +++ b/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.examples.$.tsx @@ -1,7 +1,24 @@ +import { defineComponent } from 'vue' import { createFileRoute } from '@tanstack/vue-router' import { NotFound } from '~/components/NotFound' import { capitalize, seo } from '~/utils/seo' +const Page = defineComponent({ + setup() { + const params = Route.useParams() + return () => ( +
+

+ {params.value._splat} example +

+
+ ) + }, +}) + export const Route = createFileRoute( '/$project/$version/docs/framework/$framework/examples/$', )({ @@ -15,18 +32,3 @@ export const Route = createFileRoute( return Example not found }, }) - -function Page() { - const params = Route.useParams() - - return ( -
-

- {params.value._splat} example -

-
- ) -} diff --git a/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.tsx b/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.tsx index 1b422b2ea0..e1c57491aa 100644 --- a/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.tsx +++ b/e2e/vue-start/website/src/routes/$project.$version.docs.framework.$framework.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { Link, Outlet, @@ -7,6 +8,108 @@ import { import { getDocumentHeads } from '~/server/document' import { getProject } from '~/server/projects' +const Page = defineComponent({ + setup() { + const project = Route.useLoaderData({ select: (s) => s.library }) + const documents = Route.useLoaderData({ select: (s) => s.documents }) + const pathname = useLocation({ select: (s) => s.pathname }) + return () => ( +
+ +
+

+ {pathname.value} +

+ +
+
+ ) + }, +}) + export const Route = createFileRoute( '/$project/$version/docs/framework/$framework', )({ @@ -20,104 +123,3 @@ export const Route = createFileRoute( }, component: Page, }) - -function Page() { - const project = Route.useLoaderData({ select: (s) => s.library }) - const documents = Route.useLoaderData({ select: (s) => s.documents }) - const pathname = useLocation({ select: (s) => s.pathname }) - - return ( -
- -
-

- {pathname.value} -

- -
-
- ) -} diff --git a/e2e/vue-start/website/src/routes/__root.tsx b/e2e/vue-start/website/src/routes/__root.tsx index 64228c166e..744cac4b11 100644 --- a/e2e/vue-start/website/src/routes/__root.tsx +++ b/e2e/vue-start/website/src/routes/__root.tsx @@ -51,7 +51,11 @@ export const Route = createRootRoute({ ], }), errorComponent: (props) => { - return

{props.error.stack}

+ return ( +

+ {props.error instanceof Error ? props.error.stack : String(props.error)} +

+ ) }, notFoundComponent: () => , component: RootComponent, diff --git a/e2e/vue-start/website/src/routes/_library.$project.$version.index.tsx b/e2e/vue-start/website/src/routes/_library.$project.$version.index.tsx index ed8e4d0bb4..d6c9b00671 100644 --- a/e2e/vue-start/website/src/routes/_library.$project.$version.index.tsx +++ b/e2e/vue-start/website/src/routes/_library.$project.$version.index.tsx @@ -1,23 +1,31 @@ +import { defineComponent } from 'vue' import { Link, createFileRoute } from '@tanstack/vue-router' +const Page = defineComponent({ + setup() { + const params = Route.useParams() + return () => ( +
+

+ {params.value.project} landing page +

+

+ version: {params.value.version} +

+

+ + Get started with our documentation. + +

+
+ ) + }, +}) + export const Route = createFileRoute('/_library/$project/$version/')({ component: Page, }) - -function Page() { - const params = Route.useParams() - - return ( -
-

- {params.value.project} landing page -

-

version: {params.value.version}

-

- - Get started with our documentation. - -

-
- ) -} diff --git a/e2e/vue-start/website/src/routes/_library.tsx b/e2e/vue-start/website/src/routes/_library.tsx index fcbeaa35d0..b52198950d 100644 --- a/e2e/vue-start/website/src/routes/_library.tsx +++ b/e2e/vue-start/website/src/routes/_library.tsx @@ -1,3 +1,4 @@ +import { defineComponent } from 'vue' import { Link, Outlet, @@ -6,6 +7,53 @@ import { } from '@tanstack/vue-router' import { getProjects } from '~/server/projects' +const Layout = defineComponent({ + setup() { + const loaderData = Route.useLoaderData() + const pathname = useLocation({ select: (s) => s.pathname }) + return () => ( +
+ +
+

+ {pathname.value} +

+ +
+
+ ) + }, +}) + export const Route = createFileRoute('/_library')({ loader: async () => { const projects = await getProjects() @@ -15,48 +63,3 @@ export const Route = createFileRoute('/_library')({ }, component: Layout, }) - -function Layout() { - const loaderData = Route.useLoaderData() - const pathname = useLocation({ select: (s) => s.pathname }) - return ( -
- -
-

- {pathname.value} -

- -
-
- ) -} diff --git a/examples/AGENTS.md b/examples/AGENTS.md new file mode 100644 index 0000000000..eb47fbd925 --- /dev/null +++ b/examples/AGENTS.md @@ -0,0 +1,4 @@ +# Examples + +- Versioned dependencies on this repository's packages resolve locally through `pnpm-workspace.yaml` overrides. Keep published version ranges in example manifests; do not replace them with `workspace:*` as a linking fix. +- Root `pnpm dev` watches package builds. To run an example app, use its own `dev` script after building its workspace dependencies. diff --git a/examples/react/authenticated-routes-firebase/package.json b/examples/react/authenticated-routes-firebase/package.json index ed0c97607c..1efa172047 100644 --- a/examples/react/authenticated-routes-firebase/package.json +++ b/examples/react/authenticated-routes-firebase/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "firebase": "^11.4.0", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -25,7 +25,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/authenticated-routes-firebase/src/routeTree.gen.ts b/examples/react/authenticated-routes-firebase/src/routeTree.gen.ts index 0e81c27c1c..bcc454ab03 100644 --- a/examples/react/authenticated-routes-firebase/src/routeTree.gen.ts +++ b/examples/react/authenticated-routes-firebase/src/routeTree.gen.ts @@ -9,38 +9,38 @@ // 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 LoginRouteImport } from './routes/login' -import { Route as AuthRouteImport } from './routes/_auth' import { Route as IndexRouteImport } from './routes/index' -import { Route as AuthInvoicesRouteImport } from './routes/_auth.invoices' +import { Route as AuthRouteImport } from './routes/_auth' +import { Route as LoginRouteImport } from './routes/login' import { Route as AuthDashboardRouteImport } from './routes/_auth.dashboard' +import { Route as AuthInvoicesRouteImport } from './routes/_auth.invoices' import { Route as AuthInvoicesIndexRouteImport } from './routes/_auth.invoices.index' import { Route as AuthInvoicesInvoiceIdRouteImport } from './routes/_auth.invoices.$invoiceId' -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthRoute = AuthRouteImport.update({ id: '/_auth', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) -const AuthInvoicesRoute = AuthInvoicesRouteImport.update({ - id: '/invoices', - path: '/invoices', - getParentRoute: () => AuthRoute, -} as any) const AuthDashboardRoute = AuthDashboardRouteImport.update({ id: '/dashboard', path: '/dashboard', getParentRoute: () => AuthRoute, } as any) +const AuthInvoicesRoute = AuthInvoicesRouteImport.update({ + id: '/invoices', + path: '/invoices', + getParentRoute: () => AuthRoute, +} as any) const AuthInvoicesIndexRoute = AuthInvoicesIndexRouteImport.update({ id: '/', path: '/', @@ -107,11 +107,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_auth': { @@ -121,20 +121,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/_auth/invoices': { - id: '/_auth/invoices' - path: '/invoices' - fullPath: '/invoices' - preLoaderRoute: typeof AuthInvoicesRouteImport - parentRoute: typeof AuthRoute - } '/_auth/dashboard': { id: '/_auth/dashboard' path: '/dashboard' @@ -142,6 +135,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthDashboardRouteImport parentRoute: typeof AuthRoute } + '/_auth/invoices': { + id: '/_auth/invoices' + path: '/invoices' + fullPath: '/invoices' + preLoaderRoute: typeof AuthInvoicesRouteImport + parentRoute: typeof AuthRoute + } '/_auth/invoices/': { id: '/_auth/invoices/' path: '/' diff --git a/examples/react/authenticated-routes/package.json b/examples/react/authenticated-routes/package.json index b47b6a38a2..6af48f1d34 100644 --- a/examples/react/authenticated-routes/package.json +++ b/examples/react/authenticated-routes/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -23,7 +23,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/authenticated-routes/src/routeTree.gen.ts b/examples/react/authenticated-routes/src/routeTree.gen.ts index 0e81c27c1c..bcc454ab03 100644 --- a/examples/react/authenticated-routes/src/routeTree.gen.ts +++ b/examples/react/authenticated-routes/src/routeTree.gen.ts @@ -9,38 +9,38 @@ // 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 LoginRouteImport } from './routes/login' -import { Route as AuthRouteImport } from './routes/_auth' import { Route as IndexRouteImport } from './routes/index' -import { Route as AuthInvoicesRouteImport } from './routes/_auth.invoices' +import { Route as AuthRouteImport } from './routes/_auth' +import { Route as LoginRouteImport } from './routes/login' import { Route as AuthDashboardRouteImport } from './routes/_auth.dashboard' +import { Route as AuthInvoicesRouteImport } from './routes/_auth.invoices' import { Route as AuthInvoicesIndexRouteImport } from './routes/_auth.invoices.index' import { Route as AuthInvoicesInvoiceIdRouteImport } from './routes/_auth.invoices.$invoiceId' -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthRoute = AuthRouteImport.update({ id: '/_auth', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) -const AuthInvoicesRoute = AuthInvoicesRouteImport.update({ - id: '/invoices', - path: '/invoices', - getParentRoute: () => AuthRoute, -} as any) const AuthDashboardRoute = AuthDashboardRouteImport.update({ id: '/dashboard', path: '/dashboard', getParentRoute: () => AuthRoute, } as any) +const AuthInvoicesRoute = AuthInvoicesRouteImport.update({ + id: '/invoices', + path: '/invoices', + getParentRoute: () => AuthRoute, +} as any) const AuthInvoicesIndexRoute = AuthInvoicesIndexRouteImport.update({ id: '/', path: '/', @@ -107,11 +107,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_auth': { @@ -121,20 +121,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/_auth/invoices': { - id: '/_auth/invoices' - path: '/invoices' - fullPath: '/invoices' - preLoaderRoute: typeof AuthInvoicesRouteImport - parentRoute: typeof AuthRoute - } '/_auth/dashboard': { id: '/_auth/dashboard' path: '/dashboard' @@ -142,6 +135,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthDashboardRouteImport parentRoute: typeof AuthRoute } + '/_auth/invoices': { + id: '/_auth/invoices' + path: '/invoices' + fullPath: '/invoices' + preLoaderRoute: typeof AuthInvoicesRouteImport + parentRoute: typeof AuthRoute + } '/_auth/invoices/': { id: '/_auth/invoices/' path: '/' diff --git a/examples/react/basic-default-search-params/package.json b/examples/react/basic-default-search-params/package.json index d3062bbb11..96c68fecd4 100644 --- a/examples/react/basic-default-search-params/package.json +++ b/examples/react/basic-default-search-params/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", + "@tanstack/react-query": "^5.102.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -23,7 +23,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/basic-devtools-panel/package.json b/examples/react/basic-devtools-panel/package.json index 3147d73064..ccae95d73f 100644 --- a/examples/react/basic-devtools-panel/package.json +++ b/examples/react/basic-devtools-panel/package.json @@ -10,9 +10,10 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.67.2", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -22,7 +23,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/basic-file-based/package.json b/examples/react/basic-file-based/package.json index 7aecf29cce..9c3cacada1 100644 --- a/examples/react/basic-file-based/package.json +++ b/examples/react/basic-file-based/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -23,7 +23,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/basic-file-based/src/routeTree.gen.ts b/examples/react/basic-file-based/src/routeTree.gen.ts index 9d28e9a236..f370ad5d03 100644 --- a/examples/react/basic-file-based/src/routeTree.gen.ts +++ b/examples/react/basic-file-based/src/routeTree.gen.ts @@ -9,35 +9,40 @@ // 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 AnchorRouteImport } from './routes/anchor' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as PostsRouteRouteImport } from './routes/posts.route' import { Route as IndexRouteImport } from './routes/index' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as AnchorRouteImport } from './routes/anchor' +import { Route as PostsRouteRouteImport } from './routes/posts.route' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' -const AnchorRoute = AnchorRouteImport.update({ - id: '/anchor', - path: '/anchor', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) +const AnchorRoute = AnchorRouteImport.update({ + id: '/anchor', + path: '/anchor', + getParentRoute: () => rootRouteImport, +} as any) const PostsRouteRoute = PostsRouteRouteImport.update({ id: '/posts', path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, + } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -48,10 +53,11 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRouteRoute, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -59,12 +65,6 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -129,11 +129,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/anchor': { - id: '/anchor' - path: '/anchor' - fullPath: '/anchor' - preLoaderRoute: typeof AnchorRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout': { @@ -143,6 +143,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } + '/anchor': { + id: '/anchor' + path: '/anchor' + fullPath: '/anchor' + preLoaderRoute: typeof AnchorRouteImport + parentRoute: typeof rootRouteImport + } '/posts': { id: '/posts' path: '/posts' @@ -150,12 +157,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' + path: '' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/posts/': { id: '/posts/' @@ -171,12 +178,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRouteRoute } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -185,13 +192,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } } } diff --git a/examples/react/basic-non-nested-devtools/package.json b/examples/react/basic-non-nested-devtools/package.json index 7ace128a31..32e856ebcf 100644 --- a/examples/react/basic-non-nested-devtools/package.json +++ b/examples/react/basic-non-nested-devtools/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -21,7 +21,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/basic-react-query-file-based/package.json b/examples/react/basic-react-query-file-based/package.json index e0fa7c1a36..d01a02872e 100644 --- a/examples/react/basic-react-query-file-based/package.json +++ b/examples/react/basic-react-query-file-based/package.json @@ -10,11 +10,11 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -25,7 +25,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/basic-react-query-file-based/src/routeTree.gen.ts b/examples/react/basic-react-query-file-based/src/routeTree.gen.ts index 28cfbec8ed..9676858c7c 100644 --- a/examples/react/basic-react-query-file-based/src/routeTree.gen.ts +++ b/examples/react/basic-react-query-file-based/src/routeTree.gen.ts @@ -9,15 +9,20 @@ // 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 PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as PostsRouteRouteImport } from './routes/posts.route' -import { Route as IndexRouteImport } from './routes/index' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, @@ -27,11 +32,11 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, + } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -42,10 +47,11 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRouteRoute, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -53,12 +59,6 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -117,6 +117,13 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/_pathlessLayout': { id: '/_pathlessLayout' path: '' @@ -131,12 +138,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' + path: '' fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute } '/posts/': { id: '/posts/' @@ -152,12 +159,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRouteRoute } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -166,13 +173,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } } } diff --git a/examples/react/basic-react-query/package.json b/examples/react/basic-react-query/package.json index 160c426dc1..edab96afac 100644 --- a/examples/react/basic-react-query/package.json +++ b/examples/react/basic-react-query/package.json @@ -10,10 +10,10 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -23,7 +23,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/basic-ssr-file-based/package.json b/examples/react/basic-ssr-file-based/package.json index c7f7da2e0c..3222c33e19 100644 --- a/examples/react/basic-ssr-file-based/package.json +++ b/examples/react/basic-ssr-file-based/package.json @@ -11,8 +11,8 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tanstack/react-router": "^1.170.18", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/react-router": "^1.170.46", + "@tanstack/router-plugin": "^1.169.0", "compression": "^1.8.0", "express": "^5.2.1", "get-port": "^7.1.0", @@ -21,12 +21,13 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.0", + "@tanstack/react-router-devtools": "^1.167.3", "@types/express": "^5.0.6", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.1", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/basic-ssr-file-based/src/routeTree.gen.ts b/examples/react/basic-ssr-file-based/src/routeTree.gen.ts index 4e61620e43..6f9f3f0f5e 100644 --- a/examples/react/basic-ssr-file-based/src/routeTree.gen.ts +++ b/examples/react/basic-ssr-file-based/src/routeTree.gen.ts @@ -9,12 +9,17 @@ // 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 ErrorRouteImport } from './routes/error' import { Route as PostsRouteRouteImport } from './routes/posts/route' -import { Route as IndexRouteImport } from './routes/index' import { Route as PostsIndexRouteImport } from './routes/posts/index' import { Route as PostsPostIdRouteImport } from './routes/posts/$postId' +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const ErrorRoute = ErrorRouteImport.update({ id: '/error', path: '/error', @@ -25,11 +30,6 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -78,6 +78,13 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/error': { id: '/error' path: '/error' @@ -92,13 +99,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/posts/': { id: '/posts/' path: '/' diff --git a/examples/react/basic-ssr-streaming-file-based/package.json b/examples/react/basic-ssr-streaming-file-based/package.json index f022ebb718..c3c87c8d88 100644 --- a/examples/react/basic-ssr-streaming-file-based/package.json +++ b/examples/react/basic-ssr-streaming-file-based/package.json @@ -11,8 +11,8 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tanstack/react-router": "^1.170.18", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/react-router": "^1.170.46", + "@tanstack/router-plugin": "^1.169.0", "compression": "^1.8.0", "express": "^5.2.1", "get-port": "^7.1.0", @@ -21,12 +21,13 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.0", + "@tanstack/react-router-devtools": "^1.167.3", "@types/express": "^5.0.6", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.1", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/basic-ssr-streaming-file-based/src/routeTree.gen.ts b/examples/react/basic-ssr-streaming-file-based/src/routeTree.gen.ts index 4e61620e43..6f9f3f0f5e 100644 --- a/examples/react/basic-ssr-streaming-file-based/src/routeTree.gen.ts +++ b/examples/react/basic-ssr-streaming-file-based/src/routeTree.gen.ts @@ -9,12 +9,17 @@ // 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 ErrorRouteImport } from './routes/error' import { Route as PostsRouteRouteImport } from './routes/posts/route' -import { Route as IndexRouteImport } from './routes/index' import { Route as PostsIndexRouteImport } from './routes/posts/index' import { Route as PostsPostIdRouteImport } from './routes/posts/$postId' +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const ErrorRoute = ErrorRouteImport.update({ id: '/error', path: '/error', @@ -25,11 +30,6 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -78,6 +78,13 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/error': { id: '/error' path: '/error' @@ -92,13 +99,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/posts/': { id: '/posts/' path: '/' diff --git a/examples/react/basic-virtual-file-based/package.json b/examples/react/basic-virtual-file-based/package.json index 7cf590ef31..84d326435c 100644 --- a/examples/react/basic-virtual-file-based/package.json +++ b/examples/react/basic-virtual-file-based/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "@tanstack/virtual-file-routes": "^1.162.0", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -24,7 +24,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/basic-virtual-file-based/src/routeTree.gen.ts b/examples/react/basic-virtual-file-based/src/routeTree.gen.ts index 2fe7840f19..6745e373aa 100644 --- a/examples/react/basic-virtual-file-based/src/routeTree.gen.ts +++ b/examples/react/basic-virtual-file-based/src/routeTree.gen.ts @@ -9,77 +9,77 @@ // 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 postsPostsRouteImport } from './routes/posts/posts' -import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' import { Route as homeRouteImport } from './routes/home' -import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' +import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' +import { Route as postsPostsRouteImport } from './routes/posts/posts' import { Route as layoutSecondLayoutRouteImport } from './routes/layout/second-layout' -import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' import { Route as ClassicHelloRouteRouteImport } from './routes/file-based-subtree/hello/route' +import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' +import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' import { Route as ClassicHelloIndexRouteImport } from './routes/file-based-subtree/hello/index' -import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' import { Route as ClassicHelloUniverseRouteImport } from './routes/file-based-subtree/hello/universe' -import { Route as bRouteImport } from './routes/b' +import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' import { Route as aRouteImport } from './routes/a' +import { Route as bRouteImport } from './routes/b' -const postsPostsRoute = postsPostsRouteImport.update({ - id: '/posts', - path: '/posts', +const homeRoute = homeRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const layoutFirstLayoutRoute = layoutFirstLayoutRouteImport.update({ id: '/_first', getParentRoute: () => rootRouteImport, } as any) -const homeRoute = homeRouteImport.update({ - id: '/', - path: '/', +const postsPostsRoute = postsPostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const postsPostsDetailRoute = postsPostsDetailRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => postsPostsRoute, -} as any) const layoutSecondLayoutRoute = layoutSecondLayoutRouteImport.update({ id: '/_second-layout', getParentRoute: () => layoutFirstLayoutRoute, } as any) -const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => postsPostsRoute, -} as any) const ClassicHelloRouteRoute = ClassicHelloRouteRouteImport.update({ id: '/classic/hello', path: '/classic/hello', getParentRoute: () => rootRouteImport, } as any) +const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => postsPostsRoute, +} as any) +const postsPostsDetailRoute = postsPostsDetailRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => postsPostsRoute, +} as any) const ClassicHelloIndexRoute = ClassicHelloIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ - id: '/world', - path: '/world', - getParentRoute: () => ClassicHelloRouteRoute, -} as any) const ClassicHelloUniverseRoute = ClassicHelloUniverseRouteImport.update({ id: '/universe', path: '/universe', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const bRoute = bRouteImport.update({ - id: '/route-without-file/layout-b', - path: '/route-without-file/layout-b', - getParentRoute: () => layoutSecondLayoutRoute, +const ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ + id: '/world', + path: '/world', + getParentRoute: () => ClassicHelloRouteRoute, } as any) const aRoute = aRouteImport.update({ id: '/route-without-file/layout-a', path: '/route-without-file/layout-a', getParentRoute: () => layoutSecondLayoutRoute, } as any) +const bRoute = bRouteImport.update({ + id: '/route-without-file/layout-b', + path: '/route-without-file/layout-b', + getParentRoute: () => layoutSecondLayoutRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof homeRoute @@ -166,11 +166,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof postsPostsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof homeRouteImport parentRoute: typeof rootRouteImport } '/_first': { @@ -180,20 +180,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof layoutFirstLayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof homeRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof postsPostsRouteImport parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof postsPostsDetailRouteImport - parentRoute: typeof postsPostsRoute - } '/_first/_second-layout': { id: '/_first/_second-layout' path: '' @@ -201,13 +194,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof layoutSecondLayoutRouteImport parentRoute: typeof layoutFirstLayoutRoute } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof postsPostsHomeRouteImport - parentRoute: typeof postsPostsRoute - } '/classic/hello': { id: '/classic/hello' path: '/classic/hello' @@ -215,6 +201,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ClassicHelloRouteRouteImport parentRoute: typeof rootRouteImport } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof postsPostsHomeRouteImport + parentRoute: typeof postsPostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof postsPostsDetailRouteImport + parentRoute: typeof postsPostsRoute + } '/classic/hello/': { id: '/classic/hello/' path: '/' @@ -222,13 +222,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ClassicHelloIndexRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/classic/hello/world': { - id: '/classic/hello/world' - path: '/world' - fullPath: '/classic/hello/world' - preLoaderRoute: typeof ClassicHelloWorldRouteImport - parentRoute: typeof ClassicHelloRouteRoute - } '/classic/hello/universe': { id: '/classic/hello/universe' path: '/universe' @@ -236,12 +229,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ClassicHelloUniverseRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/_first/_second-layout/route-without-file/layout-b': { - id: '/_first/_second-layout/route-without-file/layout-b' - path: '/route-without-file/layout-b' - fullPath: '/route-without-file/layout-b' - preLoaderRoute: typeof bRouteImport - parentRoute: typeof layoutSecondLayoutRoute + '/classic/hello/world': { + id: '/classic/hello/world' + path: '/world' + fullPath: '/classic/hello/world' + preLoaderRoute: typeof ClassicHelloWorldRouteImport + parentRoute: typeof ClassicHelloRouteRoute } '/_first/_second-layout/route-without-file/layout-a': { id: '/_first/_second-layout/route-without-file/layout-a' @@ -250,6 +243,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof aRouteImport parentRoute: typeof layoutSecondLayoutRoute } + '/_first/_second-layout/route-without-file/layout-b': { + id: '/_first/_second-layout/route-without-file/layout-b' + path: '/route-without-file/layout-b' + fullPath: '/route-without-file/layout-b' + preLoaderRoute: typeof bRouteImport + parentRoute: typeof layoutSecondLayoutRoute + } } } diff --git a/examples/react/basic-virtual-inside-file-based/package.json b/examples/react/basic-virtual-inside-file-based/package.json index 255facb7ff..c04cb6012e 100644 --- a/examples/react/basic-virtual-inside-file-based/package.json +++ b/examples/react/basic-virtual-inside-file-based/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "@tanstack/virtual-file-routes": "^1.162.0", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -24,7 +24,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/basic-virtual-inside-file-based/src/routeTree.gen.ts b/examples/react/basic-virtual-inside-file-based/src/routeTree.gen.ts index 947fd037d9..cda1f85f15 100644 --- a/examples/react/basic-virtual-inside-file-based/src/routeTree.gen.ts +++ b/examples/react/basic-virtual-inside-file-based/src/routeTree.gen.ts @@ -9,36 +9,31 @@ // 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 PostsRouteImport } from './routes/posts' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as IndexRouteImport } from './routes/index' -import { Route as PostsDetailsRouteImport } from './routes/posts/details' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as PostsRouteImport } from './routes/posts' import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' import { Route as PostsHomeRouteImport } from './routes/posts/home' -import { Route as PostsLetsGoIndexRouteImport } from './routes/posts/lets-go/index' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as PostsDetailsRouteImport } from './routes/posts/details' import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as PostsLetsGoIndexRouteImport } from './routes/posts/lets-go/index' import { Route as PostsLetsGoDeeperHomeRouteImport } from './routes/posts/lets-go/deeper/home' -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const LayoutRoute = LayoutRouteImport.update({ id: '/_layout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const PostsDetailsRoute = PostsDetailsRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) const LayoutLayout2Route = LayoutLayout2RouteImport.update({ id: '/_layout-2', getParentRoute: () => LayoutRoute, @@ -48,20 +43,25 @@ const PostsHomeRoute = PostsHomeRouteImport.update({ path: '/', getParentRoute: () => PostsRoute, } as any) -const PostsLetsGoIndexRoute = PostsLetsGoIndexRouteImport.update({ - id: '/inception/', - path: '/inception/', +const PostsDetailsRoute = PostsDetailsRouteImport.update({ + id: '/$postId', + path: '/$postId', getParentRoute: () => PostsRoute, } as any) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, +} as any) const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ id: '/layout-b', path: '/layout-b', getParentRoute: () => LayoutLayout2Route, } as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const PostsLetsGoIndexRoute = PostsLetsGoIndexRouteImport.update({ + id: '/inception/', + path: '/inception/', + getParentRoute: () => PostsRoute, } as any) const PostsLetsGoDeeperHomeRoute = PostsLetsGoDeeperHomeRouteImport.update({ id: '/inception/deeper/', @@ -143,11 +143,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -157,20 +157,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsDetailsRouteImport - parentRoute: typeof PostsRoute - } '/_layout/_layout-2': { id: '/_layout/_layout-2' path: '' @@ -185,13 +178,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsHomeRouteImport parentRoute: typeof PostsRoute } - '/posts/inception/': { - id: '/posts/inception/' - path: '/inception' - fullPath: '/posts/inception/' - preLoaderRoute: typeof PostsLetsGoIndexRouteImport + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsDetailsRouteImport parentRoute: typeof PostsRoute } + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route + } '/_layout/_layout-2/layout-b': { id: '/_layout/_layout-2/layout-b' path: '/layout-b' @@ -199,12 +199,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport parentRoute: typeof LayoutLayout2Route } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/posts/inception/': { + id: '/posts/inception/' + path: '/inception' + fullPath: '/posts/inception/' + preLoaderRoute: typeof PostsLetsGoIndexRouteImport + parentRoute: typeof PostsRoute } '/posts/inception/deeper/': { id: '/posts/inception/deeper/' diff --git a/examples/react/basic/package.json b/examples/react/basic/package.json index f380281baa..2c09a3dfdf 100644 --- a/examples/react/basic/package.json +++ b/examples/react/basic/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -21,7 +21,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/deferred-data/package.json b/examples/react/deferred-data/package.json index c1ca6ba2e1..99afb661ee 100644 --- a/examples/react/deferred-data/package.json +++ b/examples/react/deferred-data/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -22,7 +22,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/i18n-paraglide/package.json b/examples/react/i18n-paraglide/package.json index 55079cfebb..88140e8911 100644 --- a/examples/react/i18n-paraglide/package.json +++ b/examples/react/i18n-paraglide/package.json @@ -11,8 +11,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.18", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/react-router": "^1.170.46", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.1.1", "react-dom": "^19.1.1", "tailwindcss": "^4.2.2" @@ -22,8 +22,20 @@ "@types/react": "^19.1.13", "@types/react-dom": "^19.1.9", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "@inlang/paraglide-js": "^2.4.0" + }, + "nx": { + "targets": { + "build": { + "outputs": [ + "...", + "{projectRoot}/src/paraglide", + "{projectRoot}/project.inlang/cache" + ] + } + } } } diff --git a/examples/react/i18n-paraglide/src/routeTree.gen.ts b/examples/react/i18n-paraglide/src/routeTree.gen.ts index 59499d9fbf..12bc916ae4 100644 --- a/examples/react/i18n-paraglide/src/routeTree.gen.ts +++ b/examples/react/i18n-paraglide/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/kitchen-sink-file-based/package.json b/examples/react/kitchen-sink-file-based/package.json index 989367745e..e02defb3ce 100644 --- a/examples/react/kitchen-sink-file-based/package.json +++ b/examples/react/kitchen-sink-file-based/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -24,7 +24,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/kitchen-sink-file-based/src/routeTree.gen.ts b/examples/react/kitchen-sink-file-based/src/routeTree.gen.ts index 1e29ba5794..03af4e1e58 100644 --- a/examples/react/kitchen-sink-file-based/src/routeTree.gen.ts +++ b/examples/react/kitchen-sink-file-based/src/routeTree.gen.ts @@ -9,81 +9,71 @@ // 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 LoginRouteImport } from './routes/login' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as AuthRouteImport } from './routes/_auth' -import { Route as DashboardRouteRouteImport } from './routes/dashboard.route' import { Route as IndexRouteImport } from './routes/index' -import { Route as ExpensiveIndexRouteImport } from './routes/expensive/index' -import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' -import { Route as PathlessLayoutRouteBRouteImport } from './routes/_pathlessLayout.route-b' -import { Route as PathlessLayoutRouteARouteImport } from './routes/_pathlessLayout.route-a' -import { Route as AuthProfileRouteImport } from './routes/_auth.profile' +import { Route as AuthRouteImport } from './routes/_auth' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as DashboardRouteRouteImport } from './routes/dashboard.route' +import { Route as LoginRouteImport } from './routes/login' import { Route as thisFolderIsNotInTheUrlRouteGroupRouteImport } from './routes/(this-folder-is-not-in-the-url)/route-group' -import { Route as DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as AuthProfileRouteImport } from './routes/_auth.profile' +import { Route as PathlessLayoutRouteARouteImport } from './routes/_pathlessLayout.route-a' +import { Route as PathlessLayoutRouteBRouteImport } from './routes/_pathlessLayout.route-b' +import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' import { Route as DashboardInvoicesRouteRouteImport } from './routes/dashboard.invoices.route' -import { Route as DashboardUsersIndexRouteImport } from './routes/dashboard.users.index' +import { Route as DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as ExpensiveIndexRouteImport } from './routes/expensive/index' import { Route as DashboardInvoicesIndexRouteImport } from './routes/dashboard.invoices.index' -import { Route as DashboardUsersUserRouteImport } from './routes/dashboard.users.user' import { Route as DashboardInvoicesInvoiceIdRouteImport } from './routes/dashboard.invoices.$invoiceId' +import { Route as DashboardUsersIndexRouteImport } from './routes/dashboard.users.index' +import { Route as DashboardUsersUserRouteImport } from './routes/dashboard.users.user' -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthRoute = AuthRouteImport.update({ id: '/_auth', getParentRoute: () => rootRouteImport, } as any) +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', + getParentRoute: () => rootRouteImport, +} as any) const DashboardRouteRoute = DashboardRouteRouteImport.update({ id: '/dashboard', path: '/dashboard', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) -const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ - id: '/expensive/', - path: '/expensive/', - getParentRoute: () => rootRouteImport, -} as any) -const DashboardIndexRoute = DashboardIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardRouteRoute, -} as any) -const PathlessLayoutRouteBRoute = PathlessLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutRoute, -} as any) -const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutRoute, -} as any) -const AuthProfileRoute = AuthProfileRouteImport.update({ - id: '/profile', - path: '/profile', - getParentRoute: () => AuthRoute, -} as any) const thisFolderIsNotInTheUrlRouteGroupRoute = thisFolderIsNotInTheUrlRouteGroupRouteImport.update({ id: '/(this-folder-is-not-in-the-url)/route-group', path: '/route-group', getParentRoute: () => rootRouteImport, } as any) -const DashboardUsersRouteRoute = DashboardUsersRouteRouteImport.update({ - id: '/users', - path: '/users', +const AuthProfileRoute = AuthProfileRouteImport.update({ + id: '/profile', + path: '/profile', + getParentRoute: () => AuthRoute, +} as any) +const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutRoute, +} as any) +const PathlessLayoutRouteBRoute = PathlessLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutRoute, +} as any) +const DashboardIndexRoute = DashboardIndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => DashboardRouteRoute, } as any) const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ @@ -91,27 +81,37 @@ const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ path: '/invoices', getParentRoute: () => DashboardRouteRoute, } as any) -const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardUsersRouteRoute, +const DashboardUsersRouteRoute = DashboardUsersRouteRouteImport.update({ + id: '/users', + path: '/users', + getParentRoute: () => DashboardRouteRoute, +} as any) +const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ + id: '/expensive/', + path: '/expensive/', + getParentRoute: () => rootRouteImport, } as any) const DashboardInvoicesIndexRoute = DashboardInvoicesIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => DashboardInvoicesRouteRoute, } as any) -const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ - id: '/user', - path: '/user', - getParentRoute: () => DashboardUsersRouteRoute, -} as any) const DashboardInvoicesInvoiceIdRoute = DashboardInvoicesInvoiceIdRouteImport.update({ id: '/$invoiceId', path: '/$invoiceId', getParentRoute: () => DashboardInvoicesRouteRoute, } as any) +const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => DashboardUsersRouteRoute, +} as any) +const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ + id: '/user', + path: '/user', + getParentRoute: () => DashboardUsersRouteRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -229,18 +229,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' + '/': { + id: '/' + path: '/' fullPath: '/' - preLoaderRoute: typeof PathlessLayoutRouteImport + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_auth': { @@ -250,6 +243,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthRouteImport parentRoute: typeof rootRouteImport } + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof rootRouteImport + } '/dashboard': { id: '/dashboard' path: '/dashboard' @@ -257,48 +257,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/expensive/': { - id: '/expensive/' - path: '/expensive' - fullPath: '/expensive/' - preLoaderRoute: typeof ExpensiveIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/dashboard/': { - id: '/dashboard/' - path: '/' - fullPath: '/dashboard/' - preLoaderRoute: typeof DashboardIndexRouteImport - parentRoute: typeof DashboardRouteRoute - } - '/_pathlessLayout/route-b': { - id: '/_pathlessLayout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/_pathlessLayout/route-a': { - id: '/_pathlessLayout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/_auth/profile': { - id: '/_auth/profile' - path: '/profile' - fullPath: '/profile' - preLoaderRoute: typeof AuthProfileRouteImport - parentRoute: typeof AuthRoute - } '/(this-folder-is-not-in-the-url)/route-group': { id: '/(this-folder-is-not-in-the-url)/route-group' path: '/route-group' @@ -306,11 +271,32 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof thisFolderIsNotInTheUrlRouteGroupRouteImport parentRoute: typeof rootRouteImport } - '/dashboard/users': { - id: '/dashboard/users' - path: '/users' - fullPath: '/dashboard/users' - preLoaderRoute: typeof DashboardUsersRouteRouteImport + '/_auth/profile': { + id: '/_auth/profile' + path: '/profile' + fullPath: '/profile' + preLoaderRoute: typeof AuthProfileRouteImport + parentRoute: typeof AuthRoute + } + '/_pathlessLayout/route-a': { + id: '/_pathlessLayout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutRoute + } + '/_pathlessLayout/route-b': { + id: '/_pathlessLayout/route-b' + path: '/route-b' + fullPath: '/route-b' + preLoaderRoute: typeof PathlessLayoutRouteBRouteImport + parentRoute: typeof PathlessLayoutRoute + } + '/dashboard/': { + id: '/dashboard/' + path: '/' + fullPath: '/dashboard/' + preLoaderRoute: typeof DashboardIndexRouteImport parentRoute: typeof DashboardRouteRoute } '/dashboard/invoices': { @@ -320,12 +306,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardInvoicesRouteRouteImport parentRoute: typeof DashboardRouteRoute } - '/dashboard/users/': { - id: '/dashboard/users/' - path: '/' - fullPath: '/dashboard/users/' - preLoaderRoute: typeof DashboardUsersIndexRouteImport - parentRoute: typeof DashboardUsersRouteRoute + '/dashboard/users': { + id: '/dashboard/users' + path: '/users' + fullPath: '/dashboard/users' + preLoaderRoute: typeof DashboardUsersRouteRouteImport + parentRoute: typeof DashboardRouteRoute + } + '/expensive/': { + id: '/expensive/' + path: '/expensive' + fullPath: '/expensive/' + preLoaderRoute: typeof ExpensiveIndexRouteImport + parentRoute: typeof rootRouteImport } '/dashboard/invoices/': { id: '/dashboard/invoices/' @@ -334,13 +327,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardInvoicesIndexRouteImport parentRoute: typeof DashboardInvoicesRouteRoute } - '/dashboard/users/user': { - id: '/dashboard/users/user' - path: '/user' - fullPath: '/dashboard/users/user' - preLoaderRoute: typeof DashboardUsersUserRouteImport - parentRoute: typeof DashboardUsersRouteRoute - } '/dashboard/invoices/$invoiceId': { id: '/dashboard/invoices/$invoiceId' path: '/$invoiceId' @@ -348,6 +334,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardInvoicesInvoiceIdRouteImport parentRoute: typeof DashboardInvoicesRouteRoute } + '/dashboard/users/': { + id: '/dashboard/users/' + path: '/' + fullPath: '/dashboard/users/' + preLoaderRoute: typeof DashboardUsersIndexRouteImport + parentRoute: typeof DashboardUsersRouteRoute + } + '/dashboard/users/user': { + id: '/dashboard/users/user' + path: '/user' + fullPath: '/dashboard/users/user' + preLoaderRoute: typeof DashboardUsersUserRouteImport + parentRoute: typeof DashboardUsersRouteRoute + } } } diff --git a/examples/react/kitchen-sink-react-query-file-based/package.json b/examples/react/kitchen-sink-react-query-file-based/package.json index 378ad424c4..e3dd032ac2 100644 --- a/examples/react/kitchen-sink-react-query-file-based/package.json +++ b/examples/react/kitchen-sink-react-query-file-based/package.json @@ -10,11 +10,11 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -26,7 +26,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/kitchen-sink-react-query-file-based/src/routeTree.gen.ts b/examples/react/kitchen-sink-react-query-file-based/src/routeTree.gen.ts index 66180a8554..dbce8cf604 100644 --- a/examples/react/kitchen-sink-react-query-file-based/src/routeTree.gen.ts +++ b/examples/react/kitchen-sink-react-query-file-based/src/routeTree.gen.ts @@ -9,80 +9,65 @@ // 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 LoginRouteImport } from './routes/login' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as AuthRouteImport } from './routes/_auth' -import { Route as DashboardRouteRouteImport } from './routes/dashboard.route' import { Route as IndexRouteImport } from './routes/index' -import { Route as ExpensiveIndexRouteImport } from './routes/expensive/index' -import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' -import { Route as FooBarRouteImport } from './routes/foo/bar' -import { Route as PathlessLayoutRouteBRouteImport } from './routes/_pathlessLayout.route-b' -import { Route as PathlessLayoutRouteARouteImport } from './routes/_pathlessLayout.route-a' +import { Route as AuthRouteImport } from './routes/_auth' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as DashboardRouteRouteImport } from './routes/dashboard.route' +import { Route as LoginRouteImport } from './routes/login' import { Route as AuthProfileRouteImport } from './routes/_auth.profile' -import { Route as DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as PathlessLayoutRouteARouteImport } from './routes/_pathlessLayout.route-a' +import { Route as PathlessLayoutRouteBRouteImport } from './routes/_pathlessLayout.route-b' +import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' import { Route as DashboardInvoicesRouteRouteImport } from './routes/dashboard.invoices.route' -import { Route as DashboardUsersIndexRouteImport } from './routes/dashboard.users.index' +import { Route as DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as ExpensiveIndexRouteImport } from './routes/expensive/index' +import { Route as FooBarRouteImport } from './routes/foo/bar' import { Route as DashboardInvoicesIndexRouteImport } from './routes/dashboard.invoices.index' -import { Route as DashboardUsersUserRouteImport } from './routes/dashboard.users.user' import { Route as DashboardInvoicesInvoiceIdRouteImport } from './routes/dashboard.invoices.$invoiceId' +import { Route as DashboardUsersIndexRouteImport } from './routes/dashboard.users.index' +import { Route as DashboardUsersUserRouteImport } from './routes/dashboard.users.user' -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthRoute = AuthRouteImport.update({ id: '/_auth', getParentRoute: () => rootRouteImport, } as any) +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', + getParentRoute: () => rootRouteImport, +} as any) const DashboardRouteRoute = DashboardRouteRouteImport.update({ id: '/dashboard', path: '/dashboard', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) -const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ - id: '/expensive/', - path: '/expensive/', - getParentRoute: () => rootRouteImport, -} as any) -const DashboardIndexRoute = DashboardIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardRouteRoute, -} as any) -const FooBarRoute = FooBarRouteImport.update({ - id: '/foo/bar', - path: '/foo/bar', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRouteBRoute = PathlessLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutRoute, -} as any) -const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutRoute, -} as any) const AuthProfileRoute = AuthProfileRouteImport.update({ id: '/profile', path: '/profile', getParentRoute: () => AuthRoute, } as any) -const DashboardUsersRouteRoute = DashboardUsersRouteRouteImport.update({ - id: '/users', - path: '/users', +const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutRoute, +} as any) +const PathlessLayoutRouteBRoute = PathlessLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutRoute, +} as any) +const DashboardIndexRoute = DashboardIndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => DashboardRouteRoute, } as any) const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ @@ -90,27 +75,42 @@ const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ path: '/invoices', getParentRoute: () => DashboardRouteRoute, } as any) -const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardUsersRouteRoute, +const DashboardUsersRouteRoute = DashboardUsersRouteRouteImport.update({ + id: '/users', + path: '/users', + getParentRoute: () => DashboardRouteRoute, +} as any) +const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ + id: '/expensive/', + path: '/expensive/', + getParentRoute: () => rootRouteImport, +} as any) +const FooBarRoute = FooBarRouteImport.update({ + id: '/foo/bar', + path: '/foo/bar', + getParentRoute: () => rootRouteImport, } as any) const DashboardInvoicesIndexRoute = DashboardInvoicesIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => DashboardInvoicesRouteRoute, } as any) -const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ - id: '/user', - path: '/user', - getParentRoute: () => DashboardUsersRouteRoute, -} as any) const DashboardInvoicesInvoiceIdRoute = DashboardInvoicesInvoiceIdRouteImport.update({ id: '/$invoiceId', path: '/$invoiceId', getParentRoute: () => DashboardInvoicesRouteRoute, } as any) +const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => DashboardUsersRouteRoute, +} as any) +const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ + id: '/user', + path: '/user', + getParentRoute: () => DashboardUsersRouteRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -228,18 +228,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' + '/': { + id: '/' + path: '/' fullPath: '/' - preLoaderRoute: typeof PathlessLayoutRouteImport + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_auth': { @@ -249,6 +242,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthRouteImport parentRoute: typeof rootRouteImport } + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof rootRouteImport + } '/dashboard': { id: '/dashboard' path: '/dashboard' @@ -256,48 +256,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/expensive/': { - id: '/expensive/' - path: '/expensive' - fullPath: '/expensive/' - preLoaderRoute: typeof ExpensiveIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/dashboard/': { - id: '/dashboard/' - path: '/' - fullPath: '/dashboard/' - preLoaderRoute: typeof DashboardIndexRouteImport - parentRoute: typeof DashboardRouteRoute - } - '/foo/bar': { - id: '/foo/bar' - path: '/foo/bar' - fullPath: '/foo/bar' - preLoaderRoute: typeof FooBarRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout/route-b': { - id: '/_pathlessLayout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/_pathlessLayout/route-a': { - id: '/_pathlessLayout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutRoute - } '/_auth/profile': { id: '/_auth/profile' path: '/profile' @@ -305,11 +270,25 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthProfileRouteImport parentRoute: typeof AuthRoute } - '/dashboard/users': { - id: '/dashboard/users' - path: '/users' - fullPath: '/dashboard/users' - preLoaderRoute: typeof DashboardUsersRouteRouteImport + '/_pathlessLayout/route-a': { + id: '/_pathlessLayout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutRoute + } + '/_pathlessLayout/route-b': { + id: '/_pathlessLayout/route-b' + path: '/route-b' + fullPath: '/route-b' + preLoaderRoute: typeof PathlessLayoutRouteBRouteImport + parentRoute: typeof PathlessLayoutRoute + } + '/dashboard/': { + id: '/dashboard/' + path: '/' + fullPath: '/dashboard/' + preLoaderRoute: typeof DashboardIndexRouteImport parentRoute: typeof DashboardRouteRoute } '/dashboard/invoices': { @@ -319,12 +298,26 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardInvoicesRouteRouteImport parentRoute: typeof DashboardRouteRoute } - '/dashboard/users/': { - id: '/dashboard/users/' - path: '/' - fullPath: '/dashboard/users/' - preLoaderRoute: typeof DashboardUsersIndexRouteImport - parentRoute: typeof DashboardUsersRouteRoute + '/dashboard/users': { + id: '/dashboard/users' + path: '/users' + fullPath: '/dashboard/users' + preLoaderRoute: typeof DashboardUsersRouteRouteImport + parentRoute: typeof DashboardRouteRoute + } + '/expensive/': { + id: '/expensive/' + path: '/expensive' + fullPath: '/expensive/' + preLoaderRoute: typeof ExpensiveIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/foo/bar': { + id: '/foo/bar' + path: '/foo/bar' + fullPath: '/foo/bar' + preLoaderRoute: typeof FooBarRouteImport + parentRoute: typeof rootRouteImport } '/dashboard/invoices/': { id: '/dashboard/invoices/' @@ -333,13 +326,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardInvoicesIndexRouteImport parentRoute: typeof DashboardInvoicesRouteRoute } - '/dashboard/users/user': { - id: '/dashboard/users/user' - path: '/user' - fullPath: '/dashboard/users/user' - preLoaderRoute: typeof DashboardUsersUserRouteImport - parentRoute: typeof DashboardUsersRouteRoute - } '/dashboard/invoices/$invoiceId': { id: '/dashboard/invoices/$invoiceId' path: '/$invoiceId' @@ -347,6 +333,20 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DashboardInvoicesInvoiceIdRouteImport parentRoute: typeof DashboardInvoicesRouteRoute } + '/dashboard/users/': { + id: '/dashboard/users/' + path: '/' + fullPath: '/dashboard/users/' + preLoaderRoute: typeof DashboardUsersIndexRouteImport + parentRoute: typeof DashboardUsersRouteRoute + } + '/dashboard/users/user': { + id: '/dashboard/users/user' + path: '/user' + fullPath: '/dashboard/users/user' + preLoaderRoute: typeof DashboardUsersUserRouteImport + parentRoute: typeof DashboardUsersRouteRoute + } } } diff --git a/examples/react/kitchen-sink-react-query/package.json b/examples/react/kitchen-sink-react-query/package.json index c03d144726..14d0dc8e86 100644 --- a/examples/react/kitchen-sink-react-query/package.json +++ b/examples/react/kitchen-sink-react-query/package.json @@ -10,10 +10,10 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -25,7 +25,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/kitchen-sink/package.json b/examples/react/kitchen-sink/package.json index ebba4eb683..f738efc37e 100644 --- a/examples/react/kitchen-sink/package.json +++ b/examples/react/kitchen-sink/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -23,7 +23,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/large-file-based/package.json b/examples/react/large-file-based/package.json index e57ed59fbc..23d469d120 100644 --- a/examples/react/large-file-based/package.json +++ b/examples/react/large-file-based/package.json @@ -12,10 +12,10 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/react-query": "^5.102.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -26,7 +26,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/large-file-based/src/routeTree.gen.ts b/examples/react/large-file-based/src/routeTree.gen.ts index 93a5be975c..8494f51d73 100644 --- a/examples/react/large-file-based/src/routeTree.gen.ts +++ b/examples/react/large-file-based/src/routeTree.gen.ts @@ -9,23 +9,18 @@ // 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 RelativeRouteImport } from './routes/relative' -import { Route as LinkPropsRouteImport } from './routes/linkProps' -import { Route as AbsoluteRouteImport } from './routes/absolute' -import { Route as SearchRouteRouteImport } from './routes/search/route' -import { Route as ParamsRouteRouteImport } from './routes/params/route' import { Route as IndexRouteImport } from './routes/index' -import { Route as SearchSearchPlaceholderRouteImport } from './routes/search/searchPlaceholder' +import { Route as AbsoluteRouteImport } from './routes/absolute' +import { Route as LinkPropsRouteImport } from './routes/linkProps' +import { Route as ParamsRouteRouteImport } from './routes/params/route' +import { Route as RelativeRouteImport } from './routes/relative' +import { Route as SearchRouteRouteImport } from './routes/search/route' import { Route as ParamsParamsPlaceholderRouteImport } from './routes/params/$paramsPlaceholder' +import { Route as SearchSearchPlaceholderRouteImport } from './routes/search/searchPlaceholder' -const RelativeRoute = RelativeRouteImport.update({ - id: '/relative', - path: '/relative', - getParentRoute: () => rootRouteImport, -} as any) -const LinkPropsRoute = LinkPropsRouteImport.update({ - id: '/linkProps', - path: '/linkProps', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AbsoluteRoute = AbsoluteRouteImport.update({ @@ -33,9 +28,9 @@ const AbsoluteRoute = AbsoluteRouteImport.update({ path: '/absolute', getParentRoute: () => rootRouteImport, } as any) -const SearchRouteRoute = SearchRouteRouteImport.update({ - id: '/search', - path: '/search', +const LinkPropsRoute = LinkPropsRouteImport.update({ + id: '/linkProps', + path: '/linkProps', getParentRoute: () => rootRouteImport, } as any) const ParamsRouteRoute = ParamsRouteRouteImport.update({ @@ -43,21 +38,26 @@ const ParamsRouteRoute = ParamsRouteRouteImport.update({ path: '/params', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const RelativeRoute = RelativeRouteImport.update({ + id: '/relative', + path: '/relative', getParentRoute: () => rootRouteImport, } as any) -const SearchSearchPlaceholderRoute = SearchSearchPlaceholderRouteImport.update({ - id: '/searchPlaceholder', - path: '/searchPlaceholder', - getParentRoute: () => SearchRouteRoute, +const SearchRouteRoute = SearchRouteRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => rootRouteImport, } as any) const ParamsParamsPlaceholderRoute = ParamsParamsPlaceholderRouteImport.update({ id: '/$paramsPlaceholder', path: '/$paramsPlaceholder', getParentRoute: () => ParamsRouteRoute, } as any) +const SearchSearchPlaceholderRoute = SearchSearchPlaceholderRouteImport.update({ + id: '/searchPlaceholder', + path: '/searchPlaceholder', + getParentRoute: () => SearchRouteRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -134,18 +134,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/relative': { - id: '/relative' - path: '/relative' - fullPath: '/relative' - preLoaderRoute: typeof RelativeRouteImport - parentRoute: typeof rootRouteImport - } - '/linkProps': { - id: '/linkProps' - path: '/linkProps' - fullPath: '/linkProps' - preLoaderRoute: typeof LinkPropsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/absolute': { @@ -155,11 +148,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AbsoluteRouteImport parentRoute: typeof rootRouteImport } - '/search': { - id: '/search' - path: '/search' - fullPath: '/search' - preLoaderRoute: typeof SearchRouteRouteImport + '/linkProps': { + id: '/linkProps' + path: '/linkProps' + fullPath: '/linkProps' + preLoaderRoute: typeof LinkPropsRouteImport parentRoute: typeof rootRouteImport } '/params': { @@ -169,19 +162,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ParamsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/relative': { + id: '/relative' + path: '/relative' + fullPath: '/relative' + preLoaderRoute: typeof RelativeRouteImport parentRoute: typeof rootRouteImport } - '/search/searchPlaceholder': { - id: '/search/searchPlaceholder' - path: '/searchPlaceholder' - fullPath: '/search/searchPlaceholder' - preLoaderRoute: typeof SearchSearchPlaceholderRouteImport - parentRoute: typeof SearchRouteRoute + '/search': { + id: '/search' + path: '/search' + fullPath: '/search' + preLoaderRoute: typeof SearchRouteRouteImport + parentRoute: typeof rootRouteImport } '/params/$paramsPlaceholder': { id: '/params/$paramsPlaceholder' @@ -190,6 +183,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ParamsParamsPlaceholderRouteImport parentRoute: typeof ParamsRouteRoute } + '/search/searchPlaceholder': { + id: '/search/searchPlaceholder' + path: '/searchPlaceholder' + fullPath: '/search/searchPlaceholder' + preLoaderRoute: typeof SearchSearchPlaceholderRouteImport + parentRoute: typeof SearchRouteRoute + } } } diff --git a/examples/react/location-masking/package.json b/examples/react/location-masking/package.json index a43f090245..fe005c0d2f 100644 --- a/examples/react/location-masking/package.json +++ b/examples/react/location-masking/package.json @@ -11,9 +11,9 @@ "dependencies": { "@radix-ui/react-dialog": "^1.1.6", "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", + "@tanstack/react-query": "^5.102.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -23,7 +23,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/navigation-blocking/package.json b/examples/react/navigation-blocking/package.json index ebb1b4d3b1..a7677dfd51 100644 --- a/examples/react/navigation-blocking/package.json +++ b/examples/react/navigation-blocking/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", + "@tanstack/react-query": "^5.102.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -22,7 +22,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/quickstart-esbuild-file-based/esbuild.config.js b/examples/react/quickstart-esbuild-file-based/esbuild.config.js index fb7950d1fa..2f83a79984 100644 --- a/examples/react/quickstart-esbuild-file-based/esbuild.config.js +++ b/examples/react/quickstart-esbuild-file-based/esbuild.config.js @@ -7,5 +7,5 @@ export default { bundle: true, format: 'esm', target: ['esnext'], - plugins: [tanstackRouter({ target: 'react', autoCodeSplitting: true })], + plugins: [tanstackRouter({ target: 'react' })], } diff --git a/examples/react/quickstart-esbuild-file-based/package.json b/examples/react/quickstart-esbuild-file-based/package.json index 57203d5eec..d855694fec 100644 --- a/examples/react/quickstart-esbuild-file-based/package.json +++ b/examples/react/quickstart-esbuild-file-based/package.json @@ -9,9 +9,9 @@ "start": "dev" }, "dependencies": { - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/quickstart-file-based/package.json b/examples/react/quickstart-file-based/package.json index f89da750cc..976ec838d1 100644 --- a/examples/react/quickstart-file-based/package.json +++ b/examples/react/quickstart-file-based/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -23,7 +23,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/quickstart-file-based/src/routeTree.gen.ts b/examples/react/quickstart-file-based/src/routeTree.gen.ts index 59499d9fbf..12bc916ae4 100644 --- a/examples/react/quickstart-file-based/src/routeTree.gen.ts +++ b/examples/react/quickstart-file-based/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/quickstart-rspack-file-based/package.json b/examples/react/quickstart-rspack-file-based/package.json index 5ae8e4e737..824998f428 100644 --- a/examples/react/quickstart-rspack-file-based/package.json +++ b/examples/react/quickstart-rspack-file-based/package.json @@ -9,19 +9,20 @@ }, "dependencies": { "@tailwindcss/postcss": "^4.2.2", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "postcss": "^8.5.1", "react": "^19.0.0", "react-dom": "^19.0.0", "tailwindcss": "^4.2.2" }, "devDependencies": { - "@rsbuild/core": "^2.0.11", + "@rsbuild/core": "^2.3.1", "@rsbuild/plugin-react": "^2.0.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/router-plugin": "^1.169.0", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "typescript": "^6.0.2" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2" } } diff --git a/examples/react/quickstart-rspack-file-based/src/routeTree.gen.ts b/examples/react/quickstart-rspack-file-based/src/routeTree.gen.ts index 59499d9fbf..12bc916ae4 100644 --- a/examples/react/quickstart-rspack-file-based/src/routeTree.gen.ts +++ b/examples/react/quickstart-rspack-file-based/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/quickstart-webpack-file-based/package.json b/examples/react/quickstart-webpack-file-based/package.json index d5a729b1ff..baa14b89dd 100644 --- a/examples/react/quickstart-webpack-file-based/package.json +++ b/examples/react/quickstart-webpack-file-based/package.json @@ -7,20 +7,21 @@ "build": "webpack build && tsc --noEmit" }, "dependencies": { - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { "@swc/core": "^1.15.33", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/router-plugin": "^1.169.0", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "html-webpack-plugin": "^5.6.3", "react-refresh": "^0.18.0", "swc-loader": "^0.2.6", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "webpack": "^5.97.1", "webpack-cli": "^5.1.4", "webpack-dev-server": "^5.2.4" diff --git a/examples/react/quickstart-webpack-file-based/src/routeTree.gen.ts b/examples/react/quickstart-webpack-file-based/src/routeTree.gen.ts index 59499d9fbf..12bc916ae4 100644 --- a/examples/react/quickstart-webpack-file-based/src/routeTree.gen.ts +++ b/examples/react/quickstart-webpack-file-based/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/quickstart/package.json b/examples/react/quickstart/package.json index 983e3a00f6..b6db476ea8 100644 --- a/examples/react/quickstart/package.json +++ b/examples/react/quickstart/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "react": "^19.0.0", "react-dom": "^19.0.0", "tailwindcss": "^4.2.2" @@ -20,7 +20,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/router-monorepo-react-query/package.json b/examples/react/router-monorepo-react-query/package.json index b5cc722a6b..b158eeda56 100644 --- a/examples/react/router-monorepo-react-query/package.json +++ b/examples/react/router-monorepo-react-query/package.json @@ -10,11 +10,11 @@ "dev": "pnpm post-query build && pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" @@ -23,7 +23,8 @@ "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "@vitejs/plugin-react": "^6.0.1", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" diff --git a/examples/react/router-monorepo-react-query/packages/app/package.json b/examples/react/router-monorepo-react-query/packages/app/package.json index f4d7f184f8..f0994165c2 100644 --- a/examples/react/router-monorepo-react-query/packages/app/package.json +++ b/examples/react/router-monorepo-react-query/packages/app/package.json @@ -11,17 +11,18 @@ "dependencies": { "@router-mono-react-query/post-feature": "workspace:*", "@router-mono-react-query/router": "workspace:*", - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.0", + "@tanstack/react-router-devtools": "^1.167.3", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4", "@tailwindcss/vite": "^4.2.2" @@ -32,6 +33,12 @@ "dependsOn": [ "^build" ] + }, + "build": { + "inputs": [ + "...", + "{workspaceRoot}/examples/react/router-monorepo-react-query/.gitignore" + ] } } } diff --git a/examples/react/router-monorepo-react-query/packages/app/tsconfig.json b/examples/react/router-monorepo-react-query/packages/app/tsconfig.json index ce3a7d2339..196cb055a9 100644 --- a/examples/react/router-monorepo-react-query/packages/app/tsconfig.json +++ b/examples/react/router-monorepo-react-query/packages/app/tsconfig.json @@ -8,5 +8,6 @@ "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], "skipLibCheck": true - } + }, + "exclude": ["node_modules", "dist"] } diff --git a/examples/react/router-monorepo-react-query/packages/post-feature/package.json b/examples/react/router-monorepo-react-query/packages/post-feature/package.json index 9618fe3814..7f5e186ab0 100644 --- a/examples/react/router-monorepo-react-query/packages/post-feature/package.json +++ b/examples/react/router-monorepo-react-query/packages/post-feature/package.json @@ -8,7 +8,7 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@router-mono-react-query/post-query": "workspace:*", "@router-mono-react-query/router": "workspace:*", "react": "^19.0.0", @@ -18,7 +18,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } diff --git a/examples/react/router-monorepo-react-query/packages/post-query/package.json b/examples/react/router-monorepo-react-query/packages/post-query/package.json index 98833ff2dd..98a06051be 100644 --- a/examples/react/router-monorepo-react-query/packages/post-query/package.json +++ b/examples/react/router-monorepo-react-query/packages/post-query/package.json @@ -8,13 +8,14 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "redaxios": "^0.5.1", "zod": "^4.4.3" }, "devDependencies": { "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/router-monorepo-react-query/packages/router/package.json b/examples/react/router-monorepo-react-query/packages/router/package.json index 56d50596df..1397db14b5 100644 --- a/examples/react/router-monorepo-react-query/packages/router/package.json +++ b/examples/react/router-monorepo-react-query/packages/router/package.json @@ -9,10 +9,10 @@ "types": "./dist/index.d.ts", "dependencies": { "@router-mono-react-query/post-query": "workspace:*", - "@tanstack/history": "^1.162.0", - "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.170.18", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/history": "^1.162.5", + "@tanstack/react-query": "^5.102.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -22,7 +22,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } diff --git a/examples/react/router-monorepo-react-query/packages/router/src/routeTree.gen.ts b/examples/react/router-monorepo-react-query/packages/router/src/routeTree.gen.ts index 0820fc5f30..a4ed448d2f 100644 --- a/examples/react/router-monorepo-react-query/packages/router/src/routeTree.gen.ts +++ b/examples/react/router-monorepo-react-query/packages/router/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 PostIdRouteImport } from './routes/$postId' import { Route as IndexRouteImport } from './routes/index' +import { Route as PostIdRouteImport } from './routes/$postId' -const PostIdRoute = PostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const PostIdRoute = PostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/$postId': { - id: '/$postId' - path: '/$postId' - fullPath: '/$postId' - preLoaderRoute: typeof PostIdRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/$postId': { + id: '/$postId' + path: '/$postId' + fullPath: '/$postId' + preLoaderRoute: typeof PostIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/router-monorepo-simple-lazy/package.json b/examples/react/router-monorepo-simple-lazy/package.json index e259aba770..e044d86681 100644 --- a/examples/react/router-monorepo-simple-lazy/package.json +++ b/examples/react/router-monorepo-simple-lazy/package.json @@ -8,9 +8,9 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" @@ -20,7 +20,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" }, diff --git a/examples/react/router-monorepo-simple-lazy/packages/app/package.json b/examples/react/router-monorepo-simple-lazy/packages/app/package.json index a729b79fc9..cfc7a94942 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/app/package.json +++ b/examples/react/router-monorepo-simple-lazy/packages/app/package.json @@ -15,12 +15,13 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.0", + "@tanstack/react-router-devtools": "^1.167.3", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4", "@tailwindcss/vite": "^4.2.2" @@ -31,6 +32,12 @@ "dependsOn": [ "^build" ] + }, + "build": { + "inputs": [ + "...", + "{workspaceRoot}/examples/react/router-monorepo-simple-lazy/.gitignore" + ] } } } diff --git a/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json b/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json index ce3a7d2339..196cb055a9 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json +++ b/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json @@ -8,5 +8,6 @@ "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], "skipLibCheck": true - } + }, + "exclude": ["node_modules", "dist"] } diff --git a/examples/react/router-monorepo-simple-lazy/packages/post-feature/package.json b/examples/react/router-monorepo-simple-lazy/packages/post-feature/package.json index d2bd3c4cdf..65738d6025 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/post-feature/package.json +++ b/examples/react/router-monorepo-simple-lazy/packages/post-feature/package.json @@ -16,7 +16,7 @@ } }, "dependencies": { - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@router-mono-simple-lazy/router": "workspace:*", "react": "^19.0.0", "react-dom": "^19.0.0" @@ -25,7 +25,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } diff --git a/examples/react/router-monorepo-simple-lazy/packages/router/package.json b/examples/react/router-monorepo-simple-lazy/packages/router/package.json index c9ff6bb101..afd4702b5d 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/router/package.json +++ b/examples/react/router-monorepo-simple-lazy/packages/router/package.json @@ -8,9 +8,9 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.162.0", - "@tanstack/react-router": "^1.170.18", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/history": "^1.162.5", + "@tanstack/react-router": "^1.170.46", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -20,7 +20,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } diff --git a/examples/react/router-monorepo-simple-lazy/packages/router/src/routeTree.gen.ts b/examples/react/router-monorepo-simple-lazy/packages/router/src/routeTree.gen.ts index 0820fc5f30..a4ed448d2f 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/router/src/routeTree.gen.ts +++ b/examples/react/router-monorepo-simple-lazy/packages/router/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 PostIdRouteImport } from './routes/$postId' import { Route as IndexRouteImport } from './routes/index' +import { Route as PostIdRouteImport } from './routes/$postId' -const PostIdRoute = PostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const PostIdRoute = PostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/$postId': { - id: '/$postId' - path: '/$postId' - fullPath: '/$postId' - preLoaderRoute: typeof PostIdRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/$postId': { + id: '/$postId' + path: '/$postId' + fullPath: '/$postId' + preLoaderRoute: typeof PostIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/router-monorepo-simple/package.json b/examples/react/router-monorepo-simple/package.json index e126976126..800d948c81 100644 --- a/examples/react/router-monorepo-simple/package.json +++ b/examples/react/router-monorepo-simple/package.json @@ -8,9 +8,9 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" @@ -20,7 +20,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" }, diff --git a/examples/react/router-monorepo-simple/packages/app/package.json b/examples/react/router-monorepo-simple/packages/app/package.json index 3e2b86f6db..a06431ef86 100644 --- a/examples/react/router-monorepo-simple/packages/app/package.json +++ b/examples/react/router-monorepo-simple/packages/app/package.json @@ -15,12 +15,13 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.0", + "@tanstack/react-router-devtools": "^1.167.3", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4", "@tailwindcss/vite": "^4.2.2" @@ -31,6 +32,12 @@ "dependsOn": [ "^build" ] + }, + "build": { + "inputs": [ + "...", + "{workspaceRoot}/examples/react/router-monorepo-simple/.gitignore" + ] } } } diff --git a/examples/react/router-monorepo-simple/packages/app/tsconfig.json b/examples/react/router-monorepo-simple/packages/app/tsconfig.json index ce3a7d2339..196cb055a9 100644 --- a/examples/react/router-monorepo-simple/packages/app/tsconfig.json +++ b/examples/react/router-monorepo-simple/packages/app/tsconfig.json @@ -8,5 +8,6 @@ "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], "skipLibCheck": true - } + }, + "exclude": ["node_modules", "dist"] } diff --git a/examples/react/router-monorepo-simple/packages/post-feature/package.json b/examples/react/router-monorepo-simple/packages/post-feature/package.json index 9bdf4683c2..885aa6bbed 100644 --- a/examples/react/router-monorepo-simple/packages/post-feature/package.json +++ b/examples/react/router-monorepo-simple/packages/post-feature/package.json @@ -16,7 +16,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } diff --git a/examples/react/router-monorepo-simple/packages/router/package.json b/examples/react/router-monorepo-simple/packages/router/package.json index 0eae7a368b..391b72e610 100644 --- a/examples/react/router-monorepo-simple/packages/router/package.json +++ b/examples/react/router-monorepo-simple/packages/router/package.json @@ -8,9 +8,9 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.162.0", - "@tanstack/react-router": "^1.170.18", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/history": "^1.162.5", + "@tanstack/react-router": "^1.170.46", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -20,7 +20,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } diff --git a/examples/react/router-monorepo-simple/packages/router/src/routeTree.gen.ts b/examples/react/router-monorepo-simple/packages/router/src/routeTree.gen.ts index 0820fc5f30..a4ed448d2f 100644 --- a/examples/react/router-monorepo-simple/packages/router/src/routeTree.gen.ts +++ b/examples/react/router-monorepo-simple/packages/router/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 PostIdRouteImport } from './routes/$postId' import { Route as IndexRouteImport } from './routes/index' +import { Route as PostIdRouteImport } from './routes/$postId' -const PostIdRoute = PostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const PostIdRoute = PostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/$postId': { - id: '/$postId' - path: '/$postId' - fullPath: '/$postId' - preLoaderRoute: typeof PostIdRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/$postId': { + id: '/$postId' + path: '/$postId' + fullPath: '/$postId' + preLoaderRoute: typeof PostIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/scroll-restoration/package.json b/examples/react/scroll-restoration/package.json index caf8329f07..704ff13838 100644 --- a/examples/react/scroll-restoration/package.json +++ b/examples/react/scroll-restoration/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "@tanstack/react-virtual": "^3.13.0", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -21,7 +21,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/search-validator-adapters/package.json b/examples/react/search-validator-adapters/package.json index cfdeba55d5..35e041e825 100644 --- a/examples/react/search-validator-adapters/package.json +++ b/examples/react/search-validator-adapters/package.json @@ -12,10 +12,10 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/arktype-adapter": "^1.167.0", - "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/react-query": "^5.102.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "@tanstack/valibot-adapter": "^1.167.0", "@tanstack/zod-adapter": "^1.167.0", "arktype": "^2.1.7", @@ -26,12 +26,15 @@ "zod": "^3.24.2" }, "devDependencies": { - "@testing-library/jest-dom": "^6.6.3", + "@testing-library/jest-dom": "^7.0.1", "@testing-library/react": "^16.2.0", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", - "vite": "^8.0.14" + "@typescript/native": "npm:typescript@^7.0.2", + "jsdom": "^27.0.0", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vitest": "^5.0.4" } } diff --git a/examples/react/search-validator-adapters/src/routeTree.gen.ts b/examples/react/search-validator-adapters/src/routeTree.gen.ts index 4a973e1b29..d58c1ddfa1 100644 --- a/examples/react/search-validator-adapters/src/routeTree.gen.ts +++ b/examples/react/search-validator-adapters/src/routeTree.gen.ts @@ -10,18 +10,18 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersZodIndexRouteImport } from './routes/users/zod.index' -import { Route as UsersValibotIndexRouteImport } from './routes/users/valibot.index' import { Route as UsersArktypeIndexRouteImport } from './routes/users/arktype.index' +import { Route as UsersValibotIndexRouteImport } from './routes/users/valibot.index' +import { Route as UsersZodIndexRouteImport } from './routes/users/zod.index' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const UsersZodIndexRoute = UsersZodIndexRouteImport.update({ - id: '/users/zod/', - path: '/users/zod/', +const UsersArktypeIndexRoute = UsersArktypeIndexRouteImport.update({ + id: '/users/arktype/', + path: '/users/arktype/', getParentRoute: () => rootRouteImport, } as any) const UsersValibotIndexRoute = UsersValibotIndexRouteImport.update({ @@ -29,9 +29,9 @@ const UsersValibotIndexRoute = UsersValibotIndexRouteImport.update({ path: '/users/valibot/', getParentRoute: () => rootRouteImport, } as any) -const UsersArktypeIndexRoute = UsersArktypeIndexRouteImport.update({ - id: '/users/arktype/', - path: '/users/arktype/', +const UsersZodIndexRoute = UsersZodIndexRouteImport.update({ + id: '/users/zod/', + path: '/users/zod/', getParentRoute: () => rootRouteImport, } as any) @@ -78,11 +78,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/users/zod/': { - id: '/users/zod/' - path: '/users/zod' - fullPath: '/users/zod/' - preLoaderRoute: typeof UsersZodIndexRouteImport + '/users/arktype/': { + id: '/users/arktype/' + path: '/users/arktype' + fullPath: '/users/arktype/' + preLoaderRoute: typeof UsersArktypeIndexRouteImport parentRoute: typeof rootRouteImport } '/users/valibot/': { @@ -92,11 +92,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof UsersValibotIndexRouteImport parentRoute: typeof rootRouteImport } - '/users/arktype/': { - id: '/users/arktype/' - path: '/users/arktype' - fullPath: '/users/arktype/' - preLoaderRoute: typeof UsersArktypeIndexRouteImport + '/users/zod/': { + id: '/users/zod/' + path: '/users/zod' + fullPath: '/users/zod/' + preLoaderRoute: typeof UsersZodIndexRouteImport parentRoute: typeof rootRouteImport } } diff --git a/examples/react/search-validator-adapters/tests/arktype.test.tsx b/examples/react/search-validator-adapters/tests/arktype.test.tsx index 1c3a1baf76..776cc8369e 100644 --- a/examples/react/search-validator-adapters/tests/arktype.test.tsx +++ b/examples/react/search-validator-adapters/tests/arktype.test.tsx @@ -8,7 +8,6 @@ import { createRouter, } from '@tanstack/react-router' -import '@testing-library/jest-dom/vitest' import { type } from 'arktype' test('can navigate to the route', async () => { diff --git a/examples/react/search-validator-adapters/tests/jest-dom.setup.ts b/examples/react/search-validator-adapters/tests/jest-dom.setup.ts new file mode 100644 index 0000000000..8f7cbf15be --- /dev/null +++ b/examples/react/search-validator-adapters/tests/jest-dom.setup.ts @@ -0,0 +1,18 @@ +import * as jestDomMatchers from '@testing-library/jest-dom/matchers' +import { expect } from 'vitest' +import type { TestingLibraryMatchers } from '@testing-library/jest-dom/matchers' + +// Workaround for Vitest 5: remove once testing-library/jest-dom#742 is merged +// and released, and go back to `import '@testing-library/jest-dom/vitest'`. +// That entry imports `vitest` from its own install location, which can resolve +// a different Vitest copy than the one running these tests, and its types +// augment Vitest 4's `Assertion` instead of Vitest 5's `Matchers`. +// Keep `jest-dom` in this file name: vite-plugin-solid only skips injecting +// `@testing-library/jest-dom/vitest` when a setup file path contains it. +expect.extend(jestDomMatchers) + +declare module 'vitest' { + // Type parameter names must match Vitest's declaration for the interfaces to merge. + // eslint-disable-next-line @typescript-eslint/naming-convention + interface Matchers extends TestingLibraryMatchers {} +} diff --git a/examples/react/search-validator-adapters/tests/valibot.test.tsx b/examples/react/search-validator-adapters/tests/valibot.test.tsx index 3680d2302c..d3e18db414 100644 --- a/examples/react/search-validator-adapters/tests/valibot.test.tsx +++ b/examples/react/search-validator-adapters/tests/valibot.test.tsx @@ -8,7 +8,6 @@ import { createRouter, } from '@tanstack/react-router' import * as v from 'valibot' -import '@testing-library/jest-dom/vitest' test('can navigate to the route', async () => { const rootRoute = createRootRoute() diff --git a/examples/react/search-validator-adapters/vite.config.ts b/examples/react/search-validator-adapters/vite.config.ts index 5b41e6e26b..e4b93f5cc3 100644 --- a/examples/react/search-validator-adapters/vite.config.ts +++ b/examples/react/search-validator-adapters/vite.config.ts @@ -11,6 +11,7 @@ export default defineConfig({ watch: false, environment: 'jsdom', typecheck: { enabled: true }, + setupFiles: ['./tests/jest-dom.setup.ts'], }, plugins: [ tailwindcss(), diff --git a/examples/react/start-bare/package.json b/examples/react/start-bare/package.json index d0ff2ea336..4ab9aff272 100644 --- a/examples/react/start-bare/package.json +++ b/examples/react/start-bare/package.json @@ -10,9 +10,9 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.28", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0", "zod": "^4.4.3" @@ -22,7 +22,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/start-bare/src/routeTree.gen.ts b/examples/react/start-bare/src/routeTree.gen.ts index 421daf2790..d89758e684 100644 --- a/examples/react/start-bare/src/routeTree.gen.ts +++ b/examples/react/start-bare/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/start-bare/src/router.tsx b/examples/react/start-bare/src/router.tsx index a464233af9..6f82cbf378 100644 --- a/examples/react/start-bare/src/router.tsx +++ b/examples/react/start-bare/src/router.tsx @@ -5,7 +5,9 @@ export function getRouter() { const router = createRouter({ routeTree, defaultPreload: 'intent', - defaultErrorComponent: (err) =>

{err.error.stack}

, + defaultErrorComponent: (err) => ( +

{err.error instanceof Error ? err.error.stack : String(err.error)}

+ ), defaultNotFoundComponent: () =>

not found

, scrollRestoration: true, }) diff --git a/examples/react/start-basic-auth/README.md b/examples/react/start-basic-auth/README.md index 4e5ee29b40..7f1b093ba5 100644 --- a/examples/react/start-basic-auth/README.md +++ b/examples/react/start-basic-auth/README.md @@ -39,3 +39,13 @@ This example demonstrates: - Protected routes - Login/logout functionality - Redirect after authentication + +## Session configuration + +This example uses [iron-session](https://github.com/vvo/iron-session) through Start's `getCookie` and `setCookie` helpers. Set `SESSION_PASSWORD` to a random secret of at least 32 characters before starting the app, for example: + +```sh +export SESSION_PASSWORD="$(openssl rand -base64 32)" +``` + +Keep the same secret across instances and deployments that must read the same sessions. The cookie requires HTTPS in production. Each handler reads its own session, then awaits `session.save()` before redirecting or returning. diff --git a/examples/react/start-basic-auth/package.json b/examples/react/start-basic-auth/package.json index 4533b4bee1..9ab89bdac9 100644 --- a/examples/react/start-basic-auth/package.json +++ b/examples/react/start-basic-auth/package.json @@ -14,9 +14,10 @@ "@libsql/client": "^0.15.15", "@prisma/adapter-libsql": "^7.0.0", "@prisma/client": "^7.0.0", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.28", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", + "iron-session": "^9.0.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -31,7 +32,8 @@ "dotenv": "^17.2.3", "prisma": "^7.0.0", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/start-basic-auth/src/routeTree.gen.ts b/examples/react/start-basic-auth/src/routeTree.gen.ts index 389f656645..a74e753aec 100644 --- a/examples/react/start-basic-auth/src/routeTree.gen.ts +++ b/examples/react/start-basic-auth/src/routeTree.gen.ts @@ -9,23 +9,22 @@ // 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 SignupRouteImport } from './routes/signup' -import { Route as LogoutRouteImport } from './routes/logout' -import { Route as LoginRouteImport } from './routes/login' -import { Route as AuthedRouteImport } from './routes/_authed' import { Route as IndexRouteImport } from './routes/index' +import { Route as AuthedRouteImport } from './routes/_authed' +import { Route as LoginRouteImport } from './routes/login' +import { Route as LogoutRouteImport } from './routes/logout' +import { Route as SignupRouteImport } from './routes/signup' import { Route as AuthedPostsRouteRouteImport } from './routes/_authed/posts.route' import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' -const SignupRoute = SignupRouteImport.update({ - id: '/signup', - path: '/signup', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', getParentRoute: () => rootRouteImport, } as any) const LoginRoute = LoginRouteImport.update({ @@ -33,13 +32,14 @@ const LoginRoute = LoginRouteImport.update({ path: '/login', getParentRoute: () => rootRouteImport, } as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', +const LogoutRoute = LogoutRouteImport.update({ + id: '/logout', + path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SignupRoute = SignupRouteImport.update({ + id: '/signup', + path: '/signup', getParentRoute: () => rootRouteImport, } as any) const AuthedPostsRouteRoute = AuthedPostsRouteRouteImport.update({ @@ -120,25 +120,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/signup': { - id: '/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof SignupRouteImport - parentRoute: typeof rootRouteImport - } - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport - parentRoute: typeof rootRouteImport - } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_authed': { @@ -148,11 +134,25 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthedRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport + } + '/logout': { + id: '/logout' + path: '/logout' + fullPath: '/logout' + preLoaderRoute: typeof LogoutRouteImport + parentRoute: typeof rootRouteImport + } + '/signup': { + id: '/signup' + path: '/signup' + fullPath: '/signup' + preLoaderRoute: typeof SignupRouteImport parentRoute: typeof rootRouteImport } '/_authed/posts': { diff --git a/examples/react/start-basic-auth/src/routes/__root.tsx b/examples/react/start-basic-auth/src/routes/__root.tsx index 5728345fcf..3367c62f27 100644 --- a/examples/react/start-basic-auth/src/routes/__root.tsx +++ b/examples/react/start-basic-auth/src/routes/__root.tsx @@ -13,18 +13,18 @@ import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' import { NotFound } from '~/components/NotFound.js' import appCss from '~/styles/app.css?url' import { seo } from '~/utils/seo.js' -import { useAppSession } from '~/utils/session.js' +import { getAppSession } from '~/utils/session.js' const fetchUser = createServerFn({ method: 'GET' }).handler(async () => { // We need to auth on the server so we have access to secure cookies - const session = await useAppSession() + const session = await getAppSession() - if (!session.data.userEmail) { + if (!session.userEmail) { return null } return { - email: session.data.userEmail, + email: session.userEmail, } }) diff --git a/examples/react/start-basic-auth/src/routes/_authed.tsx b/examples/react/start-basic-auth/src/routes/_authed.tsx index 3944e590f9..0b5c6f9047 100644 --- a/examples/react/start-basic-auth/src/routes/_authed.tsx +++ b/examples/react/start-basic-auth/src/routes/_authed.tsx @@ -2,7 +2,7 @@ import { createFileRoute } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { Login } from '~/components/Login' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST' }) .validator((d: { email: string; password: string }) => d) @@ -33,13 +33,10 @@ export const loginFn = createServerFn({ method: 'POST' }) } } - // Create a session - const session = await useAppSession() - // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + const session = await getAppSession() + session.userEmail = user.email + await session.save() }) export const Route = createFileRoute('/_authed')({ @@ -49,7 +46,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error.message === 'Not authenticated') { + if (error instanceof Error && error.message === 'Not authenticated') { return } diff --git a/examples/react/start-basic-auth/src/routes/logout.tsx b/examples/react/start-basic-auth/src/routes/logout.tsx index 28f3c9f8fe..73cdaf1600 100644 --- a/examples/react/start-basic-auth/src/routes/logout.tsx +++ b/examples/react/start-basic-auth/src/routes/logout.tsx @@ -1,11 +1,10 @@ import { redirect, createFileRoute } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' const logoutFn = createServerFn().handler(async () => { - const session = await useAppSession() - - session.clear() + const session = await getAppSession() + session.destroy() throw redirect({ href: '/', diff --git a/examples/react/start-basic-auth/src/routes/signup.tsx b/examples/react/start-basic-auth/src/routes/signup.tsx index 247a94c03c..4dc8e350ac 100644 --- a/examples/react/start-basic-auth/src/routes/signup.tsx +++ b/examples/react/start-basic-auth/src/routes/signup.tsx @@ -3,7 +3,7 @@ import { createServerFn, useServerFn } from '@tanstack/react-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { useMutation } from '~/hooks/useMutation' import { Auth } from '~/components/Auth' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' export const signupFn = createServerFn({ method: 'POST' }) .validator( @@ -20,9 +20,6 @@ export const signupFn = createServerFn({ method: 'POST' }) // Encrypt the password using Sha256 into plaintext const password = await hashPassword(data.password) - // Create a session - const session = await useAppSession() - if (found) { if (found.password !== password) { return { @@ -33,9 +30,9 @@ export const signupFn = createServerFn({ method: 'POST' }) } // Store the user's email in the session - await session.update({ - userEmail: found.email, - }) + const session = await getAppSession() + session.userEmail = found.email + await session.save() // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -52,9 +49,9 @@ export const signupFn = createServerFn({ method: 'POST' }) }) // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + const session = await getAppSession() + session.userEmail = user.email + await session.save() // Redirect to the prev page stored in the "redirect" search param throw redirect({ diff --git a/examples/react/start-basic-auth/src/utils/session.ts b/examples/react/start-basic-auth/src/utils/session.ts index c38bac1e48..7df7bc4da2 100644 --- a/examples/react/start-basic-auth/src/utils/session.ts +++ b/examples/react/start-basic-auth/src/utils/session.ts @@ -1,13 +1,29 @@ -// src/services/session.server.ts -import { useSession } from '@tanstack/react-start/server' +import { getIronSession } from 'iron-session' +import { getCookie, setCookie } from '@tanstack/react-start/server' import type { User } from '@prisma/client' type SessionUser = { userEmail: User['email'] } -export function useAppSession() { - return useSession({ - password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', - }) +export function getAppSession() { + const password = process.env.SESSION_PASSWORD + if (!password || password.length < 32) { + throw new Error('Set SESSION_PASSWORD to at least 32 characters') + } + + return getIronSession( + { read: getCookie, write: setCookie }, + { + cookieName: 'app-session', + password, + ttl: 7 * 24 * 60 * 60, + cookieOptions: { + httpOnly: true, + sameSite: 'lax', + secure: process.env.NODE_ENV === 'production', + path: '/', + }, + }, + ) } diff --git a/examples/react/start-basic-authjs/package.json b/examples/react/start-basic-authjs/package.json index ba1628938d..e9fa789ea6 100644 --- a/examples/react/start-basic-authjs/package.json +++ b/examples/react/start-basic-authjs/package.json @@ -11,9 +11,9 @@ }, "dependencies": { "@auth/core": "^0.41.1", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.28", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0", "start-authjs": "^1.0.0", @@ -26,7 +26,8 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/start-basic-authjs/src/routeTree.gen.ts b/examples/react/start-basic-authjs/src/routeTree.gen.ts index 2f59e4ba33..4abcbc8048 100644 --- a/examples/react/start-basic-authjs/src/routeTree.gen.ts +++ b/examples/react/start-basic-authjs/src/routeTree.gen.ts @@ -9,14 +9,14 @@ // 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 ProtectedRouteImport } from './routes/protected' -import { Route as LoginRouteImport } from './routes/login' import { Route as IndexRouteImport } from './routes/index' +import { Route as LoginRouteImport } from './routes/login' +import { Route as ProtectedRouteImport } from './routes/protected' import { Route as ApiAuthSplatRouteImport } from './routes/api/auth/$' -const ProtectedRoute = ProtectedRouteImport.update({ - id: '/protected', - path: '/protected', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const LoginRoute = LoginRouteImport.update({ @@ -24,9 +24,9 @@ const LoginRoute = LoginRouteImport.update({ path: '/login', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ProtectedRoute = ProtectedRouteImport.update({ + id: '/protected', + path: '/protected', getParentRoute: () => rootRouteImport, } as any) const ApiAuthSplatRoute = ApiAuthSplatRouteImport.update({ @@ -71,11 +71,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/protected': { - id: '/protected' - path: '/protected' - fullPath: '/protected' - preLoaderRoute: typeof ProtectedRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/login': { @@ -85,11 +85,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/protected': { + id: '/protected' + path: '/protected' + fullPath: '/protected' + preLoaderRoute: typeof ProtectedRouteImport parentRoute: typeof rootRouteImport } '/api/auth/$': { diff --git a/examples/react/start-basic-cloudflare/package.json b/examples/react/start-basic-cloudflare/package.json index 78a01c103a..2108922446 100644 --- a/examples/react/start-basic-cloudflare/package.json +++ b/examples/react/start-basic-cloudflare/package.json @@ -12,9 +12,9 @@ "postinstall": "WRANGLER_LOG=warn npm run --silent cf-typegen" }, "dependencies": { - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.28", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0" }, @@ -26,7 +26,8 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "wrangler": "^4.74.0" } diff --git a/examples/react/start-basic-cloudflare/src/routeTree.gen.ts b/examples/react/start-basic-cloudflare/src/routeTree.gen.ts index 0bd698a666..57b849492d 100644 --- a/examples/react/start-basic-cloudflare/src/routeTree.gen.ts +++ b/examples/react/start-basic-cloudflare/src/routeTree.gen.ts @@ -9,42 +9,31 @@ // 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 UsersRouteImport } from './routes/users' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as UsersRouteImport } from './routes/users' import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ @@ -52,38 +41,24 @@ const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ path: '/customScript.js', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', + getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = @@ -91,28 +66,53 @@ const PathlessLayoutNestedLayoutRoute = id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) -const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', - getParentRoute: () => ApiUsersRoute, + getParentRoute: () => UsersRoute, } as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) const PathlessLayoutNestedLayoutRouteARoute = PathlessLayoutNestedLayoutRouteARouteImport.update({ id: '/route-a', path: '/route-a', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteBRoute = + PathlessLayoutNestedLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => ApiUsersRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -234,39 +234,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/customScript.js': { - id: '/customScript.js' - path: '/customScript.js' - fullPath: '/customScript.js' - preLoaderRoute: typeof CustomScriptDotjsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout': { @@ -276,46 +248,39 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/customScript.js': { + id: '/customScript.js' + path: '/customScript.js' + fullPath: '/customScript.js' + preLoaderRoute: typeof CustomScriptDotjsRouteImport parentRoute: typeof rootRouteImport } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout/_nested-layout': { @@ -325,19 +290,47 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport parentRoute: typeof PathlessLayoutRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/api/users/$userId': { - id: '/api/users/$userId' + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute + } + '/users/$userId': { + id: '/users/$userId' path: '/$userId' - fullPath: '/api/users/$userId' - preLoaderRoute: typeof ApiUsersUserIdRouteImport - parentRoute: typeof ApiUsersRoute + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -346,12 +339,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/api/users/$userId': { + id: '/api/users/$userId' + path: '/$userId' + fullPath: '/api/users/$userId' + preLoaderRoute: typeof ApiUsersUserIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/examples/react/start-basic-react-query/README.md b/examples/react/start-basic-react-query/README.md index 77c61c2504..70cc728ae4 100644 --- a/examples/react/start-basic-react-query/README.md +++ b/examples/react/start-basic-react-query/README.md @@ -38,5 +38,18 @@ This example demonstrates how to use TanStack Query with TanStack Start for: - Server-side data fetching - Client-side caching and synchronization -- Optimistic updates -- Automatic refetching +- Confirmed server mutations followed by query invalidation +- Explicit freshness and automatic refetching + +## SSR and mutation checks + +Read the [Start + TanStack Query guide](https://tanstack.com/start/latest/docs/framework/react/guide/tanstack-query). The `/preferences` page stores a harmless display name in a cookie, so its tests need no account or external API. This cookie is not authentication. The other post/user examples use JSONPlaceholder. + +```sh +pnpm exec playwright install chromium +pnpm test:e2e +pnpm build +QUERY_EXAMPLE_PRODUCTION=1 pnpm test:e2e +``` + +The tests check concurrent SSR request isolation, no duplicate hydration read, one refetch after mutation invalidation, and persistence on reload. Query data is fresh for 30 seconds by default in this example; choose a window appropriate for your application. diff --git a/examples/react/start-basic-react-query/package.json b/examples/react/start-basic-react-query/package.json index a39283577f..9d819d4390 100644 --- a/examples/react/start-basic-react-query/package.json +++ b/examples/react/start-basic-react-query/package.json @@ -7,15 +7,16 @@ "dev": "vite dev", "build": "vite build && tsc --noEmit", "preview": "vite preview", - "start": "pnpx srvx --prod -s ../client dist/server/server.js" + "start": "pnpx srvx --prod -s ../client dist/server/server.js", + "test:e2e": "playwright test" }, "dependencies": { - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-router-ssr-query": "^1.167.1", - "@tanstack/react-start": "^1.168.28", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router-ssr-query": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -28,7 +29,9 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", - "vite": "^8.0.14" + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "@playwright/test": "^1.61.0" } } diff --git a/examples/react/start-basic-react-query/playwright.config.ts b/examples/react/start-basic-react-query/playwright.config.ts new file mode 100644 index 0000000000..298a1133e9 --- /dev/null +++ b/examples/react/start-basic-react-query/playwright.config.ts @@ -0,0 +1,14 @@ +import { defineConfig } from '@playwright/test' + +export default defineConfig({ + testDir: './tests', + use: { baseURL: 'http://localhost:3110', browserName: 'chromium' }, + webServer: { + command: + process.env.QUERY_EXAMPLE_PRODUCTION === '1' + ? 'PORT=3110 pnpm start' + : 'pnpm dev --port 3110', + url: 'http://localhost:3110/preferences', + timeout: 120_000, + }, +}) diff --git a/examples/react/start-basic-react-query/src/routeTree.gen.ts b/examples/react/start-basic-react-query/src/routeTree.gen.ts index a3a4ddf49f..0c7a90d4a1 100644 --- a/examples/react/start-basic-react-query/src/routeTree.gen.ts +++ b/examples/react/start-basic-react-query/src/routeTree.gen.ts @@ -9,26 +9,31 @@ // 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 RedirectRouteImport } from './routes/redirect' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as UsersRouteRouteImport } from './routes/users.route' -import { Route as PostsRouteRouteImport } from './routes/posts.route' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteRouteImport } from './routes/posts.route' +import { Route as PreferencesRouteImport } from './routes/preferences' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as UsersRouteRouteImport } from './routes/users.route' import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const DeferredRoute = DeferredRouteImport.update({ @@ -36,8 +41,19 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const PostsRouteRoute = PostsRouteRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const PreferencesRoute = PreferencesRouteImport.update({ + id: '/preferences', + path: '/preferences', + getParentRoute: () => rootRouteImport, +} as any) +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', getParentRoute: () => rootRouteImport, } as any) const UsersRouteRoute = UsersRouteRouteImport.update({ @@ -45,74 +61,65 @@ const UsersRouteRoute = UsersRouteRouteImport.update({ path: '/users', getParentRoute: () => rootRouteImport, } as any) -const PostsRouteRoute = PostsRouteRouteImport.update({ - id: '/posts', - path: '/posts', +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, + } as any) +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRouteRoute, -} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => PostsRouteRoute, } as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRouteRoute, -} as any) const PostsPostIdRoute = PostsPostIdRouteImport.update({ id: '/$postId', path: '/$postId', getParentRoute: () => PostsRouteRoute, } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', - getParentRoute: () => rootRouteImport, +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRouteRoute, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRouteRoute, } as any) -const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => ApiUsersRoute, -} as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) const PathlessLayoutNestedLayoutRouteARoute = PathlessLayoutNestedLayoutRouteARouteImport.update({ id: '/route-a', path: '/route-a', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteBRoute = + PathlessLayoutNestedLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => ApiUsersRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute '/posts': typeof PostsRouteRouteWithChildren '/users': typeof UsersRouteRouteWithChildren '/deferred': typeof DeferredRoute + '/preferences': typeof PreferencesRoute '/redirect': typeof RedirectRoute '/api/users': typeof ApiUsersRouteWithChildren '/posts/$postId': typeof PostsPostIdRoute @@ -127,6 +134,7 @@ export interface FileRoutesByFullPath { export interface FileRoutesByTo { '/': typeof IndexRoute '/deferred': typeof DeferredRoute + '/preferences': typeof PreferencesRoute '/redirect': typeof RedirectRoute '/api/users': typeof ApiUsersRouteWithChildren '/posts/$postId': typeof PostsPostIdRoute @@ -145,6 +153,7 @@ export interface FileRoutesById { '/users': typeof UsersRouteRouteWithChildren '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren '/deferred': typeof DeferredRoute + '/preferences': typeof PreferencesRoute '/redirect': typeof RedirectRoute '/_pathlessLayout/_nested-layout': typeof PathlessLayoutNestedLayoutRouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren @@ -164,6 +173,7 @@ export interface FileRouteTypes { | '/posts' | '/users' | '/deferred' + | '/preferences' | '/redirect' | '/api/users' | '/posts/$postId' @@ -178,6 +188,7 @@ export interface FileRouteTypes { to: | '/' | '/deferred' + | '/preferences' | '/redirect' | '/api/users' | '/posts/$postId' @@ -195,6 +206,7 @@ export interface FileRouteTypes { | '/users' | '/_pathlessLayout' | '/deferred' + | '/preferences' | '/redirect' | '/_pathlessLayout/_nested-layout' | '/api/users' @@ -214,6 +226,7 @@ export interface RootRouteChildren { UsersRouteRoute: typeof UsersRouteRouteWithChildren PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren DeferredRoute: typeof DeferredRoute + PreferencesRoute: typeof PreferencesRoute RedirectRoute: typeof RedirectRoute ApiUsersRoute: typeof ApiUsersRouteWithChildren PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute @@ -221,18 +234,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout': { @@ -242,11 +248,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteRouteImport + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } '/posts': { @@ -256,46 +262,25 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/preferences': { + id: '/preferences' + path: '/preferences' + fullPath: '/preferences' + preLoaderRoute: typeof PreferencesRouteImport parentRoute: typeof rootRouteImport } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRouteRoute + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRouteRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRouteRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRouteRoute - } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout/_nested-layout': { @@ -305,19 +290,47 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport parentRoute: typeof PathlessLayoutRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/api/users/$id': { - id: '/api/users/$id' - path: '/$id' - fullPath: '/api/users/$id' - preLoaderRoute: typeof ApiUsersIdRouteImport - parentRoute: typeof ApiUsersRoute + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRouteRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRouteRoute + } + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRouteRoute + } + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRouteRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -326,12 +339,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/api/users/$id': { + id: '/api/users/$id' + path: '/$id' + fullPath: '/api/users/$id' + preLoaderRoute: typeof ApiUsersIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } } } @@ -412,6 +432,7 @@ const rootRouteChildren: RootRouteChildren = { UsersRouteRoute: UsersRouteRouteWithChildren, PathlessLayoutRoute: PathlessLayoutRouteWithChildren, DeferredRoute: DeferredRoute, + PreferencesRoute: PreferencesRoute, RedirectRoute: RedirectRoute, ApiUsersRoute: ApiUsersRouteWithChildren, PostsPostIdDeepRoute: PostsPostIdDeepRoute, @@ -421,10 +442,11 @@ export const routeTree = rootRouteImport ._addFileTypes() import type { getRouter } from './router.tsx' -import type { createStart } from '@tanstack/react-start' +import type { startInstance } from './start.ts' declare module '@tanstack/react-start' { interface Register { ssr: true router: Awaited> + config: Awaited> } } diff --git a/examples/react/start-basic-react-query/src/router.tsx b/examples/react/start-basic-react-query/src/router.tsx index 314b29edd0..345055c116 100644 --- a/examples/react/start-basic-react-query/src/router.tsx +++ b/examples/react/start-basic-react-query/src/router.tsx @@ -6,12 +6,15 @@ import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' import { NotFound } from './components/NotFound' export function getRouter() { - const queryClient = new QueryClient() + const queryClient = new QueryClient({ + defaultOptions: { queries: { staleTime: 30_000 } }, + }) const router = createRouter({ routeTree, context: { queryClient }, defaultPreload: 'intent', + defaultPreloadStaleTime: 0, defaultErrorComponent: DefaultCatchBoundary, defaultNotFoundComponent: () => , }) diff --git a/examples/react/start-basic-react-query/src/routes/__root.tsx b/examples/react/start-basic-react-query/src/routes/__root.tsx index bc278f8036..71c19b2c6f 100644 --- a/examples/react/start-basic-react-query/src/routes/__root.tsx +++ b/examples/react/start-basic-react-query/src/routes/__root.tsx @@ -83,6 +83,7 @@ function RootDocument({ children }: { children: React.ReactNode }) {
+ Preferences { + await context.queryClient.query(readerNameOptions) + }, + headers: () => ({ 'Cache-Control': 'private, no-store' }), + head: () => ({ meta: [{ title: 'Reader preferences' }] }), + component: Preferences, +}) + +function Preferences() { + const { data: name } = useSuspenseQuery(readerNameOptions) + const queryClient = useQueryClient() + const save = useServerFn(saveReaderName) + const hydrated = useHydrated() + const mutation = useMutation({ + mutationFn: (name: string) => save({ data: name }), + onSuccess: () => + queryClient.invalidateQueries({ queryKey: readerNameOptions.queryKey }), + }) + + return ( +
+

Reader preferences

+

Hello, {name}

+
{ + event.preventDefault() + const value = new FormData(event.currentTarget).get('name') + if (typeof value === 'string') { + mutation.mutate(value) + } + }} + > +
+ + +
+ {mutation.isError ? ( +

Could not save your name. Try again.

+ ) : null} +
+
+ ) +} diff --git a/examples/react/start-basic-react-query/src/start.ts b/examples/react/start-basic-react-query/src/start.ts new file mode 100644 index 0000000000..5fb1e247fb --- /dev/null +++ b/examples/react/start-basic-react-query/src/start.ts @@ -0,0 +1,9 @@ +import { createCsrfMiddleware, createStart } from '@tanstack/react-start' + +export const startInstance = createStart(() => ({ + requestMiddleware: [ + createCsrfMiddleware({ + filter: (ctx) => ctx.handlerType === 'serverFn', + }), + ], +})) diff --git a/examples/react/start-basic-react-query/src/utils/preferences.ts b/examples/react/start-basic-react-query/src/utils/preferences.ts new file mode 100644 index 0000000000..74c33e5848 --- /dev/null +++ b/examples/react/start-basic-react-query/src/utils/preferences.ts @@ -0,0 +1,34 @@ +import { queryOptions } from '@tanstack/react-query' +import { createServerFn } from '@tanstack/react-start' +import { + getCookie, + setCookie, + setResponseHeader, +} from '@tanstack/react-start/server' + +export const getReaderName = createServerFn({ method: 'GET' }).handler(() => { + setResponseHeader('Cache-Control', 'private, no-store') + return getCookie('reader-name') || 'Guest' +}) + +export const saveReaderName = createServerFn({ method: 'POST' }) + .validator((name: string) => { + if (typeof name !== 'string' || !name.trim() || name.length > 40) { + throw new Error('Enter a name between 1 and 40 characters') + } + return name.trim() + }) + .handler(({ data }) => { + setResponseHeader('Cache-Control', 'private, no-store') + setCookie('reader-name', data, { + httpOnly: true, + sameSite: 'lax', + secure: process.env.NODE_ENV === 'production', + path: '/', + }) + }) + +export const readerNameOptions = queryOptions({ + queryKey: ['reader-name'], + queryFn: () => getReaderName(), +}) diff --git a/examples/react/start-basic-react-query/tests/preferences.spec.ts b/examples/react/start-basic-react-query/tests/preferences.spec.ts new file mode 100644 index 0000000000..309c402798 --- /dev/null +++ b/examples/react/start-basic-react-query/tests/preferences.spec.ts @@ -0,0 +1,67 @@ +import { expect, test } from '@playwright/test' + +test('concurrent SSR requests keep the same query key isolated by request', async ({ + request, +}) => { + const names = ['Lucia', 'Omar', 'Maya', 'Felix'] + const responses = await Promise.all( + names.map((name) => + request.get('/preferences', { + headers: { Cookie: `reader-name=${name}` }, + }), + ), + ) + for (const [index, response] of responses.entries()) { + expect(response.status()).toBe(200) + expect(response.headers()['cache-control']).toContain('no-store') + const html = await response.text() + expect(html).toContain(names[index]) + for (const other of names.filter((_, otherIndex) => otherIndex !== index)) { + expect(html).not.toContain(other) + } + } +}) + +test('hydration reuses SSR data and mutation invalidation refetches once', async ({ + page, +}) => { + const reads: string[] = [] + page.on('request', (request) => { + if ( + request.method() === 'GET' && + new URL(request.url()).pathname.startsWith('/_serverFn/') + ) { + reads.push(request.url()) + } + }) + await page.goto('/preferences') + await expect(page.getByTestId('reader-name')).toHaveText('Hello, Guest') + await expect(page.getByLabel('Display name')).toBeEnabled() + await page.waitForLoadState('networkidle') + expect(reads).toHaveLength(0) + + await page.getByLabel('Display name').fill('Ada') + const mutation = page.waitForRequest((request) => request.method() === 'POST') + await page.getByRole('button', { name: 'Save name' }).click() + await expect(page.getByTestId('reader-name')).toHaveText('Hello, Ada') + await expect(page.getByRole('button', { name: 'Save name' })).toBeEnabled() + await page.waitForLoadState('networkidle') + expect(reads).toHaveLength(1) + + const savedRequest = await mutation + const headers = await savedRequest.allHeaders() + delete headers['content-length'] + headers.origin = 'https://untrusted.example' + headers['sec-fetch-site'] = 'cross-site' + const denied = await page.request.post(savedRequest.url(), { + headers, + data: savedRequest.postData() ?? '', + }) + expect(denied.status()).toBe(403) + + await page.reload() + await expect(page.getByTestId('reader-name')).toHaveText('Hello, Ada') + await expect(page.getByLabel('Display name')).toBeEnabled() + await page.waitForLoadState('networkidle') + expect(reads).toHaveLength(1) +}) diff --git a/examples/react/start-basic-rsbuild/.devcontainer/devcontainer.json b/examples/react/start-basic-rsbuild/.devcontainer/devcontainer.json new file mode 100644 index 0000000000..e5dafce188 --- /dev/null +++ b/examples/react/start-basic-rsbuild/.devcontainer/devcontainer.json @@ -0,0 +1,3 @@ +{ + "image": "mcr.microsoft.com/devcontainers/typescript-node:24" +} diff --git a/examples/react/start-basic-rsbuild/.gitignore b/examples/react/start-basic-rsbuild/.gitignore new file mode 100644 index 0000000000..1f189d9bc0 --- /dev/null +++ b/examples/react/start-basic-rsbuild/.gitignore @@ -0,0 +1,19 @@ +node_modules +package-lock.json +yarn.lock + +.DS_Store +.cache +.env +.vercel +dist +/build/ +/api/ +/server/build +/public/build# Sentry Config File +.env.sentry-build-plugin +/test-results/ +/playwright-report/ +/blob-report/ +/playwright/.cache/ +.tanstack diff --git a/examples/react/start-basic-rsbuild/.prettierignore b/examples/react/start-basic-rsbuild/.prettierignore new file mode 100644 index 0000000000..2be5eaa6ec --- /dev/null +++ b/examples/react/start-basic-rsbuild/.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-basic-rsbuild/.vscode/settings.json b/examples/react/start-basic-rsbuild/.vscode/settings.json new file mode 100644 index 0000000000..00b5278e58 --- /dev/null +++ b/examples/react/start-basic-rsbuild/.vscode/settings.json @@ -0,0 +1,11 @@ +{ + "files.watcherExclude": { + "**/routeTree.gen.ts": true + }, + "search.exclude": { + "**/routeTree.gen.ts": true + }, + "files.readonlyInclude": { + "**/routeTree.gen.ts": true + } +} diff --git a/examples/react/start-basic-rsbuild/README.md b/examples/react/start-basic-rsbuild/README.md new file mode 100644 index 0000000000..64117c915b --- /dev/null +++ b/examples/react/start-basic-rsbuild/README.md @@ -0,0 +1,36 @@ +# TanStack Start - Basic Rsbuild Example + +This is the basic TanStack Start Rsbuild example, demonstrating the fundamentals of building applications with TanStack Router and TanStack Start. + +- [TanStack Router Docs](https://tanstack.com/router) + +It's deployed automagically with Netlify! + +- [Netlify](https://netlify.com/) + +## Start a new project based on this example + +To start a new project based on this example, run: + +```sh +npx gitpick TanStack/router/tree/main/examples/react/start-basic-rsbuild start-basic-rsbuild +``` + +## Getting Started + +From your terminal: + +```sh +pnpm install +pnpm dev +``` + +This starts your app in development mode, rebuilding assets on file changes. + +## Build + +To build the app for production: + +```sh +pnpm build +``` diff --git a/examples/react/start-basic-rsbuild/package.json b/examples/react/start-basic-rsbuild/package.json new file mode 100644 index 0000000000..bea4ba26ef --- /dev/null +++ b/examples/react/start-basic-rsbuild/package.json @@ -0,0 +1,33 @@ +{ + "name": "tanstack-start-example-basic-rsbuild", + "private": true, + "sideEffects": false, + "type": "module", + "scripts": { + "dev": "rsbuild dev --port 3000", + "build": "rsbuild build && tsc --noEmit", + "preview": "rsbuild preview", + "start": "srvx --prod -s ../client dist/server/index.js" + }, + "dependencies": { + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", + "react": "^19.2.3", + "react-dom": "^19.2.3", + "tailwind-merge": "^3.6.0", + "zod": "^4.4.3" + }, + "devDependencies": { + "@rsbuild/core": "^2.3.1", + "@rsbuild/plugin-react": "^2.0.0", + "@rsbuild/plugin-tailwindcss": "^2.0.3", + "@types/node": "25.0.9", + "@types/react": "^19.2.8", + "@types/react-dom": "^19.2.3", + "srvx": "^1.0.0", + "tailwindcss": "^4.2.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2" + } +} diff --git a/examples/react/start-basic-rsbuild/public/android-chrome-192x192.png b/examples/react/start-basic-rsbuild/public/android-chrome-192x192.png new file mode 100644 index 0000000000..09c8324f8c Binary files /dev/null and b/examples/react/start-basic-rsbuild/public/android-chrome-192x192.png differ diff --git a/examples/react/start-basic-rsbuild/public/android-chrome-512x512.png b/examples/react/start-basic-rsbuild/public/android-chrome-512x512.png new file mode 100644 index 0000000000..11d626ea3d Binary files /dev/null and b/examples/react/start-basic-rsbuild/public/android-chrome-512x512.png differ diff --git a/examples/react/start-basic-rsbuild/public/apple-touch-icon.png b/examples/react/start-basic-rsbuild/public/apple-touch-icon.png new file mode 100644 index 0000000000..5a9423cc02 Binary files /dev/null and b/examples/react/start-basic-rsbuild/public/apple-touch-icon.png differ diff --git a/examples/react/start-basic-rsbuild/public/favicon-16x16.png b/examples/react/start-basic-rsbuild/public/favicon-16x16.png new file mode 100644 index 0000000000..e3389b0044 Binary files /dev/null and b/examples/react/start-basic-rsbuild/public/favicon-16x16.png differ diff --git a/examples/react/start-basic-rsbuild/public/favicon-32x32.png b/examples/react/start-basic-rsbuild/public/favicon-32x32.png new file mode 100644 index 0000000000..900c77d444 Binary files /dev/null and b/examples/react/start-basic-rsbuild/public/favicon-32x32.png differ diff --git a/examples/react/start-basic-rsbuild/public/favicon.ico b/examples/react/start-basic-rsbuild/public/favicon.ico new file mode 100644 index 0000000000..1a1751676f Binary files /dev/null and b/examples/react/start-basic-rsbuild/public/favicon.ico differ diff --git a/examples/react/start-basic-rsbuild/public/favicon.png b/examples/react/start-basic-rsbuild/public/favicon.png new file mode 100644 index 0000000000..1e77bc0609 Binary files /dev/null and b/examples/react/start-basic-rsbuild/public/favicon.png differ diff --git a/examples/react/start-basic-rsbuild/public/site.webmanifest b/examples/react/start-basic-rsbuild/public/site.webmanifest new file mode 100644 index 0000000000..fa99de77db --- /dev/null +++ b/examples/react/start-basic-rsbuild/public/site.webmanifest @@ -0,0 +1,19 @@ +{ + "name": "", + "short_name": "", + "icons": [ + { + "src": "/android-chrome-192x192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "/android-chrome-512x512.png", + "sizes": "512x512", + "type": "image/png" + } + ], + "theme_color": "#ffffff", + "background_color": "#ffffff", + "display": "standalone" +} diff --git a/examples/react/start-basic-rsbuild/rsbuild.config.ts b/examples/react/start-basic-rsbuild/rsbuild.config.ts new file mode 100644 index 0000000000..3705696818 --- /dev/null +++ b/examples/react/start-basic-rsbuild/rsbuild.config.ts @@ -0,0 +1,17 @@ +import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' +import { defineConfig } from '@rsbuild/core' +import { pluginReact } from '@rsbuild/plugin-react' +import { pluginTailwindcss } from '@rsbuild/plugin-tailwindcss' + +export default defineConfig({ + server: { + port: 3000, + }, + plugins: [ + pluginTailwindcss(), + pluginReact(), + tanstackStart({ + srcDirectory: 'src', + }), + ], +}) diff --git a/examples/react/start-basic-rsbuild/src/components/DefaultCatchBoundary.tsx b/examples/react/start-basic-rsbuild/src/components/DefaultCatchBoundary.tsx new file mode 100644 index 0000000000..4a22649ed4 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/components/DefaultCatchBoundary.tsx @@ -0,0 +1,51 @@ +import { + ErrorComponent, + Link, + useLocation, + useRouter, +} from '@tanstack/react-router' +import type { ErrorComponentProps } from '@tanstack/react-router' + +export function DefaultCatchBoundary({ error }: ErrorComponentProps) { + const router = useRouter() + const isRoot = useLocation({ + select: (location) => location.pathname === '/', + }) + + console.error('DefaultCatchBoundary Error:', error) + + return ( +
+ +
+ + {isRoot ? ( + + Home + + ) : ( + { + e.preventDefault() + window.history.back() + }} + > + Go Back + + )} +
+
+ ) +} diff --git a/examples/react/start-basic-rsbuild/src/components/NotFound.tsx b/examples/react/start-basic-rsbuild/src/components/NotFound.tsx new file mode 100644 index 0000000000..fd4e75befe --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/components/NotFound.tsx @@ -0,0 +1,25 @@ +import { Link } from '@tanstack/react-router' + +export function NotFound({ children }: { children?: any }) { + return ( +
+
+ {children ||

The page you are looking for does not exist.

} +
+

+ + + Start Over + +

+
+ ) +} diff --git a/examples/react/start-basic-rsbuild/src/components/PostError.tsx b/examples/react/start-basic-rsbuild/src/components/PostError.tsx new file mode 100644 index 0000000000..271f2d1de1 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/components/PostError.tsx @@ -0,0 +1,6 @@ +import { ErrorComponent } from '@tanstack/react-router' +import type { ErrorComponentProps } from '@tanstack/react-router' + +export function PostErrorComponent({ error }: ErrorComponentProps) { + return +} diff --git a/examples/react/start-basic-rsbuild/src/components/UserError.tsx b/examples/react/start-basic-rsbuild/src/components/UserError.tsx new file mode 100644 index 0000000000..af5d0c6f16 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/components/UserError.tsx @@ -0,0 +1,6 @@ +import { ErrorComponent } from '@tanstack/react-router' +import type { ErrorComponentProps } from '@tanstack/react-router' + +export function UserErrorComponent({ error }: ErrorComponentProps) { + return +} diff --git a/examples/react/start-basic-rsbuild/src/env.d.ts b/examples/react/start-basic-rsbuild/src/env.d.ts new file mode 100644 index 0000000000..b0ac762b09 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/env.d.ts @@ -0,0 +1 @@ +/// diff --git a/examples/react/start-basic-rsbuild/src/routeTree.gen.ts b/examples/react/start-basic-rsbuild/src/routeTree.gen.ts new file mode 100644 index 0000000000..57b849492d --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routeTree.gen.ts @@ -0,0 +1,447 @@ +/* eslint-disable */ + +// @ts-nocheck + +// 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 PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as UsersRouteImport } from './routes/users' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' +import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', + getParentRoute: () => rootRouteImport, +} as any) +const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ + id: '/customScript.js', + path: '/customScript.js', + getParentRoute: () => rootRouteImport, +} as any) +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', + getParentRoute: () => rootRouteImport, +} as any) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', + getParentRoute: () => rootRouteImport, +} as any) +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', + getParentRoute: () => rootRouteImport, +} as any) +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, + } as any) +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', + getParentRoute: () => rootRouteImport, +} as any) +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRoute, +} as any) +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const PathlessLayoutNestedLayoutRouteBRoute = + PathlessLayoutNestedLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => ApiUsersRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/customScript.js': typeof CustomScriptDotjsRoute + '/deferred': typeof DeferredRoute + '/posts': typeof PostsRouteWithChildren + '/redirect': typeof RedirectRoute + '/users': typeof UsersRouteWithChildren + '/api/users': typeof ApiUsersRouteWithChildren + '/posts/$postId': typeof PostsPostIdRoute + '/users/$userId': typeof UsersUserIdRoute + '/posts/': typeof PostsIndexRoute + '/users/': typeof UsersIndexRoute + '/route-a': typeof PathlessLayoutNestedLayoutRouteARoute + '/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute + '/api/users/$userId': typeof ApiUsersUserIdRoute + '/posts/$postId/deep': typeof PostsPostIdDeepRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/customScript.js': typeof CustomScriptDotjsRoute + '/deferred': typeof DeferredRoute + '/redirect': typeof RedirectRoute + '/api/users': typeof ApiUsersRouteWithChildren + '/posts/$postId': typeof PostsPostIdRoute + '/users/$userId': typeof UsersUserIdRoute + '/posts': typeof PostsIndexRoute + '/users': typeof UsersIndexRoute + '/route-a': typeof PathlessLayoutNestedLayoutRouteARoute + '/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute + '/api/users/$userId': typeof ApiUsersUserIdRoute + '/posts/$postId/deep': typeof PostsPostIdDeepRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/_pathlessLayout': typeof PathlessLayoutRouteWithChildren + '/customScript.js': typeof CustomScriptDotjsRoute + '/deferred': typeof DeferredRoute + '/posts': typeof PostsRouteWithChildren + '/redirect': typeof RedirectRoute + '/users': typeof UsersRouteWithChildren + '/_pathlessLayout/_nested-layout': typeof PathlessLayoutNestedLayoutRouteWithChildren + '/api/users': typeof ApiUsersRouteWithChildren + '/posts/$postId': typeof PostsPostIdRoute + '/users/$userId': typeof UsersUserIdRoute + '/posts/': typeof PostsIndexRoute + '/users/': typeof UsersIndexRoute + '/_pathlessLayout/_nested-layout/route-a': typeof PathlessLayoutNestedLayoutRouteARoute + '/_pathlessLayout/_nested-layout/route-b': typeof PathlessLayoutNestedLayoutRouteBRoute + '/api/users/$userId': typeof ApiUsersUserIdRoute + '/posts_/$postId/deep': typeof PostsPostIdDeepRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/customScript.js' + | '/deferred' + | '/posts' + | '/redirect' + | '/users' + | '/api/users' + | '/posts/$postId' + | '/users/$userId' + | '/posts/' + | '/users/' + | '/route-a' + | '/route-b' + | '/api/users/$userId' + | '/posts/$postId/deep' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/customScript.js' + | '/deferred' + | '/redirect' + | '/api/users' + | '/posts/$postId' + | '/users/$userId' + | '/posts' + | '/users' + | '/route-a' + | '/route-b' + | '/api/users/$userId' + | '/posts/$postId/deep' + id: + | '__root__' + | '/' + | '/_pathlessLayout' + | '/customScript.js' + | '/deferred' + | '/posts' + | '/redirect' + | '/users' + | '/_pathlessLayout/_nested-layout' + | '/api/users' + | '/posts/$postId' + | '/users/$userId' + | '/posts/' + | '/users/' + | '/_pathlessLayout/_nested-layout/route-a' + | '/_pathlessLayout/_nested-layout/route-b' + | '/api/users/$userId' + | '/posts_/$postId/deep' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + PathlessLayoutRoute: typeof PathlessLayoutRouteWithChildren + CustomScriptDotjsRoute: typeof CustomScriptDotjsRoute + DeferredRoute: typeof DeferredRoute + PostsRoute: typeof PostsRouteWithChildren + RedirectRoute: typeof RedirectRoute + UsersRoute: typeof UsersRouteWithChildren + ApiUsersRoute: typeof ApiUsersRouteWithChildren + PostsPostIdDeepRoute: typeof PostsPostIdDeepRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/customScript.js': { + id: '/customScript.js' + path: '/customScript.js' + fullPath: '/customScript.js' + preLoaderRoute: typeof CustomScriptDotjsRouteImport + parentRoute: typeof rootRouteImport + } + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport + } + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute + } + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport + parentRoute: typeof rootRouteImport + } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute + } + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute + } + '/_pathlessLayout/_nested-layout/route-b': { + id: '/_pathlessLayout/_nested-layout/route-b' + path: '/route-b' + fullPath: '/route-b' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute + } + '/api/users/$userId': { + id: '/api/users/$userId' + path: '/$userId' + fullPath: '/api/users/$userId' + preLoaderRoute: typeof ApiUsersUserIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +interface PathlessLayoutNestedLayoutRouteChildren { + PathlessLayoutNestedLayoutRouteARoute: typeof PathlessLayoutNestedLayoutRouteARoute + PathlessLayoutNestedLayoutRouteBRoute: typeof PathlessLayoutNestedLayoutRouteBRoute +} + +const PathlessLayoutNestedLayoutRouteChildren: PathlessLayoutNestedLayoutRouteChildren = + { + PathlessLayoutNestedLayoutRouteARoute: + PathlessLayoutNestedLayoutRouteARoute, + PathlessLayoutNestedLayoutRouteBRoute: + PathlessLayoutNestedLayoutRouteBRoute, + } + +const PathlessLayoutNestedLayoutRouteWithChildren = + PathlessLayoutNestedLayoutRoute._addFileChildren( + PathlessLayoutNestedLayoutRouteChildren, + ) + +interface PathlessLayoutRouteChildren { + PathlessLayoutNestedLayoutRoute: typeof PathlessLayoutNestedLayoutRouteWithChildren +} + +const PathlessLayoutRouteChildren: PathlessLayoutRouteChildren = { + PathlessLayoutNestedLayoutRoute: PathlessLayoutNestedLayoutRouteWithChildren, +} + +const PathlessLayoutRouteWithChildren = PathlessLayoutRoute._addFileChildren( + PathlessLayoutRouteChildren, +) + +interface PostsRouteChildren { + PostsPostIdRoute: typeof PostsPostIdRoute + PostsIndexRoute: typeof PostsIndexRoute +} + +const PostsRouteChildren: PostsRouteChildren = { + PostsPostIdRoute: PostsPostIdRoute, + PostsIndexRoute: PostsIndexRoute, +} + +const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) + +interface UsersRouteChildren { + UsersUserIdRoute: typeof UsersUserIdRoute + UsersIndexRoute: typeof UsersIndexRoute +} + +const UsersRouteChildren: UsersRouteChildren = { + UsersUserIdRoute: UsersUserIdRoute, + UsersIndexRoute: UsersIndexRoute, +} + +const UsersRouteWithChildren = UsersRoute._addFileChildren(UsersRouteChildren) + +interface ApiUsersRouteChildren { + ApiUsersUserIdRoute: typeof ApiUsersUserIdRoute +} + +const ApiUsersRouteChildren: ApiUsersRouteChildren = { + ApiUsersUserIdRoute: ApiUsersUserIdRoute, +} + +const ApiUsersRouteWithChildren = ApiUsersRoute._addFileChildren( + ApiUsersRouteChildren, +) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + PathlessLayoutRoute: PathlessLayoutRouteWithChildren, + CustomScriptDotjsRoute: CustomScriptDotjsRoute, + DeferredRoute: DeferredRoute, + PostsRoute: PostsRouteWithChildren, + RedirectRoute: RedirectRoute, + UsersRoute: UsersRouteWithChildren, + ApiUsersRoute: ApiUsersRouteWithChildren, + PostsPostIdDeepRoute: PostsPostIdDeepRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +import type { getRouter } from './router.tsx' +import type { createStart } from '@tanstack/react-start' +declare module '@tanstack/react-start' { + interface Register { + ssr: true + router: Awaited> + } +} diff --git a/examples/react/start-basic-rsbuild/src/router.tsx b/examples/react/start-basic-rsbuild/src/router.tsx new file mode 100644 index 0000000000..f380f73be7 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/router.tsx @@ -0,0 +1,15 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' +import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' +import { NotFound } from './components/NotFound' + +export function getRouter() { + const router = createRouter({ + routeTree, + defaultPreload: 'intent', + defaultErrorComponent: DefaultCatchBoundary, + defaultNotFoundComponent: () => , + scrollRestoration: true, + }) + return router +} diff --git a/examples/react/start-basic-rsbuild/src/routes/__root.tsx b/examples/react/start-basic-rsbuild/src/routes/__root.tsx new file mode 100644 index 0000000000..6d4aed1fe0 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/__root.tsx @@ -0,0 +1,130 @@ +import { + HeadContent, + Link, + Scripts, + createRootRoute, +} from '@tanstack/react-router' +import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' +import * as React from 'react' +import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary' +import { NotFound } from '~/components/NotFound' +import appCss from '~/styles/app.css?url' +import { seo } from '~/utils/seo' + +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { + charSet: 'utf-8', + }, + { + name: 'viewport', + content: 'width=device-width, initial-scale=1', + }, + ...seo({ + title: + 'TanStack Start | Type-Safe, Client-First, Full-Stack React Framework', + description: `TanStack Start is a type-safe, client-first, full-stack React framework. `, + }), + ], + links: [ + { rel: 'stylesheet', href: appCss }, + { + rel: 'apple-touch-icon', + sizes: '180x180', + href: '/apple-touch-icon.png', + }, + { + rel: 'icon', + type: 'image/png', + sizes: '32x32', + href: '/favicon-32x32.png', + }, + { + rel: 'icon', + type: 'image/png', + sizes: '16x16', + href: '/favicon-16x16.png', + }, + { rel: 'manifest', href: '/site.webmanifest', color: '#fffff' }, + { rel: 'icon', href: '/favicon.ico' }, + ], + scripts: [ + { + src: '/customScript.js', + type: 'text/javascript', + }, + ], + }), + errorComponent: DefaultCatchBoundary, + notFoundComponent: () => , + shellComponent: RootDocument, +}) + +function RootDocument({ children }: { children: React.ReactNode }) { + return ( + + + + + +
+ + Home + {' '} + + Posts + {' '} + + Users + {' '} + + Pathless Layout + {' '} + + Deferred + {' '} + + This Route Does Not Exist + +
+
+ {children} + + + + + ) +} diff --git a/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout.tsx b/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout.tsx new file mode 100644 index 0000000000..c3b12442b8 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout.tsx @@ -0,0 +1,16 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/_pathlessLayout')({ + component: LayoutComponent, +}) + +function LayoutComponent() { + return ( +
+
I'm a layout
+
+ +
+
+ ) +} diff --git a/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout.tsx b/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout.tsx new file mode 100644 index 0000000000..9a48b73a46 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout.tsx @@ -0,0 +1,34 @@ +import { Link, Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/_pathlessLayout/_nested-layout')({ + component: LayoutComponent, +}) + +function LayoutComponent() { + return ( +
+
I'm a nested layout
+
+ + Go to route A + + + Go to route B + +
+
+ +
+
+ ) +} diff --git a/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout/route-a.tsx b/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout/route-a.tsx new file mode 100644 index 0000000000..426a8fe486 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout/route-a.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/_pathlessLayout/_nested-layout/route-a')( + { + component: LayoutAComponent, + }, +) + +function LayoutAComponent() { + return
I'm A!
+} diff --git a/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout/route-b.tsx b/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout/route-b.tsx new file mode 100644 index 0000000000..20facf2daf --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/_pathlessLayout/_nested-layout/route-b.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/_pathlessLayout/_nested-layout/route-b')( + { + component: LayoutBComponent, + }, +) + +function LayoutBComponent() { + return
I'm B!
+} diff --git a/examples/react/start-basic-rsbuild/src/routes/api/users.$userId.ts b/examples/react/start-basic-rsbuild/src/routes/api/users.$userId.ts new file mode 100644 index 0000000000..ee34d7a189 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/api/users.$userId.ts @@ -0,0 +1,31 @@ +import { createFileRoute } from '@tanstack/react-router' +import type { User } from '~/utils/users' + +export const Route = createFileRoute('/api/users/$userId')({ + server: { + handlers: { + GET: async ({ params, request }) => { + console.info(`Fetching users by id=${params.userId}... @`, request.url) + try { + const res = await fetch( + 'https://jsonplaceholder.typicode.com/users/' + params.userId, + ) + if (!res.ok) { + throw new Error('Failed to fetch user') + } + + const user = (await res.json()) as User + + return Response.json({ + id: user.id, + name: user.name, + email: user.email, + }) + } catch (e) { + console.error(e) + return Response.json({ error: 'User not found' }, { status: 404 }) + } + }, + }, + }, +}) diff --git a/examples/react/start-basic-rsbuild/src/routes/api/users.ts b/examples/react/start-basic-rsbuild/src/routes/api/users.ts new file mode 100644 index 0000000000..4cecd01852 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/api/users.ts @@ -0,0 +1,63 @@ +import { createFileRoute } from '@tanstack/react-router' +import { getRequestHeaders } from '@tanstack/react-start/server' +import { createMiddleware } from '@tanstack/react-start' +import type { User } from '~/utils/users' + +const userLoggerMiddleware = createMiddleware().server(async ({ next }) => { + console.info('In: /users') + console.info('Request Headers:', getRequestHeaders()) + const result = await next() + result.response.headers.set('x-users', 'true') + console.info('Out: /users') + return result +}) + +const testParentMiddleware = createMiddleware().server(async ({ next }) => { + console.info('In: testParentMiddleware') + const result = await next() + result.response.headers.set('x-test-parent', 'true') + console.info('Out: testParentMiddleware') + return result +}) + +const testMiddleware = createMiddleware() + .middleware([testParentMiddleware]) + .server(async ({ next }) => { + console.info('In: testMiddleware') + const result = await next() + result.response.headers.set('x-test', 'true') + + // if (Math.random() > 0.5) { + // throw new Response(null, { + // status: 302, + // headers: { Location: 'https://www.google.com' }, + // }) + // } + + console.info('Out: testMiddleware') + return result + }) + +export const Route = createFileRoute('/api/users')({ + server: { + middleware: [testMiddleware, userLoggerMiddleware], + handlers: { + GET: async ({ request }) => { + console.info('GET /api/users @', request.url) + console.info('Fetching users... @', request.url) + const res = await fetch('https://jsonplaceholder.typicode.com/users') + if (!res.ok) { + throw new Error('Failed to fetch users') + } + + const data = (await res.json()) as Array + + const list = data.slice(0, 10) + + return Response.json( + list.map((u) => ({ id: u.id, name: u.name, email: u.email })), + ) + }, + }, + }, +}) diff --git a/examples/react/start-basic-rsbuild/src/routes/customScript[.]js.ts b/examples/react/start-basic-rsbuild/src/routes/customScript[.]js.ts new file mode 100644 index 0000000000..811471ac15 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/customScript[.]js.ts @@ -0,0 +1,15 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/customScript.js')({ + server: { + handlers: { + GET: () => { + return new Response('console.log("Hello from customScript.js!")', { + headers: { + 'Content-Type': 'application/javascript', + }, + }) + }, + }, + }, +}) diff --git a/examples/react/start-basic-rsbuild/src/routes/deferred.tsx b/examples/react/start-basic-rsbuild/src/routes/deferred.tsx new file mode 100644 index 0000000000..f3e09d1d4e --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/deferred.tsx @@ -0,0 +1,62 @@ +import { Await, createFileRoute } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' +import { Suspense, useState } from 'react' + +const personServerFn = createServerFn({ method: 'GET' }) + .validator((d: string) => d) + .handler(({ data: name }) => { + return { name, randomNumber: Math.floor(Math.random() * 100) } + }) + +const slowServerFn = createServerFn({ method: 'GET' }) + .validator((d: string) => d) + .handler(async ({ data: name }) => { + await new Promise((r) => setTimeout(r, 1000)) + return { name, randomNumber: Math.floor(Math.random() * 100) } + }) + +export const Route = createFileRoute('/deferred')({ + loader: async () => { + return { + deferredStuff: new Promise((r) => + setTimeout(() => r('Hello deferred!'), 2000), + ), + deferredPerson: slowServerFn({ data: 'Tanner Linsley' }), + person: await personServerFn({ data: 'John Doe' }), + } + }, + component: Deferred, +}) + +function Deferred() { + const [count, setCount] = useState(0) + const { deferredStuff, deferredPerson, person } = Route.useLoaderData() + + return ( +
+
+ {person.name} - {person.randomNumber} +
+ Loading person...
}> + ( +
+ {data.name} - {data.randomNumber} +
+ )} + /> + + Loading stuff...
}> +

{data}

} + /> + +
Count: {count}
+
+ +
+

+ ) +} diff --git a/examples/react/start-basic-rsbuild/src/routes/index.tsx b/examples/react/start-basic-rsbuild/src/routes/index.tsx new file mode 100644 index 0000000000..09a907cb18 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/index.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: Home, +}) + +function Home() { + return ( +
+

Welcome Home!!!

+
+ ) +} diff --git a/examples/react/start-basic-rsbuild/src/routes/posts.$postId.tsx b/examples/react/start-basic-rsbuild/src/routes/posts.$postId.tsx new file mode 100644 index 0000000000..65905bf8c4 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/posts.$postId.tsx @@ -0,0 +1,34 @@ +import { Link, createFileRoute } from '@tanstack/react-router' +import { fetchPost } from '../utils/posts' +import { NotFound } from '~/components/NotFound' +import { PostErrorComponent } from '~/components/PostError' + +export const Route = createFileRoute('/posts/$postId')({ + loader: ({ params: { postId } }) => fetchPost({ data: postId }), + errorComponent: PostErrorComponent, + component: PostComponent, + notFoundComponent: () => { + return Post not found + }, +}) + +function PostComponent() { + const post = Route.useLoaderData() + + return ( +
+

{post.title}

+
{post.body}
+ + Deep View + +
+ ) +} diff --git a/examples/react/start-basic-rsbuild/src/routes/posts.index.tsx b/examples/react/start-basic-rsbuild/src/routes/posts.index.tsx new file mode 100644 index 0000000000..5b5f08f95b --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/posts.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/posts/')({ + component: PostsIndexComponent, +}) + +function PostsIndexComponent() { + return
Select a post.
+} diff --git a/examples/react/start-basic-rsbuild/src/routes/posts.tsx b/examples/react/start-basic-rsbuild/src/routes/posts.tsx new file mode 100644 index 0000000000..9b9162be7c --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/posts.tsx @@ -0,0 +1,38 @@ +import { Link, Outlet, createFileRoute } from '@tanstack/react-router' +import { fetchPosts } from '../utils/posts' + +export const Route = createFileRoute('/posts')({ + loader: async () => fetchPosts(), + component: PostsComponent, +}) + +function PostsComponent() { + const posts = Route.useLoaderData() + + return ( +
+
    + {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }].map( + (post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + }, + )} +
+
+ +
+ ) +} diff --git a/examples/react/start-basic-rsbuild/src/routes/posts_.$postId.deep.tsx b/examples/react/start-basic-rsbuild/src/routes/posts_.$postId.deep.tsx new file mode 100644 index 0000000000..29e6c39b5a --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/posts_.$postId.deep.tsx @@ -0,0 +1,29 @@ +import { Link, createFileRoute } from '@tanstack/react-router' +import { fetchPost } from '../utils/posts' +import { PostErrorComponent } from '~/components/PostError' + +export const Route = createFileRoute('/posts_/$postId/deep')({ + loader: async ({ params: { postId } }) => + fetchPost({ + data: postId, + }), + errorComponent: PostErrorComponent, + component: PostDeepComponent, +}) + +function PostDeepComponent() { + const post = Route.useLoaderData() + + return ( +
+ + ← All Posts + +

{post.title}

+
{post.body}
+
+ ) +} diff --git a/examples/react/start-basic-rsbuild/src/routes/redirect.tsx b/examples/react/start-basic-rsbuild/src/routes/redirect.tsx new file mode 100644 index 0000000000..ea34b6e420 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/redirect.tsx @@ -0,0 +1,9 @@ +import { createFileRoute, redirect } from '@tanstack/react-router' + +export const Route = createFileRoute('/redirect')({ + beforeLoad: () => { + throw redirect({ + to: '/posts', + }) + }, +}) diff --git a/examples/react/start-basic-rsbuild/src/routes/users.$userId.tsx b/examples/react/start-basic-rsbuild/src/routes/users.$userId.tsx new file mode 100644 index 0000000000..4e4d470075 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/users.$userId.tsx @@ -0,0 +1,45 @@ +import { createFileRoute } from '@tanstack/react-router' +import { NotFound } from '../components/NotFound' +import { UserErrorComponent } from '../components/UserError' +import type { User } from '../utils/users' + +export const Route = createFileRoute('/users/$userId')({ + loader: async ({ params: { userId } }) => { + try { + const res = await fetch('/api/users/' + userId) + if (!res.ok) { + throw new Error('Unexpected status code') + } + + const data = await res.json() + + return data as User + } catch { + throw new Error('Failed to fetch user') + } + }, + errorComponent: UserErrorComponent, + component: UserComponent, + notFoundComponent: () => { + return User not found + }, +}) + +function UserComponent() { + const user = Route.useLoaderData() + + return ( +
+

{user.name}

+
{user.email}
+ +
+ ) +} diff --git a/examples/react/start-basic-rsbuild/src/routes/users.index.tsx b/examples/react/start-basic-rsbuild/src/routes/users.index.tsx new file mode 100644 index 0000000000..27d136987e --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/users.index.tsx @@ -0,0 +1,19 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/users/')({ + component: UsersIndexComponent, +}) + +function UsersIndexComponent() { + return ( +
+ Select a user or{' '} + + view as JSON + +
+ ) +} diff --git a/examples/react/start-basic-rsbuild/src/routes/users.tsx b/examples/react/start-basic-rsbuild/src/routes/users.tsx new file mode 100644 index 0000000000..64ca3ce156 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/routes/users.tsx @@ -0,0 +1,49 @@ +import { Link, Outlet, createFileRoute } from '@tanstack/react-router' +import type { User } from '../utils/users' + +export const Route = createFileRoute('/users')({ + loader: async () => { + const res = await fetch('/api/users') + + if (!res.ok) { + throw new Error('Unexpected status code') + } + + const data = await res.json() + + return data as Array + }, + component: UsersComponent, +}) + +function UsersComponent() { + const users = Route.useLoaderData() + + return ( +
+
    + {[ + ...users, + { id: 'i-do-not-exist', name: 'Non-existent User', email: '' }, + ].map((user) => { + return ( +
  • + +
    {user.name}
    + +
  • + ) + })} +
+
+ +
+ ) +} diff --git a/examples/react/start-basic-rsbuild/src/styles/app.css b/examples/react/start-basic-rsbuild/src/styles/app.css new file mode 100644 index 0000000000..37c1f5a6e2 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/styles/app.css @@ -0,0 +1,30 @@ +@import 'tailwindcss' source('../'); + +@layer base { + *, + ::after, + ::before, + ::backdrop, + ::file-selector-button { + border-color: var(--color-gray-200, currentcolor); + } +} + +@layer base { + html { + color-scheme: light dark; + } + + * { + @apply border-gray-200 dark:border-gray-800; + } + + html, + body { + @apply text-gray-900 bg-gray-50 dark:bg-gray-950 dark:text-gray-200; + } + + .using-mouse * { + outline: none !important; + } +} diff --git a/examples/react/start-basic-rsbuild/src/utils/loggingMiddleware.tsx b/examples/react/start-basic-rsbuild/src/utils/loggingMiddleware.tsx new file mode 100644 index 0000000000..3ea9a06439 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/utils/loggingMiddleware.tsx @@ -0,0 +1,41 @@ +import { createMiddleware } from '@tanstack/react-start' + +const preLogMiddleware = createMiddleware({ type: 'function' }) + .client(async (ctx) => { + const clientTime = new Date() + + return ctx.next({ + context: { + clientTime, + }, + sendContext: { + clientTime, + }, + }) + }) + .server(async (ctx) => { + const serverTime = new Date() + + return ctx.next({ + sendContext: { + serverTime, + durationToServer: + serverTime.getTime() - ctx.context.clientTime.getTime(), + }, + }) + }) + +export const logMiddleware = createMiddleware({ type: 'function' }) + .middleware([preLogMiddleware]) + .client(async (ctx) => { + const res = await ctx.next() + + const now = new Date() + console.log('Client Req/Res:', { + duration: now.getTime() - res.context.clientTime.getTime(), + durationToServer: res.context.durationToServer, + durationFromServer: now.getTime() - res.context.serverTime.getTime(), + }) + + return res + }) diff --git a/examples/react/start-basic-rsbuild/src/utils/posts.tsx b/examples/react/start-basic-rsbuild/src/utils/posts.tsx new file mode 100644 index 0000000000..ea7dd0a721 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/utils/posts.tsx @@ -0,0 +1,40 @@ +import { notFound } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' + +export type PostType = { + id: number + title: string + body: string +} + +export const fetchPost = createServerFn({ method: 'POST' }) + .validator((d: string) => d) + .handler(async ({ data }) => { + console.info(`Fetching post with id ${data}...`) + const res = await fetch( + `https://jsonplaceholder.typicode.com/posts/${data}`, + ) + if (!res.ok) { + if (res.status === 404) { + throw notFound() + } + + throw new Error('Failed to fetch post') + } + + const post = await res.json() + + return post as PostType + }) + +export const fetchPosts = createServerFn().handler(async () => { + console.info('Fetching posts...') + const res = await fetch('https://jsonplaceholder.typicode.com/posts') + if (!res.ok) { + throw new Error('Failed to fetch posts') + } + + const posts = await res.json() + + return (posts as Array).slice(0, 10) +}) diff --git a/examples/react/start-basic-rsbuild/src/utils/seo.ts b/examples/react/start-basic-rsbuild/src/utils/seo.ts new file mode 100644 index 0000000000..d18ad84b74 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/utils/seo.ts @@ -0,0 +1,33 @@ +export const seo = ({ + title, + description, + keywords, + image, +}: { + title: string + description?: string + image?: string + keywords?: string +}) => { + const tags = [ + { title }, + { name: 'description', content: description }, + { name: 'keywords', content: keywords }, + { name: 'twitter:title', content: title }, + { name: 'twitter:description', content: description }, + { name: 'twitter:creator', content: '@tannerlinsley' }, + { name: 'twitter:site', content: '@tannerlinsley' }, + { name: 'og:type', content: 'website' }, + { name: 'og:title', content: title }, + { name: 'og:description', content: description }, + ...(image + ? [ + { name: 'twitter:image', content: image }, + { name: 'twitter:card', content: 'summary_large_image' }, + { name: 'og:image', content: image }, + ] + : []), + ] + + return tags +} diff --git a/examples/react/start-basic-rsbuild/src/utils/users.tsx b/examples/react/start-basic-rsbuild/src/utils/users.tsx new file mode 100644 index 0000000000..7ba645b383 --- /dev/null +++ b/examples/react/start-basic-rsbuild/src/utils/users.tsx @@ -0,0 +1,5 @@ +export type User = { + id: number + name: string + email: string +} diff --git a/examples/react/start-basic-rsbuild/tsconfig.json b/examples/react/start-basic-rsbuild/tsconfig.json new file mode 100644 index 0000000000..cc479423a1 --- /dev/null +++ b/examples/react/start-basic-rsbuild/tsconfig.json @@ -0,0 +1,21 @@ +{ + "include": ["**/*.ts", "**/*.tsx", "**/*.d.ts"], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["DOM", "DOM.Iterable", "ES2024"], + "isolatedModules": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "target": "ES2024", + "allowJs": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "~/*": ["./src/*"] + }, + "noEmit": true + } +} diff --git a/examples/react/start-basic-static/package.json b/examples/react/start-basic-static/package.json index c167f5ce79..58d573ca36 100644 --- a/examples/react/start-basic-static/package.json +++ b/examples/react/start-basic-static/package.json @@ -10,10 +10,10 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.28", - "@tanstack/start-static-server-functions": "^1.167.19", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", + "@tanstack/start-static-server-functions": "^1.167.44", "@vitejs/plugin-react": "^6.0.1", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -26,7 +26,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/start-basic-static/src/routeTree.gen.ts b/examples/react/start-basic-static/src/routeTree.gen.ts index ddc8fc320a..d4a8e72343 100644 --- a/examples/react/start-basic-static/src/routeTree.gen.ts +++ b/examples/react/start-basic-static/src/routeTree.gen.ts @@ -9,34 +9,28 @@ // 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 UsersRouteImport } from './routes/users' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as UsersRouteImport } from './routes/users' import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const DeferredRoute = DeferredRouteImport.update({ @@ -44,57 +38,63 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, -} as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', + getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = PathlessLayoutNestedLayoutRouteImport.update({ id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRoute, } as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) const PathlessLayoutNestedLayoutRouteARoute = PathlessLayoutNestedLayoutRouteARouteImport.update({ id: '/route-a', path: '/route-a', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteBRoute = + PathlessLayoutNestedLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -196,32 +196,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout': { @@ -231,40 +210,33 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport + parentRoute: typeof rootRouteImport } '/_pathlessLayout/_nested-layout': { id: '/_pathlessLayout/_nested-layout' @@ -273,12 +245,40 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport parentRoute: typeof PathlessLayoutRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute + } + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -287,12 +287,12 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/examples/react/start-basic/package.json b/examples/react/start-basic/package.json index 9fd4e517a6..46df8e4650 100644 --- a/examples/react/start-basic/package.json +++ b/examples/react/start-basic/package.json @@ -10,9 +10,9 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.28", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0", "tailwind-merge": "^3.6.0", @@ -24,9 +24,10 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "nitro": "^3.0.260311-beta", + "nitro": "^3.0.260903-beta", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/start-basic/src/routeTree.gen.ts b/examples/react/start-basic/src/routeTree.gen.ts index 0bd698a666..57b849492d 100644 --- a/examples/react/start-basic/src/routeTree.gen.ts +++ b/examples/react/start-basic/src/routeTree.gen.ts @@ -9,42 +9,31 @@ // 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 UsersRouteImport } from './routes/users' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as UsersRouteImport } from './routes/users' import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ @@ -52,38 +41,24 @@ const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ path: '/customScript.js', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', + getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = @@ -91,28 +66,53 @@ const PathlessLayoutNestedLayoutRoute = id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) -const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', - getParentRoute: () => ApiUsersRoute, + getParentRoute: () => UsersRoute, } as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) const PathlessLayoutNestedLayoutRouteARoute = PathlessLayoutNestedLayoutRouteARouteImport.update({ id: '/route-a', path: '/route-a', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteBRoute = + PathlessLayoutNestedLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => ApiUsersRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -234,39 +234,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/customScript.js': { - id: '/customScript.js' - path: '/customScript.js' - fullPath: '/customScript.js' - preLoaderRoute: typeof CustomScriptDotjsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout': { @@ -276,46 +248,39 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/customScript.js': { + id: '/customScript.js' + path: '/customScript.js' + fullPath: '/customScript.js' + preLoaderRoute: typeof CustomScriptDotjsRouteImport parentRoute: typeof rootRouteImport } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout/_nested-layout': { @@ -325,19 +290,47 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport parentRoute: typeof PathlessLayoutRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/api/users/$userId': { - id: '/api/users/$userId' + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute + } + '/users/$userId': { + id: '/users/$userId' path: '/$userId' - fullPath: '/api/users/$userId' - preLoaderRoute: typeof ApiUsersUserIdRouteImport - parentRoute: typeof ApiUsersRoute + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -346,12 +339,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/api/users/$userId': { + id: '/api/users/$userId' + path: '/$userId' + fullPath: '/api/users/$userId' + preLoaderRoute: typeof ApiUsersUserIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/examples/react/start-bun/package.json b/examples/react/start-bun/package.json index c0571fea19..24f7113912 100644 --- a/examples/react/start-bun/package.json +++ b/examples/react/start-bun/package.json @@ -15,11 +15,11 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/react-devtools": "^0.7.0", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-router-ssr-query": "^1.167.1", - "@tanstack/react-start": "^1.168.28", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router-ssr-query": "^1.167.3", + "@tanstack/react-start": "^1.169.6", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.1.1", "react-dom": "^19.1.1", "tailwindcss": "^4.2.2" @@ -35,9 +35,10 @@ "@vitejs/plugin-react": "^6.0.1", "jsdom": "^27.0.0", "prettier": "^3.6.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", - "vitest": "^4.1.4", + "vitest": "^5.0.4", "web-vitals": "^5.1.0" } } diff --git a/examples/react/start-bun/src/routeTree.gen.ts b/examples/react/start-bun/src/routeTree.gen.ts index 18fbc9b60e..77415f9088 100644 --- a/examples/react/start-bun/src/routeTree.gen.ts +++ b/examples/react/start-bun/src/routeTree.gen.ts @@ -11,8 +11,8 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' import { Route as ApiDemoNamesRouteImport } from './routes/api.demo-names' -import { Route as DemoStartServerFuncsRouteImport } from './routes/demo.start.server-funcs' import { Route as DemoStartApiRequestRouteImport } from './routes/demo.start.api-request' +import { Route as DemoStartServerFuncsRouteImport } from './routes/demo.start.server-funcs' const IndexRoute = IndexRouteImport.update({ id: '/', @@ -24,16 +24,16 @@ const ApiDemoNamesRoute = ApiDemoNamesRouteImport.update({ path: '/api/demo-names', getParentRoute: () => rootRouteImport, } as any) -const DemoStartServerFuncsRoute = DemoStartServerFuncsRouteImport.update({ - id: '/demo/start/server-funcs', - path: '/demo/start/server-funcs', - getParentRoute: () => rootRouteImport, -} as any) const DemoStartApiRequestRoute = DemoStartApiRequestRouteImport.update({ id: '/demo/start/api-request', path: '/demo/start/api-request', getParentRoute: () => rootRouteImport, } as any) +const DemoStartServerFuncsRoute = DemoStartServerFuncsRouteImport.update({ + id: '/demo/start/server-funcs', + path: '/demo/start/server-funcs', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -98,13 +98,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiDemoNamesRouteImport parentRoute: typeof rootRouteImport } - '/demo/start/server-funcs': { - id: '/demo/start/server-funcs' - path: '/demo/start/server-funcs' - fullPath: '/demo/start/server-funcs' - preLoaderRoute: typeof DemoStartServerFuncsRouteImport - parentRoute: typeof rootRouteImport - } '/demo/start/api-request': { id: '/demo/start/api-request' path: '/demo/start/api-request' @@ -112,6 +105,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof DemoStartApiRequestRouteImport parentRoute: typeof rootRouteImport } + '/demo/start/server-funcs': { + id: '/demo/start/server-funcs' + path: '/demo/start/server-funcs' + fullPath: '/demo/start/server-funcs' + preLoaderRoute: typeof DemoStartServerFuncsRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/start-clerk-basic/package.json b/examples/react/start-clerk-basic/package.json index 7aeffb6a9b..022300e159 100644 --- a/examples/react/start-clerk-basic/package.json +++ b/examples/react/start-clerk-basic/package.json @@ -11,14 +11,14 @@ }, "dependencies": { "@clerk/tanstack-react-start": "^0.27.14", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.28", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "@vitejs/plugin-react": "^6.0.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "srvx": "^0.11.9", + "srvx": "^1.0.0", "tailwind-merge": "^3.6.0" }, "devDependencies": { @@ -27,7 +27,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/start-clerk-basic/src/routeTree.gen.ts b/examples/react/start-clerk-basic/src/routeTree.gen.ts index 04f57442e2..87269f2faf 100644 --- a/examples/react/start-clerk-basic/src/routeTree.gen.ts +++ b/examples/react/start-clerk-basic/src/routeTree.gen.ts @@ -9,22 +9,22 @@ // 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 AuthedRouteImport } from './routes/_authed' import { Route as IndexRouteImport } from './routes/index' +import { Route as AuthedRouteImport } from './routes/_authed' import { Route as AuthedPostsRouteImport } from './routes/_authed/posts' import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' -import { Route as AuthedProfileSplatRouteImport } from './routes/_authed/profile.$' import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' +import { Route as AuthedProfileSplatRouteImport } from './routes/_authed/profile.$' -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', + getParentRoute: () => rootRouteImport, +} as any) const AuthedPostsRoute = AuthedPostsRouteImport.update({ id: '/posts', path: '/posts', @@ -35,16 +35,16 @@ const AuthedPostsIndexRoute = AuthedPostsIndexRouteImport.update({ path: '/', getParentRoute: () => AuthedPostsRoute, } as any) -const AuthedProfileSplatRoute = AuthedProfileSplatRouteImport.update({ - id: '/profile/$', - path: '/profile/$', - getParentRoute: () => AuthedRoute, -} as any) const AuthedPostsPostIdRoute = AuthedPostsPostIdRouteImport.update({ id: '/$postId', path: '/$postId', getParentRoute: () => AuthedPostsRoute, } as any) +const AuthedProfileSplatRoute = AuthedProfileSplatRouteImport.update({ + id: '/profile/$', + path: '/profile/$', + getParentRoute: () => AuthedRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -90,13 +90,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/_authed': { - id: '/_authed' - path: '' - fullPath: '/' - preLoaderRoute: typeof AuthedRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -104,6 +97,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/_authed': { + id: '/_authed' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthedRouteImport + parentRoute: typeof rootRouteImport + } '/_authed/posts': { id: '/_authed/posts' path: '/posts' @@ -118,13 +118,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthedPostsIndexRouteImport parentRoute: typeof AuthedPostsRoute } - '/_authed/profile/$': { - id: '/_authed/profile/$' - path: '/profile/$' - fullPath: '/profile/$' - preLoaderRoute: typeof AuthedProfileSplatRouteImport - parentRoute: typeof AuthedRoute - } '/_authed/posts/$postId': { id: '/_authed/posts/$postId' path: '/$postId' @@ -132,6 +125,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthedPostsPostIdRouteImport parentRoute: typeof AuthedPostsRoute } + '/_authed/profile/$': { + id: '/_authed/profile/$' + path: '/profile/$' + fullPath: '/profile/$' + preLoaderRoute: typeof AuthedProfileSplatRouteImport + parentRoute: typeof AuthedRoute + } } } diff --git a/examples/react/start-clerk-basic/src/routes/_authed.tsx b/examples/react/start-clerk-basic/src/routes/_authed.tsx index 1a97917c12..04f8196894 100644 --- a/examples/react/start-clerk-basic/src/routes/_authed.tsx +++ b/examples/react/start-clerk-basic/src/routes/_authed.tsx @@ -8,7 +8,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error.message === 'Not authenticated') { + if (error instanceof Error && error.message === 'Not authenticated') { return (
diff --git a/examples/react/start-convex-trellaux/package.json b/examples/react/start-convex-trellaux/package.json index 356a7cab2d..3452f910d0 100644 --- a/examples/react/start-convex-trellaux/package.json +++ b/examples/react/start-convex-trellaux/package.json @@ -13,12 +13,12 @@ }, "dependencies": { "@convex-dev/react-query": "0.0.0-alpha.8", - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-router-ssr-query": "^1.167.1", - "@tanstack/react-start": "^1.168.28", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router-ssr-query": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "concurrently": "^8.2.2", "convex": "^1.19.0", "ky": "^1.7.4", @@ -37,7 +37,8 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/start-counter/package.json b/examples/react/start-counter/package.json index 03a572f79c..8f4673143e 100644 --- a/examples/react/start-counter/package.json +++ b/examples/react/start-counter/package.json @@ -10,9 +10,9 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.28", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0" }, @@ -21,7 +21,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/start-i18n-paraglide/package.json b/examples/react/start-i18n-paraglide/package.json index b4a62068a3..074f714d5c 100644 --- a/examples/react/start-i18n-paraglide/package.json +++ b/examples/react/start-i18n-paraglide/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tanstack/react-devtools": "^0.7.0", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.28", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.1.1", "react-dom": "^19.1.1" }, @@ -21,10 +21,22 @@ "@types/react": "^19.1.13", "@types/react-dom": "^19.1.9", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "@tailwindcss/vite": "^4.2.2", "tailwindcss": "^4.2.2", "@inlang/paraglide-js": "^2.4.0" + }, + "nx": { + "targets": { + "build": { + "outputs": [ + "...", + "{projectRoot}/src/paraglide", + "{projectRoot}/project.inlang/cache" + ] + } + } } } diff --git a/examples/react/start-i18n-paraglide/src/routeTree.gen.ts b/examples/react/start-i18n-paraglide/src/routeTree.gen.ts index 421daf2790..d89758e684 100644 --- a/examples/react/start-i18n-paraglide/src/routeTree.gen.ts +++ b/examples/react/start-i18n-paraglide/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/start-large/package.json b/examples/react/start-large/package.json index f4822d3eba..f9f86b81d1 100644 --- a/examples/react/start-large/package.json +++ b/examples/react/start-large/package.json @@ -12,10 +12,10 @@ "test:types": "tsc --extendedDiagnostics" }, "dependencies": { - "@tanstack/react-query": "^5.90.0", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.28", + "@tanstack/react-query": "^5.102.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -29,7 +29,8 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" }, "keywords": [], diff --git a/examples/react/start-large/src/routeTree.gen.ts b/examples/react/start-large/src/routeTree.gen.ts index 03cc2b9080..4f1551f71d 100644 --- a/examples/react/start-large/src/routeTree.gen.ts +++ b/examples/react/start-large/src/routeTree.gen.ts @@ -9,23 +9,18 @@ // 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 RelativeRouteImport } from './routes/relative' -import { Route as LinkPropsRouteImport } from './routes/linkProps' -import { Route as AbsoluteRouteImport } from './routes/absolute' -import { Route as SearchRouteRouteImport } from './routes/search/route' -import { Route as ParamsRouteRouteImport } from './routes/params/route' import { Route as IndexRouteImport } from './routes/index' -import { Route as SearchSearchPlaceholderRouteImport } from './routes/search/searchPlaceholder' +import { Route as AbsoluteRouteImport } from './routes/absolute' +import { Route as LinkPropsRouteImport } from './routes/linkProps' +import { Route as ParamsRouteRouteImport } from './routes/params/route' +import { Route as RelativeRouteImport } from './routes/relative' +import { Route as SearchRouteRouteImport } from './routes/search/route' import { Route as ParamsParamsPlaceholderRouteImport } from './routes/params/$paramsPlaceholder' +import { Route as SearchSearchPlaceholderRouteImport } from './routes/search/searchPlaceholder' -const RelativeRoute = RelativeRouteImport.update({ - id: '/relative', - path: '/relative', - getParentRoute: () => rootRouteImport, -} as any) -const LinkPropsRoute = LinkPropsRouteImport.update({ - id: '/linkProps', - path: '/linkProps', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AbsoluteRoute = AbsoluteRouteImport.update({ @@ -33,9 +28,9 @@ const AbsoluteRoute = AbsoluteRouteImport.update({ path: '/absolute', getParentRoute: () => rootRouteImport, } as any) -const SearchRouteRoute = SearchRouteRouteImport.update({ - id: '/search', - path: '/search', +const LinkPropsRoute = LinkPropsRouteImport.update({ + id: '/linkProps', + path: '/linkProps', getParentRoute: () => rootRouteImport, } as any) const ParamsRouteRoute = ParamsRouteRouteImport.update({ @@ -43,21 +38,26 @@ const ParamsRouteRoute = ParamsRouteRouteImport.update({ path: '/params', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const RelativeRoute = RelativeRouteImport.update({ + id: '/relative', + path: '/relative', getParentRoute: () => rootRouteImport, } as any) -const SearchSearchPlaceholderRoute = SearchSearchPlaceholderRouteImport.update({ - id: '/searchPlaceholder', - path: '/searchPlaceholder', - getParentRoute: () => SearchRouteRoute, +const SearchRouteRoute = SearchRouteRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => rootRouteImport, } as any) const ParamsParamsPlaceholderRoute = ParamsParamsPlaceholderRouteImport.update({ id: '/$paramsPlaceholder', path: '/$paramsPlaceholder', getParentRoute: () => ParamsRouteRoute, } as any) +const SearchSearchPlaceholderRoute = SearchSearchPlaceholderRouteImport.update({ + id: '/searchPlaceholder', + path: '/searchPlaceholder', + getParentRoute: () => SearchRouteRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -134,18 +134,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/relative': { - id: '/relative' - path: '/relative' - fullPath: '/relative' - preLoaderRoute: typeof RelativeRouteImport - parentRoute: typeof rootRouteImport - } - '/linkProps': { - id: '/linkProps' - path: '/linkProps' - fullPath: '/linkProps' - preLoaderRoute: typeof LinkPropsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/absolute': { @@ -155,11 +148,11 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AbsoluteRouteImport parentRoute: typeof rootRouteImport } - '/search': { - id: '/search' - path: '/search' - fullPath: '/search' - preLoaderRoute: typeof SearchRouteRouteImport + '/linkProps': { + id: '/linkProps' + path: '/linkProps' + fullPath: '/linkProps' + preLoaderRoute: typeof LinkPropsRouteImport parentRoute: typeof rootRouteImport } '/params': { @@ -169,19 +162,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ParamsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/relative': { + id: '/relative' + path: '/relative' + fullPath: '/relative' + preLoaderRoute: typeof RelativeRouteImport parentRoute: typeof rootRouteImport } - '/search/searchPlaceholder': { - id: '/search/searchPlaceholder' - path: '/searchPlaceholder' - fullPath: '/search/searchPlaceholder' - preLoaderRoute: typeof SearchSearchPlaceholderRouteImport - parentRoute: typeof SearchRouteRoute + '/search': { + id: '/search' + path: '/search' + fullPath: '/search' + preLoaderRoute: typeof SearchRouteRouteImport + parentRoute: typeof rootRouteImport } '/params/$paramsPlaceholder': { id: '/params/$paramsPlaceholder' @@ -190,6 +183,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ParamsParamsPlaceholderRouteImport parentRoute: typeof ParamsRouteRoute } + '/search/searchPlaceholder': { + id: '/search/searchPlaceholder' + path: '/searchPlaceholder' + fullPath: '/search/searchPlaceholder' + preLoaderRoute: typeof SearchSearchPlaceholderRouteImport + parentRoute: typeof SearchRouteRoute + } } } diff --git a/examples/react/start-material-ui/package.json b/examples/react/start-material-ui/package.json index 0efed05e33..1647e95f20 100644 --- a/examples/react/start-material-ui/package.json +++ b/examples/react/start-material-ui/package.json @@ -15,9 +15,9 @@ "@emotion/styled": "11.14.0", "@fontsource-variable/roboto": "5.2.5", "@mui/material": "6.4.7", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.28", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0", "zod": "^4.4.3" @@ -27,7 +27,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/start-material-ui/src/routeTree.gen.ts b/examples/react/start-material-ui/src/routeTree.gen.ts index 421daf2790..d89758e684 100644 --- a/examples/react/start-material-ui/src/routeTree.gen.ts +++ b/examples/react/start-material-ui/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/react/start-material-ui/src/router.tsx b/examples/react/start-material-ui/src/router.tsx index a464233af9..6f82cbf378 100644 --- a/examples/react/start-material-ui/src/router.tsx +++ b/examples/react/start-material-ui/src/router.tsx @@ -5,7 +5,9 @@ export function getRouter() { const router = createRouter({ routeTree, defaultPreload: 'intent', - defaultErrorComponent: (err) =>

{err.error.stack}

, + defaultErrorComponent: (err) => ( +

{err.error instanceof Error ? err.error.stack : String(err.error)}

+ ), defaultNotFoundComponent: () =>

not found

, scrollRestoration: true, }) diff --git a/examples/react/start-next-migration/.gitignore b/examples/react/start-next-migration/.gitignore new file mode 100644 index 0000000000..24e8148a7d --- /dev/null +++ b/examples/react/start-next-migration/.gitignore @@ -0,0 +1,13 @@ +node_modules +.next +.output +.nitro +.tanstack +test-results +playwright-report +.env +.env.local +*.tsbuildinfo +next-env.d.ts +next-app/AGENTS.md +next-app/CLAUDE.md diff --git a/examples/react/start-next-migration/README.md b/examples/react/start-next-migration/README.md new file mode 100644 index 0000000000..03bb53244e --- /dev/null +++ b/examples/react/start-next-migration/README.md @@ -0,0 +1,61 @@ +# Next.js to TanStack Start + +Two versions of the same small article site. `next-app/` uses the Next.js App Router; `src/` uses TanStack Start. They keep the public paths, article content, titles, descriptions, canonical URLs, search parameter, and permanent redirect. + +The private page saves one article in an encrypted session cookie. This keeps the example runnable without a database or an auth-provider account. It is a migration reference, not an authentication starter: the single demo account has no registration, password recovery, rate limiting, or account database. Do not deploy it as a public sign-in service. + +## Run + +Use Node 24 or newer and pnpm 12. From the repository root: + +```sh +pnpm install +pnpm nx run @tanstack/react-start:build +cd examples/react/start-next-migration +``` + +In each terminal that starts a server, set these variables. Generate your own secret and choose a demo password: + +```sh +export SESSION_PASSWORD="$(node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))")" +export DEMO_PASSWORD='choose-a-local-demo-password' +``` + +Run `pnpm dev:next` for Next.js at and `pnpm dev` in another terminal for Start at . Sign in as `reader@example.com` using the password you set. + +Both apps use iron-session, with different cookie names. Signing in to one does not sign you in to the other. Changing `SESSION_PASSWORD` invalidates that app's session. Saved state is tied to that session, not durable account storage. + +## Check the migration + +From this directory, with those ports free: + +```sh +pnpm exec playwright install chromium +pnpm test:e2e +pnpm build:next +pnpm build +MIGRATION_PRODUCTION=1 pnpm test:e2e +``` + +Playwright starts both dev servers with test-only credentials. The same tests run against each app and check server-rendered metadata, public paths, search, a 308 redirect, a missing article, sitemap membership, login errors, session persistence, private cache headers, saved-state mutation, and rejection of a captured mutation after sign-out. + +For a production-mode smoke check, keep the environment variables set and run `pnpm start:next` or `PORT=3101 pnpm start` after building. The cookie settings assume HTTPS in production. Deployment infrastructure, a shared database, real account security, and CDN behavior are outside this local fixture. + +## Compare + +| Next.js | TanStack Start | +| --------------------------------------------- | ------------------------------------------------------- | +| `next-app/app/page.tsx`, async `searchParams` | `src/routes/index.tsx`, `validateSearch` | +| `next-app/app/posts/[slug]/page.tsx` | `src/routes/posts.$slug.tsx` | +| `generateMetadata` | Route `head` using `loaderData` | +| `next-app/app/actions.ts` | `src/server/account.ts` | +| Server Action form and `revalidatePath` | `useServerFn`, local pending state, `router.invalidate` | +| `cookies()` with `iron-session` | `iron-session` with `getCookie` / `setCookie` | +| `next-app/next.config.ts` redirect | `src/routes/old-notes.tsx` redirect | +| `next-app/app/sitemap.ts` | `src/routes/sitemap[.]xml.ts` server route | + +The Next.js forms use Server Actions. The Start forms in this example handle client submit events and require JavaScript. For a no-JavaScript form, use a FormData-compatible server function URL or an explicit server-route POST implementation, including validation and CSRF protection. Replacing an Action with `createServerFn` does not preserve progressive enhancement automatically. + +The canonical origin is intentionally `https://field-notes.example` in both content modules, so local ports do not change the comparison. Replace it with your real public origin before adapting the example. + +The Start app enables `createCsrfMiddleware` for server-function requests in `src/start.ts`. The paired browser tests replay a mutation with an authenticated cookie jar and cross-site request metadata, then verify that it was rejected and the saved value did not change. Endpoint authorization is still checked independently after sign-out. diff --git a/examples/react/start-next-migration/next-app/account.ts b/examples/react/start-next-migration/next-app/account.ts new file mode 100644 index 0000000000..7073518994 --- /dev/null +++ b/examples/react/start-next-migration/next-app/account.ts @@ -0,0 +1,14 @@ +import { cookies } from 'next/headers' +import { getIronSession } from 'iron-session' +export async function getSession() { + const cookieStore = await cookies() + const password = process.env.SESSION_PASSWORD + if (!password || password.length < 32) { + throw new Error('Set SESSION_PASSWORD to at least 32 characters') + } + return getIronSession<{ email: string; saved: boolean }>(cookieStore, { + cookieName: 'next-migration-session', + password, + cookieOptions: { secure: process.env.NODE_ENV === 'production' }, + }) +} diff --git a/examples/react/start-next-migration/next-app/app/actions.ts b/examples/react/start-next-migration/next-app/app/actions.ts new file mode 100644 index 0000000000..325a4de176 --- /dev/null +++ b/examples/react/start-next-migration/next-app/app/actions.ts @@ -0,0 +1,36 @@ +'use server' +import { redirect } from 'next/navigation' +import { revalidatePath } from 'next/cache' +import { getSession } from '../account' +export async function signIn(_state: { error: string }, form: FormData) { + if (!process.env.DEMO_PASSWORD) { + throw new Error('Set DEMO_PASSWORD before running the example') + } + const email = form.get('email'), + password = form.get('password') + if ( + email !== 'reader@example.com' || + password !== process.env.DEMO_PASSWORD + ) { + return { error: 'Invalid credentials' } + } + const session = await getSession() + session.email = email + session.saved = false + await session.save() + redirect('/saved') +} +export async function toggleSaved() { + const session = await getSession() + if (!session.email) { + throw new Error('Unauthorized') + } + session.saved = !session.saved + await session.save() + revalidatePath('/saved') +} +export async function signOut() { + const session = await getSession() + session.destroy() + redirect('/login') +} diff --git a/examples/react/start-next-migration/next-app/app/layout.tsx b/examples/react/start-next-migration/next-app/app/layout.tsx new file mode 100644 index 0000000000..2aafe653dd --- /dev/null +++ b/examples/react/start-next-migration/next-app/app/layout.tsx @@ -0,0 +1,16 @@ +import Link from 'next/link' +import type { ReactNode } from 'react' +export default function Layout({ children }: { children: ReactNode }) { + return ( + + + + {children} + + + ) +} diff --git a/examples/react/start-next-migration/next-app/app/login/form.tsx b/examples/react/start-next-migration/next-app/app/login/form.tsx new file mode 100644 index 0000000000..41347eb65b --- /dev/null +++ b/examples/react/start-next-migration/next-app/app/login/form.tsx @@ -0,0 +1,25 @@ +'use client' +import { useActionState } from 'react' +import { signIn } from '../actions' +export function LoginForm() { + const [state, action, pending] = useActionState(signIn, { error: '' }) + return ( +
+ + + +

{state.error}

+
+ ) +} diff --git a/examples/react/start-next-migration/next-app/app/login/page.tsx b/examples/react/start-next-migration/next-app/app/login/page.tsx new file mode 100644 index 0000000000..9cbb900629 --- /dev/null +++ b/examples/react/start-next-migration/next-app/app/login/page.tsx @@ -0,0 +1,13 @@ +import { LoginForm } from './form' +export const metadata = { + title: 'Sign in | Field notes', + robots: { index: false }, +} +export default function Login() { + return ( +
+

Sign in

+ +
+ ) +} diff --git a/examples/react/start-next-migration/next-app/app/not-found.tsx b/examples/react/start-next-migration/next-app/app/not-found.tsx new file mode 100644 index 0000000000..5da341bf43 --- /dev/null +++ b/examples/react/start-next-migration/next-app/app/not-found.tsx @@ -0,0 +1,9 @@ +import Link from 'next/link' +export default function NotFound() { + return ( +
+

Article not found

+ All articles +
+ ) +} diff --git a/examples/react/start-next-migration/next-app/app/page.tsx b/examples/react/start-next-migration/next-app/app/page.tsx new file mode 100644 index 0000000000..75653b8344 --- /dev/null +++ b/examples/react/start-next-migration/next-app/app/page.tsx @@ -0,0 +1,37 @@ +import Link from 'next/link' +import { articles, siteUrl } from '../content' +export const metadata = { + title: 'Field notes', + description: + 'Notes on moving a web application without losing its public URLs.', + alternates: { canonical: siteUrl }, +} +export default async function Page({ + searchParams, +}: { + searchParams: Promise<{ q?: string | string[] }> +}) { + const search = await searchParams + const q = typeof search.q === 'string' ? search.q : '' + const visible = articles.filter((article) => + article.title.toLowerCase().includes(q.toLowerCase()), + ) + return ( +
+

Field notes

+
+ + +
+
    + {visible.map((article) => ( +
  • + {article.title} +
  • + ))} +
+
+ ) +} diff --git a/examples/react/start-next-migration/next-app/app/posts/[slug]/page.tsx b/examples/react/start-next-migration/next-app/app/posts/[slug]/page.tsx new file mode 100644 index 0000000000..36ed5b62da --- /dev/null +++ b/examples/react/start-next-migration/next-app/app/posts/[slug]/page.tsx @@ -0,0 +1,36 @@ +import { notFound } from 'next/navigation' +import { articles, siteUrl } from '../../../content' +async function getArticle(params: Promise<{ slug: string }>) { + const { slug } = await params + const article = articles.find((item) => item.slug === slug) + if (!article) { + notFound() + } + return article +} +export async function generateMetadata({ + params, +}: { + params: Promise<{ slug: string }> +}) { + const article = await getArticle(params) + return { + title: article.title, + description: article.description, + openGraph: { title: article.title }, + alternates: { canonical: `${siteUrl}/posts/${article.slug}` }, + } +} +export default async function Page({ + params, +}: { + params: Promise<{ slug: string }> +}) { + const article = await getArticle(params) + return ( +
+

{article.title}

+

{article.body}

+
+ ) +} diff --git a/examples/react/start-next-migration/next-app/app/saved/page.tsx b/examples/react/start-next-migration/next-app/app/saved/page.tsx new file mode 100644 index 0000000000..5310dbc37e --- /dev/null +++ b/examples/react/start-next-migration/next-app/app/saved/page.tsx @@ -0,0 +1,28 @@ +import { redirect } from 'next/navigation' +import { getSession } from '../../account' +import { signOut, toggleSaved } from '../actions' +export const metadata = { + title: 'Saved articles | Field notes', + robots: { index: false }, +} +export default async function Saved() { + const session = await getSession() + if (!session.email) { + redirect('/login') + } + return ( +
+

Saved articles

+

{session.email}

+

+ {session.saved ? 'Keeping your URLs is saved' : 'No saved articles'} +

+
+ +
+
+ +
+
+ ) +} diff --git a/examples/react/start-next-migration/next-app/app/sitemap.ts b/examples/react/start-next-migration/next-app/app/sitemap.ts new file mode 100644 index 0000000000..9859cffa17 --- /dev/null +++ b/examples/react/start-next-migration/next-app/app/sitemap.ts @@ -0,0 +1,7 @@ +import { articles, siteUrl } from '../content' +export default function sitemap() { + return [ + { url: siteUrl }, + ...articles.map((article) => ({ url: `${siteUrl}/posts/${article.slug}` })), + ] +} diff --git a/examples/react/start-next-migration/next-app/content.ts b/examples/react/start-next-migration/next-app/content.ts new file mode 100644 index 0000000000..2a9d15c1c0 --- /dev/null +++ b/examples/react/start-next-migration/next-app/content.ts @@ -0,0 +1,15 @@ +export const articles = [ + { + slug: 'keeping-your-urls', + title: 'Keeping your URLs', + description: 'Preserve public URLs when changing frameworks.', + body: 'A framework migration can keep the URLs your readers already use.', + }, + { + slug: 'checking-your-metadata', + title: 'Checking your metadata', + description: 'Compare rendered titles and canonical URLs before launch.', + body: 'Check the server response as well as the page after client navigation.', + }, +] +export const siteUrl = 'https://field-notes.example' diff --git a/examples/react/start-next-migration/next-app/next.config.ts b/examples/react/start-next-migration/next-app/next.config.ts new file mode 100644 index 0000000000..dc72c3ae72 --- /dev/null +++ b/examples/react/start-next-migration/next-app/next.config.ts @@ -0,0 +1,13 @@ +import type { NextConfig } from 'next' +const config: NextConfig = { + async redirects() { + return [ + { + source: '/old-notes', + destination: '/posts/keeping-your-urls', + permanent: true, + }, + ] + }, +} +export default config diff --git a/examples/react/start-next-migration/next-app/tsconfig.json b/examples/react/start-next-migration/next-app/tsconfig.json new file mode 100644 index 0000000000..8786ab9834 --- /dev/null +++ b/examples/react/start-next-migration/next-app/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "target": "ES2024", + "lib": ["dom", "dom.iterable", "esnext"], + "allowJs": true, + "skipLibCheck": true, + "strict": true, + "noEmit": true, + "esModuleInterop": true, + "module": "esnext", + "moduleResolution": "bundler", + "resolveJsonModule": true, + "isolatedModules": true, + "jsx": "react-jsx", + "incremental": true, + "plugins": [ + { + "name": "next" + } + ] + }, + "include": [ + "next-env.d.ts", + "**/*.ts", + "**/*.tsx", + ".next/types/**/*.ts", + ".next/dev/types/**/*.ts" + ], + "exclude": ["node_modules"] +} diff --git a/examples/react/start-next-migration/package.json b/examples/react/start-next-migration/package.json new file mode 100644 index 0000000000..0c2a2a9563 --- /dev/null +++ b/examples/react/start-next-migration/package.json @@ -0,0 +1,43 @@ +{ + "name": "tanstack-start-example-next-migration", + "private": true, + "type": "module", + "scripts": { + "dev": "vite dev --port 3101", + "dev:next": "next dev next-app --port 3100", + "build": "vite build && tsc --noEmit", + "build:next": "next build next-app", + "start": "node .output/server/index.mjs", + "start:next": "next start next-app --port 3100", + "test:e2e": "playwright test" + }, + "dependencies": { + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-start": "^1.169.6", + "iron-session": "^9.0.1", + "next": "16.3.4", + "react": "^19.2.3", + "react-dom": "^19.2.3" + }, + "devDependencies": { + "@playwright/test": "^1.61.0", + "@types/node": "^22.10.2", + "@types/react": "^19.2.8", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^6.0.1", + "nitro": "^3.0.260903-beta", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14" + }, + "nx": { + "targets": { + "test:e2e": { + "outputs": [ + "...", + "{projectRoot}/next-app/.next", + "{projectRoot}/next-app/next-env.d.ts" + ] + } + } + } +} diff --git a/examples/react/start-next-migration/playwright.config.ts b/examples/react/start-next-migration/playwright.config.ts new file mode 100644 index 0000000000..ce48715df4 --- /dev/null +++ b/examples/react/start-next-migration/playwright.config.ts @@ -0,0 +1,30 @@ +import { defineConfig } from '@playwright/test' + +const production = process.env.MIGRATION_PRODUCTION === '1' +const env = { + SESSION_PASSWORD: 'migration-reference-test-secret-at-least-32-characters', + DEMO_PASSWORD: 'migration-test-password', +} + +export default defineConfig({ + testDir: './tests', + use: { browserName: 'chromium' }, + projects: [ + { name: 'next', use: { baseURL: 'http://localhost:3100' } }, + { name: 'start', use: { baseURL: 'http://localhost:3101' } }, + ], + webServer: [ + { + command: production ? 'pnpm start:next' : 'pnpm dev:next', + url: 'http://localhost:3100', + env, + timeout: 120_000, + }, + { + command: production ? 'PORT=3101 pnpm start' : 'pnpm dev', + url: 'http://localhost:3101', + env, + timeout: 120_000, + }, + ], +}) diff --git a/examples/react/start-next-migration/src/content.ts b/examples/react/start-next-migration/src/content.ts new file mode 100644 index 0000000000..2a9d15c1c0 --- /dev/null +++ b/examples/react/start-next-migration/src/content.ts @@ -0,0 +1,15 @@ +export const articles = [ + { + slug: 'keeping-your-urls', + title: 'Keeping your URLs', + description: 'Preserve public URLs when changing frameworks.', + body: 'A framework migration can keep the URLs your readers already use.', + }, + { + slug: 'checking-your-metadata', + title: 'Checking your metadata', + description: 'Compare rendered titles and canonical URLs before launch.', + body: 'Check the server response as well as the page after client navigation.', + }, +] +export const siteUrl = 'https://field-notes.example' diff --git a/examples/react/start-next-migration/src/routeTree.gen.ts b/examples/react/start-next-migration/src/routeTree.gen.ts new file mode 100644 index 0000000000..15eeafce02 --- /dev/null +++ b/examples/react/start-next-migration/src/routeTree.gen.ts @@ -0,0 +1,167 @@ +/* eslint-disable */ + +// @ts-nocheck + +// 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 LoginRouteImport } from './routes/login' +import { Route as OldNotesRouteImport } from './routes/old-notes' +import { Route as SavedRouteImport } from './routes/saved' +import { Route as SitemapDotxmlRouteImport } from './routes/sitemap[.]xml' +import { Route as PostsSlugRouteImport } from './routes/posts.$slug' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', + getParentRoute: () => rootRouteImport, +} as any) +const OldNotesRoute = OldNotesRouteImport.update({ + id: '/old-notes', + path: '/old-notes', + getParentRoute: () => rootRouteImport, +} as any) +const SavedRoute = SavedRouteImport.update({ + id: '/saved', + path: '/saved', + getParentRoute: () => rootRouteImport, +} as any) +const SitemapDotxmlRoute = SitemapDotxmlRouteImport.update({ + id: '/sitemap.xml', + path: '/sitemap.xml', + getParentRoute: () => rootRouteImport, +} as any) +const PostsSlugRoute = PostsSlugRouteImport.update({ + id: '/posts/$slug', + path: '/posts/$slug', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/login': typeof LoginRoute + '/old-notes': typeof OldNotesRoute + '/saved': typeof SavedRoute + '/sitemap.xml': typeof SitemapDotxmlRoute + '/posts/$slug': typeof PostsSlugRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/login': typeof LoginRoute + '/old-notes': typeof OldNotesRoute + '/saved': typeof SavedRoute + '/sitemap.xml': typeof SitemapDotxmlRoute + '/posts/$slug': typeof PostsSlugRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/login': typeof LoginRoute + '/old-notes': typeof OldNotesRoute + '/saved': typeof SavedRoute + '/sitemap.xml': typeof SitemapDotxmlRoute + '/posts/$slug': typeof PostsSlugRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + '/' | '/login' | '/old-notes' | '/saved' | '/sitemap.xml' | '/posts/$slug' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/login' | '/old-notes' | '/saved' | '/sitemap.xml' | '/posts/$slug' + id: + | '__root__' + | '/' + | '/login' + | '/old-notes' + | '/saved' + | '/sitemap.xml' + | '/posts/$slug' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + LoginRoute: typeof LoginRoute + OldNotesRoute: typeof OldNotesRoute + SavedRoute: typeof SavedRoute + SitemapDotxmlRoute: typeof SitemapDotxmlRoute + PostsSlugRoute: typeof PostsSlugRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport + } + '/old-notes': { + id: '/old-notes' + path: '/old-notes' + fullPath: '/old-notes' + preLoaderRoute: typeof OldNotesRouteImport + parentRoute: typeof rootRouteImport + } + '/saved': { + id: '/saved' + path: '/saved' + fullPath: '/saved' + preLoaderRoute: typeof SavedRouteImport + parentRoute: typeof rootRouteImport + } + '/sitemap.xml': { + id: '/sitemap.xml' + path: '/sitemap.xml' + fullPath: '/sitemap.xml' + preLoaderRoute: typeof SitemapDotxmlRouteImport + parentRoute: typeof rootRouteImport + } + '/posts/$slug': { + id: '/posts/$slug' + path: '/posts/$slug' + fullPath: '/posts/$slug' + preLoaderRoute: typeof PostsSlugRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + LoginRoute: LoginRoute, + OldNotesRoute: OldNotesRoute, + SavedRoute: SavedRoute, + SitemapDotxmlRoute: SitemapDotxmlRoute, + PostsSlugRoute: PostsSlugRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() + +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> + } +} diff --git a/examples/react/start-next-migration/src/router.tsx b/examples/react/start-next-migration/src/router.tsx new file mode 100644 index 0000000000..9711e610bf --- /dev/null +++ b/examples/react/start-next-migration/src/router.tsx @@ -0,0 +1,5 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' +export function getRouter() { + return createRouter({ routeTree, scrollRestoration: true }) +} diff --git a/examples/react/start-next-migration/src/routes/__root.tsx b/examples/react/start-next-migration/src/routes/__root.tsx new file mode 100644 index 0000000000..a7eaa0168f --- /dev/null +++ b/examples/react/start-next-migration/src/routes/__root.tsx @@ -0,0 +1,46 @@ +import { + createRootRoute, + HeadContent, + Link, + Outlet, + Scripts, +} from '@tanstack/react-router' +import type { ReactNode } from 'react' +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + ], + }), + component: Outlet, + shellComponent: Document, + notFoundComponent: () => ( +
+

Article not found

+ + All articles + +
+ ), +}) +function Document({ children }: { children: ReactNode }) { + return ( + + + + + + + {children} + + + + ) +} diff --git a/examples/react/start-next-migration/src/routes/index.tsx b/examples/react/start-next-migration/src/routes/index.tsx new file mode 100644 index 0000000000..8778d9d01f --- /dev/null +++ b/examples/react/start-next-migration/src/routes/index.tsx @@ -0,0 +1,45 @@ +import { createFileRoute, Link } from '@tanstack/react-router' +import { articles, siteUrl } from '../content' +export const Route = createFileRoute('/')({ + validateSearch: (search) => ({ + q: typeof search.q === 'string' ? search.q : '', + }), + head: () => ({ + meta: [ + { title: 'Field notes' }, + { + name: 'description', + content: + 'Notes on moving a web application without losing its public URLs.', + }, + ], + links: [{ rel: 'canonical', href: siteUrl }], + }), + component: Articles, +}) +function Articles() { + const { q } = Route.useSearch() + const visible = articles.filter((article) => + article.title.toLowerCase().includes(q.toLowerCase()), + ) + return ( +
+

Field notes

+
+ + +
+
    + {visible.map((article) => ( +
  • + + {article.title} + +
  • + ))} +
+
+ ) +} diff --git a/examples/react/start-next-migration/src/routes/login.tsx b/examples/react/start-next-migration/src/routes/login.tsx new file mode 100644 index 0000000000..628261cc8e --- /dev/null +++ b/examples/react/start-next-migration/src/routes/login.tsx @@ -0,0 +1,70 @@ +import { createFileRoute, useHydrated, useRouter } from '@tanstack/react-router' +import { useServerFn } from '@tanstack/react-start' +import { useState } from 'react' +import { signIn } from '../server/account' +export const Route = createFileRoute('/login')({ + head: () => ({ + meta: [ + { title: 'Sign in | Field notes' }, + { name: 'robots', content: 'noindex' }, + ], + }), + component: Login, +}) +function Login() { + const hydrated = useHydrated() + const login = useServerFn(signIn) + const router = useRouter() + const [error, setError] = useState('') + const [pending, setPending] = useState(false) + return ( +
+

Sign in

+
{ + event.preventDefault() + const form = new FormData(event.currentTarget) + const email = form.get('email'), + password = form.get('password') + if (typeof email !== 'string' || typeof password !== 'string') { + return + } + setPending(true) + setError('') + try { + const result = await login({ data: { email, password } }) + if (result.error) { + setError(result.error) + return + } + await router.invalidate() + await router.navigate({ to: '/saved' }) + } catch { + setError('Sign-in failed. Try again.') + } finally { + setPending(false) + } + }} + > +
+ + + +
+

{error}

+
+
+ ) +} diff --git a/examples/react/start-next-migration/src/routes/old-notes.tsx b/examples/react/start-next-migration/src/routes/old-notes.tsx new file mode 100644 index 0000000000..1fb5ce846b --- /dev/null +++ b/examples/react/start-next-migration/src/routes/old-notes.tsx @@ -0,0 +1,10 @@ +import { createFileRoute, redirect } from '@tanstack/react-router' +export const Route = createFileRoute('/old-notes')({ + beforeLoad: () => { + throw redirect({ + to: '/posts/$slug', + params: { slug: 'keeping-your-urls' }, + statusCode: 308, + }) + }, +}) diff --git a/examples/react/start-next-migration/src/routes/posts.$slug.tsx b/examples/react/start-next-migration/src/routes/posts.$slug.tsx new file mode 100644 index 0000000000..1998717393 --- /dev/null +++ b/examples/react/start-next-migration/src/routes/posts.$slug.tsx @@ -0,0 +1,34 @@ +import { createFileRoute, notFound } from '@tanstack/react-router' +import { articles, siteUrl } from '../content' +export const Route = createFileRoute('/posts/$slug')({ + loader: ({ params }) => { + const article = articles.find((item) => item.slug === params.slug) + if (!article) { + throw notFound() + } + return article + }, + head: ({ loaderData }) => + loaderData + ? { + meta: [ + { title: loaderData.title }, + { name: 'description', content: loaderData.description }, + { property: 'og:title', content: loaderData.title }, + ], + links: [ + { rel: 'canonical', href: `${siteUrl}/posts/${loaderData.slug}` }, + ], + } + : {}, + component: Article, +}) +function Article() { + const article = Route.useLoaderData() + return ( +
+

{article.title}

+

{article.body}

+
+ ) +} diff --git a/examples/react/start-next-migration/src/routes/saved.tsx b/examples/react/start-next-migration/src/routes/saved.tsx new file mode 100644 index 0000000000..2f526eb7b5 --- /dev/null +++ b/examples/react/start-next-migration/src/routes/saved.tsx @@ -0,0 +1,79 @@ +import { + createFileRoute, + redirect, + useHydrated, + useRouter, +} from '@tanstack/react-router' +import { useServerFn } from '@tanstack/react-start' +import { useState } from 'react' +import { getAccount, signOut, toggleSaved } from '../server/account' +export const Route = createFileRoute('/saved')({ + loader: async () => { + const account = await getAccount() + if (!account) { + throw redirect({ to: '/login' }) + } + return account + }, + headers: () => ({ 'Cache-Control': 'private, no-store' }), + head: () => ({ + meta: [ + { title: 'Saved articles | Field notes' }, + { name: 'robots', content: 'noindex' }, + ], + }), + component: Saved, +}) +function Saved() { + const hydrated = useHydrated() + const account = Route.useLoaderData() + const toggle = useServerFn(toggleSaved), + logout = useServerFn(signOut) + const router = useRouter() + const [pending, setPending] = useState(false), + [error, setError] = useState('') + return ( +
+

Saved articles

+

{account.email}

+

+ {account.saved ? 'Keeping your URLs is saved' : 'No saved articles'} +

+ + +

{error}

+
+ ) +} diff --git a/examples/react/start-next-migration/src/routes/sitemap[.]xml.ts b/examples/react/start-next-migration/src/routes/sitemap[.]xml.ts new file mode 100644 index 0000000000..a7dfcaa594 --- /dev/null +++ b/examples/react/start-next-migration/src/routes/sitemap[.]xml.ts @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/react-router' +import { articles, siteUrl } from '../content' +export const Route = createFileRoute('/sitemap.xml')({ + server: { + handlers: { + GET: () => + new Response( + `${siteUrl}${articles.map((article) => `${siteUrl}/posts/${article.slug}`).join('')}`, + { headers: { 'Content-Type': 'application/xml' } }, + ), + }, + }, +}) diff --git a/examples/react/start-next-migration/src/server/account.ts b/examples/react/start-next-migration/src/server/account.ts new file mode 100644 index 0000000000..85e921c74b --- /dev/null +++ b/examples/react/start-next-migration/src/server/account.ts @@ -0,0 +1,77 @@ +import { getIronSession } from 'iron-session' +import { createServerFn } from '@tanstack/react-start' +import { + getCookie, + setCookie, + setResponseStatus, + setResponseHeader, +} from '@tanstack/react-start/server' +import { redirect } from '@tanstack/react-router' +async function session() { + setResponseHeader('Cache-Control', 'private, no-store') + const password = process.env.SESSION_PASSWORD + if (!password || password.length < 32) { + throw new Error('Set SESSION_PASSWORD to at least 32 characters') + } + return getIronSession<{ email: string; saved: boolean }>( + { read: getCookie, write: setCookie }, + { + cookieName: 'start-migration-session', + password, + ttl: 7 * 24 * 60 * 60, + cookieOptions: { + httpOnly: true, + secure: process.env.NODE_ENV === 'production', + sameSite: 'lax', + path: '/', + }, + }, + ) +} +export const getAccount = createServerFn({ method: 'GET' }).handler( + async () => { + const current = await session() + return current.email + ? { email: current.email, saved: current.saved ?? false } + : null + }, +) +export const signIn = createServerFn({ method: 'POST' }) + .validator((input: { email: string; password: string }) => { + if (typeof input.email !== 'string' || typeof input.password !== 'string') { + throw new Error('Invalid credentials') + } + return input + }) + .handler(async ({ data }) => { + if (!process.env.DEMO_PASSWORD) { + throw new Error('Set DEMO_PASSWORD before running the example') + } + if ( + data.email !== 'reader@example.com' || + data.password !== process.env.DEMO_PASSWORD + ) { + return { error: 'Invalid credentials' } + } + const current = await session() + current.email = data.email + current.saved = false + await current.save() + return { error: '' } + }) +export const toggleSaved = createServerFn({ method: 'POST' }).handler( + async () => { + const current = await session() + if (!current.email) { + setResponseStatus(401) + throw new Error('Unauthorized') + } + current.saved = !current.saved + await current.save() + }, +) +export const signOut = createServerFn({ method: 'POST' }).handler(async () => { + const current = await session() + current.destroy() + throw redirect({ to: '/login' }) +}) diff --git a/examples/react/start-next-migration/src/start.ts b/examples/react/start-next-migration/src/start.ts new file mode 100644 index 0000000000..5fb1e247fb --- /dev/null +++ b/examples/react/start-next-migration/src/start.ts @@ -0,0 +1,9 @@ +import { createCsrfMiddleware, createStart } from '@tanstack/react-start' + +export const startInstance = createStart(() => ({ + requestMiddleware: [ + createCsrfMiddleware({ + filter: (ctx) => ctx.handlerType === 'serverFn', + }), + ], +})) diff --git a/examples/react/start-next-migration/tests/migration.spec.ts b/examples/react/start-next-migration/tests/migration.spec.ts new file mode 100644 index 0000000000..7009095977 --- /dev/null +++ b/examples/react/start-next-migration/tests/migration.spec.ts @@ -0,0 +1,163 @@ +import { expect, test } from '@playwright/test' + +test('public URLs, server metadata, search, redirects, and missing pages survive migration', async ({ + page, + request, +}) => { + const response = await request.get('/posts/keeping-your-urls') + expect(response.status()).toBe(200) + const html = await response.text() + expect(html).toContain('Keeping your URLs') + expect(html).toMatch( + /]+name="description"[^>]+content="Preserve public URLs when changing frameworks\."/, + ) + expect(html).toMatch( + /]+rel="canonical"[^>]+href="https:\/\/field-notes\.example\/posts\/keeping-your-urls"/, + ) + expect(html).toMatch( + /]+property="og:title"[^>]+content="Keeping your URLs"/, + ) + expect(html).toContain( + 'A framework migration can keep the URLs your readers already use.', + ) + + const old = await request.get('/old-notes', { maxRedirects: 0 }) + expect(old.status()).toBe(308) + expect(new URL(old.headers().location, old.url()).pathname).toBe( + '/posts/keeping-your-urls', + ) + expect((await request.get('/posts/missing')).status()).toBe(404) + const sitemap = await (await request.get('/sitemap.xml')).text() + expect(sitemap).toContain( + 'https://field-notes.example/posts/keeping-your-urls', + ) + expect(sitemap).not.toContain('/saved') + + await page.goto('/?q=metadata') + await expect( + page.getByRole('link', { name: 'Checking your metadata' }), + ).toBeVisible() + await expect( + page.getByRole('link', { name: 'Keeping your URLs' }), + ).toHaveCount(0) + await page.getByRole('link', { name: 'Checking your metadata' }).click() + await expect(page).toHaveURL(/\/posts\/checking-your-metadata$/) + await expect(page).toHaveTitle('Checking your metadata') + await expect(page.locator('link[rel="canonical"]')).toHaveAttribute( + 'href', + 'https://field-notes.example/posts/checking-your-metadata', + ) +}) + +test('sessions and protected mutations survive reload but cannot run after sign-out', async ({ + page, +}, testInfo) => { + await page.goto('/saved') + await expect(page).toHaveURL(/\/login$/) + await page.getByLabel('Email', { exact: true }).fill('reader@example.com') + await page.getByLabel('Password', { exact: true }).fill('wrong-password') + await page.getByRole('button', { name: 'Sign in', exact: true }).click() + await expect(page.getByRole('main').getByRole('alert')).toHaveText( + 'Invalid credentials', + ) + await page.getByLabel('Email', { exact: true }).fill('reader@example.com') + await page + .getByLabel('Password', { exact: true }) + .fill('migration-test-password') + await page.getByRole('button', { name: 'Sign in', exact: true }).click() + await expect(page).toHaveURL(/\/saved$/) + await expect(page.getByTestId('saved-state')).toHaveText('No saved articles') + const mutation = page.waitForRequest((request) => request.method() === 'POST') + await page.getByRole('button', { name: 'Save article', exact: true }).click() + const savedRequest = await mutation + await expect(page.getByTestId('saved-state')).toHaveText( + 'Keeping your URLs is saved', + ) + // Keep the authenticated cookie jar while replaying a cross-site request. + const crossSiteHeaders = await savedRequest.allHeaders() + delete crossSiteHeaders.cookie + delete crossSiteHeaders['content-length'] + crossSiteHeaders.origin = 'https://untrusted.example' + crossSiteHeaders['sec-fetch-site'] = 'cross-site' + const crossSite = await page.request.post(savedRequest.url(), { + headers: crossSiteHeaders, + data: savedRequest.postData() ?? '', + }) + if (testInfo.project.name === 'start') { + expect(crossSite.status()).toBe(403) + } else { + expect(crossSite.status()).toBeGreaterThanOrEqual(400) + } + + const response = await page.reload() + expect(response?.headers()['cache-control']).toMatch( + process.env.MIGRATION_PRODUCTION ? /no-store/ : /no-store|no-cache/, + ) + await expect(page.getByTestId('saved-state')).toHaveText( + 'Keeping your URLs is saved', + ) + await page.getByRole('button', { name: 'Sign out', exact: true }).click() + await expect(page).toHaveURL(/\/login$/) + + // Replay the real mutation with the now-signed-out browser cookie jar. + const headers = await savedRequest.allHeaders() + delete headers.cookie + delete headers['content-length'] + const denied = await page.request.post(savedRequest.url(), { + headers, + data: savedRequest.postData() ?? '', + }) + expect(denied.status()).toBeGreaterThanOrEqual(400) + await page.goto('/saved') + await expect(page).toHaveURL(/\/login$/) +}) + +test('Start serializes saving and signing out so their responses cannot arrive out of order', async ({ + page, +}, testInfo) => { + test.skip(testInfo.project.name !== 'start', 'Start event-handler regression') + await page.goto('/login') + await page.getByLabel('Email', { exact: true }).fill('reader@example.com') + await page + .getByLabel('Password', { exact: true }) + .fill('migration-test-password') + await page.getByRole('button', { name: 'Sign in', exact: true }).click() + await expect(page).toHaveURL(/\/saved$/) + + for (const action of ['Save article', 'Sign out']) { + let release = () => {} + const held = new Promise((resolve) => { + release = resolve + }) + await page.route('**/_serverFn/**', async (route) => { + if (route.request().method() === 'POST') { + await held + } + await route.continue() + }) + await page.getByRole('button', { name: action, exact: true }).click() + try { + await expect( + page.getByRole('button', { name: /^(Save|Remove) article$/ }), + ).toBeDisabled() + await expect( + page.getByRole('button', { name: 'Sign out', exact: true }), + ).toBeDisabled() + } finally { + release() + } + if (action === 'Save article') { + await expect(page.getByTestId('saved-state')).toHaveText( + 'Keeping your URLs is saved', + ) + await expect( + page.getByRole('button', { name: 'Sign out', exact: true }), + ).toBeEnabled() + } else { + await expect(page).toHaveURL(/\/login$/) + } + await page.unrouteAll({ behavior: 'wait' }) + } + await page.goto('/saved') + await expect(page).toHaveURL(/\/login$/) +}) diff --git a/examples/react/start-next-migration/tsconfig.json b/examples/react/start-next-migration/tsconfig.json new file mode 100644 index 0000000000..a41553b9a1 --- /dev/null +++ b/examples/react/start-next-migration/tsconfig.json @@ -0,0 +1,21 @@ +{ + "include": [ + "src/**/*.ts", + "src/**/*.tsx", + "vite.config.ts", + "playwright.config.ts", + "tests/**/*.ts" + ], + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["DOM", "DOM.Iterable", "ES2024"], + "skipLibCheck": true, + "target": "ES2024", + "noEmit": true, + "types": ["vite/client"] + } +} diff --git a/examples/react/start-next-migration/vite.config.ts b/examples/react/start-next-migration/vite.config.ts new file mode 100644 index 0000000000..26d0e455d5 --- /dev/null +++ b/examples/react/start-next-migration/vite.config.ts @@ -0,0 +1,5 @@ +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import { nitro } from 'nitro/vite' +export default defineConfig({ plugins: [tanstackStart(), react(), nitro()] }) diff --git a/examples/react/start-rscs/package.json b/examples/react/start-rscs/package.json index 8d39c00a79..00c88681d7 100644 --- a/examples/react/start-rscs/package.json +++ b/examples/react/start-rscs/package.json @@ -10,9 +10,9 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.28", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "dexie": "^4.0.10", "react": "^19.2.0", "react-dom": "^19.2.0", @@ -26,8 +26,8 @@ "@types/react": "^19.2.2", "@types/react-dom": "^19.2.2", "@vitejs/plugin-react": "^6.0.1", - "@vitejs/plugin-rsc": "^0.5.20", - "nitro": "^3.0.260311-beta", + "@vitejs/plugin-rsc": "^0.5.39", + "nitro": "^3.0.260903-beta", "tailwindcss": "^4.1.18", "typescript": "^5.7.2", "vite": "^8.0.14" diff --git a/examples/react/start-rscs/src/routeTree.gen.ts b/examples/react/start-rscs/src/routeTree.gen.ts index ca4cef3864..d89ab3d3e7 100644 --- a/examples/react/start-rscs/src/routeTree.gen.ts +++ b/examples/react/start-rscs/src/routeTree.gen.ts @@ -9,26 +9,16 @@ // 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 PokemonRscRouteImport } from './routes/pokemon-rsc' -import { Route as PokemonRouteImport } from './routes/pokemon' -import { Route as LowLevelApiRouteImport } from './routes/low-level-api' -import { Route as ECommerceRouteImport } from './routes/e-commerce' import { Route as IndexRouteImport } from './routes/index' +import { Route as ECommerceRouteImport } from './routes/e-commerce' +import { Route as LowLevelApiRouteImport } from './routes/low-level-api' +import { Route as PokemonRouteImport } from './routes/pokemon' +import { Route as PokemonRscRouteImport } from './routes/pokemon-rsc' import { Route as ApiRscRouteImport } from './routes/api/rsc' -const PokemonRscRoute = PokemonRscRouteImport.update({ - id: '/pokemon-rsc', - path: '/pokemon-rsc', - getParentRoute: () => rootRouteImport, -} as any) -const PokemonRoute = PokemonRouteImport.update({ - id: '/pokemon', - path: '/pokemon', - getParentRoute: () => rootRouteImport, -} as any) -const LowLevelApiRoute = LowLevelApiRouteImport.update({ - id: '/low-level-api', - path: '/low-level-api', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const ECommerceRoute = ECommerceRouteImport.update({ @@ -36,9 +26,19 @@ const ECommerceRoute = ECommerceRouteImport.update({ path: '/e-commerce', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LowLevelApiRoute = LowLevelApiRouteImport.update({ + id: '/low-level-api', + path: '/low-level-api', + getParentRoute: () => rootRouteImport, +} as any) +const PokemonRoute = PokemonRouteImport.update({ + id: '/pokemon', + path: '/pokemon', + getParentRoute: () => rootRouteImport, +} as any) +const PokemonRscRoute = PokemonRscRouteImport.update({ + id: '/pokemon-rsc', + path: '/pokemon-rsc', getParentRoute: () => rootRouteImport, } as any) const ApiRscRoute = ApiRscRouteImport.update({ @@ -110,25 +110,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/pokemon-rsc': { - id: '/pokemon-rsc' - path: '/pokemon-rsc' - fullPath: '/pokemon-rsc' - preLoaderRoute: typeof PokemonRscRouteImport - parentRoute: typeof rootRouteImport - } - '/pokemon': { - id: '/pokemon' - path: '/pokemon' - fullPath: '/pokemon' - preLoaderRoute: typeof PokemonRouteImport - parentRoute: typeof rootRouteImport - } - '/low-level-api': { - id: '/low-level-api' - path: '/low-level-api' - fullPath: '/low-level-api' - preLoaderRoute: typeof LowLevelApiRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/e-commerce': { @@ -138,11 +124,25 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ECommerceRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/low-level-api': { + id: '/low-level-api' + path: '/low-level-api' + fullPath: '/low-level-api' + preLoaderRoute: typeof LowLevelApiRouteImport + parentRoute: typeof rootRouteImport + } + '/pokemon': { + id: '/pokemon' + path: '/pokemon' + fullPath: '/pokemon' + preLoaderRoute: typeof PokemonRouteImport + parentRoute: typeof rootRouteImport + } + '/pokemon-rsc': { + id: '/pokemon-rsc' + path: '/pokemon-rsc' + fullPath: '/pokemon-rsc' + preLoaderRoute: typeof PokemonRscRouteImport parentRoute: typeof rootRouteImport } '/api/rsc': { diff --git a/examples/react/start-streaming-data-from-server-functions/package.json b/examples/react/start-streaming-data-from-server-functions/package.json index 82ddd0726e..762bbff733 100644 --- a/examples/react/start-streaming-data-from-server-functions/package.json +++ b/examples/react/start-streaming-data-from-server-functions/package.json @@ -10,9 +10,9 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.28", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0", "zod": "^4.4.3" @@ -22,7 +22,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/start-streaming-data-from-server-functions/src/router.tsx b/examples/react/start-streaming-data-from-server-functions/src/router.tsx index a464233af9..6f82cbf378 100644 --- a/examples/react/start-streaming-data-from-server-functions/src/router.tsx +++ b/examples/react/start-streaming-data-from-server-functions/src/router.tsx @@ -5,7 +5,9 @@ export function getRouter() { const router = createRouter({ routeTree, defaultPreload: 'intent', - defaultErrorComponent: (err) =>

{err.error.stack}

, + defaultErrorComponent: (err) => ( +

{err.error instanceof Error ? err.error.stack : String(err.error)}

+ ), defaultNotFoundComponent: () =>

not found

, scrollRestoration: true, }) diff --git a/examples/react/start-supabase-basic/.gitignore b/examples/react/start-supabase-basic/.gitignore index 8293849e8d..372dc30373 100644 --- a/examples/react/start-supabase-basic/.gitignore +++ b/examples/react/start-supabase-basic/.gitignore @@ -1,12 +1,11 @@ node_modules -# Keep environment variables out of version control -!.env package-lock.json yarn.lock .DS_Store .cache -.env +# The checked-in .env contains public demo values used by the build. +!.env .vercel .output /build/ diff --git a/examples/react/start-supabase-basic/package.json b/examples/react/start-supabase-basic/package.json index c28c4c0972..0bf4b2c246 100644 --- a/examples/react/start-supabase-basic/package.json +++ b/examples/react/start-supabase-basic/package.json @@ -15,9 +15,9 @@ "dependencies": { "@supabase/ssr": "^0.5.2", "@supabase/supabase-js": "^2.48.1", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.28", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" @@ -28,7 +28,8 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/start-supabase-basic/src/routeTree.gen.ts b/examples/react/start-supabase-basic/src/routeTree.gen.ts index 6be84444eb..998d34a709 100644 --- a/examples/react/start-supabase-basic/src/routeTree.gen.ts +++ b/examples/react/start-supabase-basic/src/routeTree.gen.ts @@ -9,23 +9,22 @@ // 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 SignupRouteImport } from './routes/signup' -import { Route as LogoutRouteImport } from './routes/logout' -import { Route as LoginRouteImport } from './routes/login' -import { Route as AuthedRouteImport } from './routes/_authed' import { Route as IndexRouteImport } from './routes/index' +import { Route as AuthedRouteImport } from './routes/_authed' +import { Route as LoginRouteImport } from './routes/login' +import { Route as LogoutRouteImport } from './routes/logout' +import { Route as SignupRouteImport } from './routes/signup' import { Route as AuthedPostsRouteImport } from './routes/_authed/posts' import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' -const SignupRoute = SignupRouteImport.update({ - id: '/signup', - path: '/signup', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', getParentRoute: () => rootRouteImport, } as any) const LoginRoute = LoginRouteImport.update({ @@ -33,13 +32,14 @@ const LoginRoute = LoginRouteImport.update({ path: '/login', getParentRoute: () => rootRouteImport, } as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', +const LogoutRoute = LogoutRouteImport.update({ + id: '/logout', + path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SignupRoute = SignupRouteImport.update({ + id: '/signup', + path: '/signup', getParentRoute: () => rootRouteImport, } as any) const AuthedPostsRoute = AuthedPostsRouteImport.update({ @@ -120,25 +120,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/signup': { - id: '/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof SignupRouteImport - parentRoute: typeof rootRouteImport - } - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport - parentRoute: typeof rootRouteImport - } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_authed': { @@ -148,11 +134,25 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthedRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport + } + '/logout': { + id: '/logout' + path: '/logout' + fullPath: '/logout' + preLoaderRoute: typeof LogoutRouteImport + parentRoute: typeof rootRouteImport + } + '/signup': { + id: '/signup' + path: '/signup' + fullPath: '/signup' + preLoaderRoute: typeof SignupRouteImport parentRoute: typeof rootRouteImport } '/_authed/posts': { diff --git a/examples/react/start-supabase-basic/src/routes/_authed.tsx b/examples/react/start-supabase-basic/src/routes/_authed.tsx index ed97848e6a..697e35e427 100644 --- a/examples/react/start-supabase-basic/src/routes/_authed.tsx +++ b/examples/react/start-supabase-basic/src/routes/_authed.tsx @@ -27,7 +27,7 @@ export const Route = createFileRoute('/_authed')({ } }, errorComponent: ({ error }) => { - if (error.message === 'Not authenticated') { + if (error instanceof Error && error.message === 'Not authenticated') { return } diff --git a/examples/react/start-tailwind-v4/package.json b/examples/react/start-tailwind-v4/package.json index 840669580e..b58fbe4ff0 100644 --- a/examples/react/start-tailwind-v4/package.json +++ b/examples/react/start-tailwind-v4/package.json @@ -10,9 +10,9 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.28", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "react": "^19.0.0", "react-dom": "^19.0.0", "tailwind-merge": "^3.6.0", @@ -25,7 +25,8 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/start-trellaux/package.json b/examples/react/start-trellaux/package.json index 58d3386253..7755d227fc 100644 --- a/examples/react/start-trellaux/package.json +++ b/examples/react/start-trellaux/package.json @@ -10,12 +10,12 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-router-ssr-query": "^1.167.1", - "@tanstack/react-start": "^1.168.28", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router-ssr-query": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "ky": "^1.7.4", "msw": "^2.7.0", "react": "^19.0.0", @@ -32,7 +32,8 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/start-workos/package.json b/examples/react/start-workos/package.json index 3639294bac..0ab7e89c2d 100644 --- a/examples/react/start-workos/package.json +++ b/examples/react/start-workos/package.json @@ -14,9 +14,9 @@ "license": "MIT", "dependencies": { "@radix-ui/themes": "^3.3.0", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.28", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-start": "^1.169.6", "@workos/authkit-tanstack-react-start": "^0.5.0", "react": "^19.0.0", "react-dom": "^19.0.0" @@ -25,7 +25,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/start-workos/src/routeTree.gen.ts b/examples/react/start-workos/src/routeTree.gen.ts index 49009fc848..559db280de 100644 --- a/examples/react/start-workos/src/routeTree.gen.ts +++ b/examples/react/start-workos/src/routeTree.gen.ts @@ -9,16 +9,20 @@ // 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 LogoutRouteImport } from './routes/logout' -import { Route as ClientRouteImport } from './routes/client' -import { Route as AuthenticatedRouteImport } from './routes/_authenticated' import { Route as IndexRouteImport } from './routes/index' +import { Route as AuthenticatedRouteImport } from './routes/_authenticated' +import { Route as ClientRouteImport } from './routes/client' +import { Route as LogoutRouteImport } from './routes/logout' import { Route as AuthenticatedAccountRouteImport } from './routes/_authenticated/account' import { Route as ApiAuthCallbackRouteImport } from './routes/api/auth/callback' -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const AuthenticatedRoute = AuthenticatedRouteImport.update({ + id: '/_authenticated', getParentRoute: () => rootRouteImport, } as any) const ClientRoute = ClientRouteImport.update({ @@ -26,13 +30,9 @@ const ClientRoute = ClientRouteImport.update({ path: '/client', getParentRoute: () => rootRouteImport, } as any) -const AuthenticatedRoute = AuthenticatedRouteImport.update({ - id: '/_authenticated', - getParentRoute: () => rootRouteImport, -} as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LogoutRoute = LogoutRouteImport.update({ + id: '/logout', + path: '/logout', getParentRoute: () => rootRouteImport, } as any) const AuthenticatedAccountRoute = AuthenticatedAccountRouteImport.update({ @@ -94,18 +94,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport - parentRoute: typeof rootRouteImport - } - '/client': { - id: '/client' - path: '/client' - fullPath: '/client' - preLoaderRoute: typeof ClientRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_authenticated': { @@ -115,11 +108,18 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthenticatedRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/client': { + id: '/client' + path: '/client' + fullPath: '/client' + preLoaderRoute: typeof ClientRouteImport + parentRoute: typeof rootRouteImport + } + '/logout': { + id: '/logout' + path: '/logout' + fullPath: '/logout' + preLoaderRoute: typeof LogoutRouteImport parentRoute: typeof rootRouteImport } '/_authenticated/account': { diff --git a/examples/react/view-transitions/package.json b/examples/react/view-transitions/package.json index 4170f718e9..0be3c60e8f 100644 --- a/examples/react/view-transitions/package.json +++ b/examples/react/view-transitions/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", @@ -23,7 +23,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/view-transitions/src/routeTree.gen.ts b/examples/react/view-transitions/src/routeTree.gen.ts index 20ee76a1a5..8982fca68f 100644 --- a/examples/react/view-transitions/src/routeTree.gen.ts +++ b/examples/react/view-transitions/src/routeTree.gen.ts @@ -9,16 +9,16 @@ // 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 HowItWorksRouteImport } from './routes/how-it-works' -import { Route as ExploreRouteImport } from './routes/explore' -import { Route as PostsRouteRouteImport } from './routes/posts.route' import { Route as IndexRouteImport } from './routes/index' +import { Route as ExploreRouteImport } from './routes/explore' +import { Route as HowItWorksRouteImport } from './routes/how-it-works' +import { Route as PostsRouteRouteImport } from './routes/posts.route' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -const HowItWorksRoute = HowItWorksRouteImport.update({ - id: '/how-it-works', - path: '/how-it-works', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const ExploreRoute = ExploreRouteImport.update({ @@ -26,16 +26,16 @@ const ExploreRoute = ExploreRouteImport.update({ path: '/explore', getParentRoute: () => rootRouteImport, } as any) +const HowItWorksRoute = HowItWorksRouteImport.update({ + id: '/how-it-works', + path: '/how-it-works', + getParentRoute: () => rootRouteImport, +} as any) const PostsRouteRoute = PostsRouteRouteImport.update({ id: '/posts', path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -101,11 +101,11 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/how-it-works': { - id: '/how-it-works' - path: '/how-it-works' - fullPath: '/how-it-works' - preLoaderRoute: typeof HowItWorksRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/explore': { @@ -115,6 +115,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ExploreRouteImport parentRoute: typeof rootRouteImport } + '/how-it-works': { + id: '/how-it-works' + path: '/how-it-works' + fullPath: '/how-it-works' + preLoaderRoute: typeof HowItWorksRouteImport + parentRoute: typeof rootRouteImport + } '/posts': { id: '/posts' path: '/posts' @@ -122,13 +129,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/posts/': { id: '/posts/' path: '/' diff --git a/examples/react/view-transitions/src/routes/posts.route.tsx b/examples/react/view-transitions/src/routes/posts.route.tsx index c63dc78ff2..4612ed3d5d 100644 --- a/examples/react/view-transitions/src/routes/posts.route.tsx +++ b/examples/react/view-transitions/src/routes/posts.route.tsx @@ -1,5 +1,10 @@ import * as React from 'react' -import { Link, Outlet, createFileRoute } from '@tanstack/react-router' +import { + Link, + Outlet, + createFileRoute, + useRouter, +} from '@tanstack/react-router' import { fetchPosts } from '../posts' export const Route = createFileRoute('/posts')({ @@ -9,6 +14,7 @@ export const Route = createFileRoute('/posts')({ function PostsLayoutComponent() { const posts = Route.useLoaderData() + const router = useRouter() return (
@@ -24,8 +30,30 @@ function PostsLayoutComponent() { }} className="block py-1 text-blue-600 hover:opacity-75" activeProps={{ className: 'font-bold underline' }} - // see styles.css for 'warp' transition - viewTransition={{ types: ['warp'] }} + // see styles.css for 'warp' and 'warp-backwards' transition + viewTransition={{ + types: ({ fromLocation, toLocation }) => { + const fromRoute = router + .matchRoutes(fromLocation?.pathname ?? '/') + .find((entry) => entry.routeId === '/posts/$postId') + const toRoute = router + .matchRoutes(toLocation?.pathname ?? '/') + .find((entry) => entry.routeId === '/posts/$postId') + + const fromIndex = Number(fromRoute?.params.postId) + const toIndex = Number(toRoute?.params.postId) + + if ( + Number.isNaN(fromIndex) || + Number.isNaN(toIndex) || + fromIndex === toIndex + ) { + return false // no transition + } + + return fromIndex > toIndex ? ['warp-backwards'] : ['warp'] + }, + }} >
{post.title.substring(0, 20)}
diff --git a/examples/react/view-transitions/src/styles.css b/examples/react/view-transitions/src/styles.css index b51e6e1244..502642b383 100644 --- a/examples/react/view-transitions/src/styles.css +++ b/examples/react/view-transitions/src/styles.css @@ -87,6 +87,16 @@ html:active-view-transition-type(warp) { } } +html:active-view-transition-type(warp-backwards) { + &::view-transition-old(post) { + animation: 400ms ease-out both warp-out-backwards; + } + + &::view-transition-new(post) { + animation: 400ms ease-out both warp-in-backwards; + } +} + @keyframes warp-out { from { opacity: 1; @@ -112,3 +122,29 @@ html:active-view-transition-type(warp) { transform: scale(1) rotate(0deg); } } + +@keyframes warp-in-backwards { + from { + opacity: 0; + filter: blur(15px) brightness(1.8); + transform: scale(0.9) rotate(45deg); + } + to { + opacity: 1; + filter: blur(0) brightness(1); + transform: scale(1) rotate(0deg); + } +} + +@keyframes warp-out-backwards { + from { + opacity: 1; + filter: blur(0) brightness(1); + transform: scale(1) rotate(0deg); + } + to { + opacity: 0; + filter: blur(15px) brightness(1.8); + transform: scale(1.1) rotate(-90deg); + } +} diff --git a/examples/react/with-framer-motion/package.json b/examples/react/with-framer-motion/package.json index b690bb1c9a..c606070dfb 100644 --- a/examples/react/with-framer-motion/package.json +++ b/examples/react/with-framer-motion/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", "framer-motion": "^11.18.2", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -23,7 +23,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/react/with-trpc-react-query/package.json b/examples/react/with-trpc-react-query/package.json index 8831056e3d..11df7bf03b 100644 --- a/examples/react/with-trpc-react-query/package.json +++ b/examples/react/with-trpc-react-query/package.json @@ -11,11 +11,11 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-query": "^5.90.0", + "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "@trpc/client": "^11.4.3", "@trpc/server": "^11.4.3", "@trpc/tanstack-react-query": "^11.4.3", diff --git a/examples/react/with-trpc-react-query/src/routeTree.gen.ts b/examples/react/with-trpc-react-query/src/routeTree.gen.ts index b407b58e4c..548a4b9e88 100644 --- a/examples/react/with-trpc-react-query/src/routeTree.gen.ts +++ b/examples/react/with-trpc-react-query/src/routeTree.gen.ts @@ -9,23 +9,23 @@ // 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 DashboardRouteImport } from './routes/dashboard' import { Route as IndexRouteImport } from './routes/index' +import { Route as DashboardRouteImport } from './routes/dashboard' import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' import { Route as DashboardPostsRouteImport } from './routes/dashboard.posts' import { Route as DashboardPostsIndexRouteImport } from './routes/dashboard.posts.index' import { Route as DashboardPostsPostIdRouteImport } from './routes/dashboard.posts.$postId' -const DashboardRoute = DashboardRouteImport.update({ - id: '/dashboard', - path: '/dashboard', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const DashboardRoute = DashboardRouteImport.update({ + id: '/dashboard', + path: '/dashboard', + getParentRoute: () => rootRouteImport, +} as any) const DashboardIndexRoute = DashboardIndexRouteImport.update({ id: '/', path: '/', @@ -98,13 +98,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/dashboard': { - id: '/dashboard' - path: '/dashboard' - fullPath: '/dashboard' - preLoaderRoute: typeof DashboardRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -112,6 +105,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/dashboard': { + id: '/dashboard' + path: '/dashboard' + fullPath: '/dashboard' + preLoaderRoute: typeof DashboardRouteImport + parentRoute: typeof rootRouteImport + } '/dashboard/': { id: '/dashboard/' path: '/' diff --git a/examples/react/with-trpc/package.json b/examples/react/with-trpc/package.json index 6ec641420c..5612419cae 100644 --- a/examples/react/with-trpc/package.json +++ b/examples/react/with-trpc/package.json @@ -11,9 +11,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/react-router": "^1.170.18", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/react-router": "^1.170.46", + "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "@trpc/client": "^11.4.3", "@trpc/server": "^11.4.3", "express": "^5.2.1", diff --git a/examples/react/with-trpc/src/routeTree.gen.ts b/examples/react/with-trpc/src/routeTree.gen.ts index b407b58e4c..548a4b9e88 100644 --- a/examples/react/with-trpc/src/routeTree.gen.ts +++ b/examples/react/with-trpc/src/routeTree.gen.ts @@ -9,23 +9,23 @@ // 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 DashboardRouteImport } from './routes/dashboard' import { Route as IndexRouteImport } from './routes/index' +import { Route as DashboardRouteImport } from './routes/dashboard' import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' import { Route as DashboardPostsRouteImport } from './routes/dashboard.posts' import { Route as DashboardPostsIndexRouteImport } from './routes/dashboard.posts.index' import { Route as DashboardPostsPostIdRouteImport } from './routes/dashboard.posts.$postId' -const DashboardRoute = DashboardRouteImport.update({ - id: '/dashboard', - path: '/dashboard', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const DashboardRoute = DashboardRouteImport.update({ + id: '/dashboard', + path: '/dashboard', + getParentRoute: () => rootRouteImport, +} as any) const DashboardIndexRoute = DashboardIndexRouteImport.update({ id: '/', path: '/', @@ -98,13 +98,6 @@ export interface RootRouteChildren { declare module '@tanstack/react-router' { interface FileRoutesByPath { - '/dashboard': { - id: '/dashboard' - path: '/dashboard' - fullPath: '/dashboard' - preLoaderRoute: typeof DashboardRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -112,6 +105,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/dashboard': { + id: '/dashboard' + path: '/dashboard' + fullPath: '/dashboard' + preLoaderRoute: typeof DashboardRouteImport + parentRoute: typeof rootRouteImport + } '/dashboard/': { id: '/dashboard/' path: '/' diff --git a/examples/solid/authenticated-routes-firebase/package.json b/examples/solid/authenticated-routes-firebase/package.json index 0ed139ce36..110b4d2621 100644 --- a/examples/solid/authenticated-routes-firebase/package.json +++ b/examples/solid/authenticated-routes-firebase/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.168.20", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "firebase": "^11.4.0", "redaxios": "^0.5.1", "simple-icons": "^14.9.0", @@ -21,7 +21,8 @@ "zod": "^4.4.3" }, "devDependencies": { - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/authenticated-routes-firebase/src/auth.tsx b/examples/solid/authenticated-routes-firebase/src/auth.tsx index 84f1df8c99..97337889b7 100644 --- a/examples/solid/authenticated-routes-firebase/src/auth.tsx +++ b/examples/solid/authenticated-routes-firebase/src/auth.tsx @@ -1,7 +1,6 @@ import * as Solid from 'solid-js' import { onAuthStateChanged, signInWithPopup, signOut } from 'firebase/auth' -import { flushSync } from 'react-dom' import { auth } from './firebase/config' import type { AuthProvider, User } from 'firebase/auth' @@ -22,7 +21,7 @@ export function AuthContextProvider(props: { children: Solid.JSX.Element }) { Solid.createEffect(() => { const unsubscribe = onAuthStateChanged(auth, (user) => { - flushSync(() => { + Solid.batch(() => { setUser(user) setIsInitialLoading(false) }) @@ -39,7 +38,7 @@ export function AuthContextProvider(props: { children: Solid.JSX.Element }) { const login = async (provider: AuthProvider) => { const result = await signInWithPopup(auth, provider) - flushSync(() => { + Solid.batch(() => { setUser(result.user) setIsInitialLoading(false) }) diff --git a/examples/solid/authenticated-routes-firebase/src/routeTree.gen.ts b/examples/solid/authenticated-routes-firebase/src/routeTree.gen.ts index ff0ae58ad7..4b98258aea 100644 --- a/examples/solid/authenticated-routes-firebase/src/routeTree.gen.ts +++ b/examples/solid/authenticated-routes-firebase/src/routeTree.gen.ts @@ -9,38 +9,38 @@ // 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 LoginRouteImport } from './routes/login' -import { Route as AuthRouteImport } from './routes/_auth' import { Route as IndexRouteImport } from './routes/index' -import { Route as AuthInvoicesRouteImport } from './routes/_auth.invoices' +import { Route as AuthRouteImport } from './routes/_auth' +import { Route as LoginRouteImport } from './routes/login' import { Route as AuthDashboardRouteImport } from './routes/_auth.dashboard' +import { Route as AuthInvoicesRouteImport } from './routes/_auth.invoices' import { Route as AuthInvoicesIndexRouteImport } from './routes/_auth.invoices.index' import { Route as AuthInvoicesInvoiceIdRouteImport } from './routes/_auth.invoices.$invoiceId' -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthRoute = AuthRouteImport.update({ id: '/_auth', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) -const AuthInvoicesRoute = AuthInvoicesRouteImport.update({ - id: '/invoices', - path: '/invoices', - getParentRoute: () => AuthRoute, -} as any) const AuthDashboardRoute = AuthDashboardRouteImport.update({ id: '/dashboard', path: '/dashboard', getParentRoute: () => AuthRoute, } as any) +const AuthInvoicesRoute = AuthInvoicesRouteImport.update({ + id: '/invoices', + path: '/invoices', + getParentRoute: () => AuthRoute, +} as any) const AuthInvoicesIndexRoute = AuthInvoicesIndexRouteImport.update({ id: '/', path: '/', @@ -107,11 +107,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_auth': { @@ -121,20 +121,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AuthRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/_auth/invoices': { - id: '/_auth/invoices' - path: '/invoices' - fullPath: '/invoices' - preLoaderRoute: typeof AuthInvoicesRouteImport - parentRoute: typeof AuthRoute - } '/_auth/dashboard': { id: '/_auth/dashboard' path: '/dashboard' @@ -142,6 +135,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AuthDashboardRouteImport parentRoute: typeof AuthRoute } + '/_auth/invoices': { + id: '/_auth/invoices' + path: '/invoices' + fullPath: '/invoices' + preLoaderRoute: typeof AuthInvoicesRouteImport + parentRoute: typeof AuthRoute + } '/_auth/invoices/': { id: '/_auth/invoices/' path: '/' diff --git a/examples/solid/authenticated-routes/package.json b/examples/solid/authenticated-routes/package.json index 979f85c8a9..ea7d05c902 100644 --- a/examples/solid/authenticated-routes/package.json +++ b/examples/solid/authenticated-routes/package.json @@ -10,16 +10,17 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.168.20", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, "devDependencies": { - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/authenticated-routes/src/routeTree.gen.ts b/examples/solid/authenticated-routes/src/routeTree.gen.ts index ff0ae58ad7..4b98258aea 100644 --- a/examples/solid/authenticated-routes/src/routeTree.gen.ts +++ b/examples/solid/authenticated-routes/src/routeTree.gen.ts @@ -9,38 +9,38 @@ // 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 LoginRouteImport } from './routes/login' -import { Route as AuthRouteImport } from './routes/_auth' import { Route as IndexRouteImport } from './routes/index' -import { Route as AuthInvoicesRouteImport } from './routes/_auth.invoices' +import { Route as AuthRouteImport } from './routes/_auth' +import { Route as LoginRouteImport } from './routes/login' import { Route as AuthDashboardRouteImport } from './routes/_auth.dashboard' +import { Route as AuthInvoicesRouteImport } from './routes/_auth.invoices' import { Route as AuthInvoicesIndexRouteImport } from './routes/_auth.invoices.index' import { Route as AuthInvoicesInvoiceIdRouteImport } from './routes/_auth.invoices.$invoiceId' -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthRoute = AuthRouteImport.update({ id: '/_auth', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) -const AuthInvoicesRoute = AuthInvoicesRouteImport.update({ - id: '/invoices', - path: '/invoices', - getParentRoute: () => AuthRoute, -} as any) const AuthDashboardRoute = AuthDashboardRouteImport.update({ id: '/dashboard', path: '/dashboard', getParentRoute: () => AuthRoute, } as any) +const AuthInvoicesRoute = AuthInvoicesRouteImport.update({ + id: '/invoices', + path: '/invoices', + getParentRoute: () => AuthRoute, +} as any) const AuthInvoicesIndexRoute = AuthInvoicesIndexRouteImport.update({ id: '/', path: '/', @@ -107,11 +107,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_auth': { @@ -121,20 +121,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AuthRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/_auth/invoices': { - id: '/_auth/invoices' - path: '/invoices' - fullPath: '/invoices' - preLoaderRoute: typeof AuthInvoicesRouteImport - parentRoute: typeof AuthRoute - } '/_auth/dashboard': { id: '/_auth/dashboard' path: '/dashboard' @@ -142,6 +135,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AuthDashboardRouteImport parentRoute: typeof AuthRoute } + '/_auth/invoices': { + id: '/_auth/invoices' + path: '/invoices' + fullPath: '/invoices' + preLoaderRoute: typeof AuthInvoicesRouteImport + parentRoute: typeof AuthRoute + } '/_auth/invoices/': { id: '/_auth/invoices/' path: '/' diff --git a/examples/solid/basic-default-search-params/package.json b/examples/solid/basic-default-search-params/package.json index a41e918fe4..830df7b9cf 100644 --- a/examples/solid/basic-default-search-params/package.json +++ b/examples/solid/basic-default-search-params/package.json @@ -11,15 +11,16 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, "devDependencies": { - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/basic-devtools-panel/package.json b/examples/solid/basic-devtools-panel/package.json index fcc8d093ed..e7d608f5fe 100644 --- a/examples/solid/basic-devtools-panel/package.json +++ b/examples/solid/basic-devtools-panel/package.json @@ -10,14 +10,15 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, "devDependencies": { - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/basic-file-based/package.json b/examples/solid/basic-file-based/package.json index b032501a85..867118382e 100644 --- a/examples/solid/basic-file-based/package.json +++ b/examples/solid/basic-file-based/package.json @@ -10,16 +10,17 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, "devDependencies": { - "@tanstack/router-plugin": "^1.168.20", - "typescript": "^6.0.2", + "@tanstack/router-plugin": "^1.169.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/basic-file-based/src/routeTree.gen.ts b/examples/solid/basic-file-based/src/routeTree.gen.ts index bde5d68567..5942acc907 100644 --- a/examples/solid/basic-file-based/src/routeTree.gen.ts +++ b/examples/solid/basic-file-based/src/routeTree.gen.ts @@ -9,29 +9,34 @@ // 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 PostsRouteImport } from './routes/posts' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as IndexRouteImport } from './routes/index' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, + } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -42,10 +47,11 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRoute, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -53,12 +59,6 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -117,11 +117,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout': { @@ -131,13 +131,20 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute + } '/posts/': { id: '/posts/' path: '/' @@ -152,12 +159,12 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -166,13 +173,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } } } diff --git a/examples/solid/basic-non-nested-devtools/package.json b/examples/solid/basic-non-nested-devtools/package.json index 64bf1df09f..c8e00ee43e 100644 --- a/examples/solid/basic-non-nested-devtools/package.json +++ b/examples/solid/basic-non-nested-devtools/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" @@ -19,7 +19,8 @@ "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/basic-solid-query-file-based/package.json b/examples/solid/basic-solid-query-file-based/package.json index e70255d71e..fdb5f05f52 100644 --- a/examples/solid/basic-solid-query-file-based/package.json +++ b/examples/solid/basic-solid-query-file-based/package.json @@ -13,16 +13,17 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, "devDependencies": { - "@tanstack/router-plugin": "^1.168.20", - "typescript": "^6.0.2", + "@tanstack/router-plugin": "^1.169.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/basic-solid-query-file-based/src/routeTree.gen.ts b/examples/solid/basic-solid-query-file-based/src/routeTree.gen.ts index bde5d68567..5942acc907 100644 --- a/examples/solid/basic-solid-query-file-based/src/routeTree.gen.ts +++ b/examples/solid/basic-solid-query-file-based/src/routeTree.gen.ts @@ -9,29 +9,34 @@ // 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 PostsRouteImport } from './routes/posts' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as IndexRouteImport } from './routes/index' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, + } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -42,10 +47,11 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRoute, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -53,12 +59,6 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -117,11 +117,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout': { @@ -131,13 +131,20 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute + } '/posts/': { id: '/posts/' path: '/' @@ -152,12 +159,12 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -166,13 +173,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } } } diff --git a/examples/solid/basic-solid-query/package.json b/examples/solid/basic-solid-query/package.json index a3aaeb30da..7b132b11a1 100644 --- a/examples/solid/basic-solid-query/package.json +++ b/examples/solid/basic-solid-query/package.json @@ -12,15 +12,16 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, "devDependencies": { - "@tanstack/router-plugin": "^1.168.20", - "typescript": "^6.0.2", + "@tanstack/router-plugin": "^1.169.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/basic-ssr-file-based/package.json b/examples/solid/basic-ssr-file-based/package.json index 6a298c782e..e3699970a9 100644 --- a/examples/solid/basic-ssr-file-based/package.json +++ b/examples/solid/basic-ssr-file-based/package.json @@ -11,8 +11,8 @@ "debug": "node --inspect-brk server" }, "dependencies": { - "@tanstack/solid-router": "^1.170.18", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/router-plugin": "^1.169.0", "compression": "^1.8.0", "express": "^5.2.1", "get-port": "^7.1.0", @@ -20,10 +20,11 @@ "solid-js": "^1.9.10" }, "devDependencies": { - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router-devtools": "^1.167.3", "@types/express": "^5.0.6", "vite-plugin-solid": "^2.11.11", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/solid/basic-ssr-file-based/src/routeTree.gen.ts b/examples/solid/basic-ssr-file-based/src/routeTree.gen.ts index 26eb09e67f..fc6a3e4377 100644 --- a/examples/solid/basic-ssr-file-based/src/routeTree.gen.ts +++ b/examples/solid/basic-ssr-file-based/src/routeTree.gen.ts @@ -9,12 +9,17 @@ // 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 ErrorRouteImport } from './routes/error' import { Route as PostsRouteRouteImport } from './routes/posts/route' -import { Route as IndexRouteImport } from './routes/index' import { Route as PostsIndexRouteImport } from './routes/posts/index' import { Route as PostsPostIdRouteImport } from './routes/posts/$postId' +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const ErrorRoute = ErrorRouteImport.update({ id: '/error', path: '/error', @@ -25,11 +30,6 @@ const PostsRouteRoute = PostsRouteRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -78,6 +78,13 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/error': { id: '/error' path: '/error' @@ -92,13 +99,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/posts/': { id: '/posts/' path: '/' diff --git a/examples/solid/basic-ssr-streaming-file-based/package.json b/examples/solid/basic-ssr-streaming-file-based/package.json index 7e8e90bb09..92367442fc 100644 --- a/examples/solid/basic-ssr-streaming-file-based/package.json +++ b/examples/solid/basic-ssr-streaming-file-based/package.json @@ -12,8 +12,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "compression": "^1.8.0", "express": "^5.2.1", "get-port": "^7.1.0", @@ -24,9 +24,10 @@ "zod": "^4.4.3" }, "devDependencies": { - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/router-plugin": "^1.169.0", "@types/express": "^5.0.6", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/basic-ssr-streaming-file-based/src/routeTree.gen.ts b/examples/solid/basic-ssr-streaming-file-based/src/routeTree.gen.ts index be2ed5b18d..0161f550f0 100644 --- a/examples/solid/basic-ssr-streaming-file-based/src/routeTree.gen.ts +++ b/examples/solid/basic-ssr-streaming-file-based/src/routeTree.gen.ts @@ -9,19 +9,23 @@ // 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 PostsRouteImport } from './routes/posts' -import { Route as CounterRouteImport } from './routes/counter' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as IndexRouteImport } from './routes/index' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as CounterRouteImport } from './routes/counter' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const CounterRoute = CounterRouteImport.update({ @@ -29,15 +33,16 @@ const CounterRoute = CounterRouteImport.update({ path: '/counter', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', - getParentRoute: () => rootRouteImport, -} as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, + } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -48,10 +53,11 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRoute, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, +const PathlessLayoutNestedLayoutRouteARoute = + PathlessLayoutNestedLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) const PathlessLayoutNestedLayoutRouteBRoute = PathlessLayoutNestedLayoutRouteBRouteImport.update({ @@ -59,12 +65,6 @@ const PathlessLayoutNestedLayoutRouteBRoute = path: '/route-b', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) -const PathlessLayoutNestedLayoutRouteARoute = - PathlessLayoutNestedLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -129,18 +129,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/counter': { - id: '/counter' - path: '/counter' - fullPath: '/counter' - preLoaderRoute: typeof CounterRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout': { @@ -150,13 +143,27 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/counter': { + id: '/counter' + path: '/counter' + fullPath: '/counter' + preLoaderRoute: typeof CounterRouteImport parentRoute: typeof rootRouteImport } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/_pathlessLayout/_nested-layout': { + id: '/_pathlessLayout/_nested-layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport + parentRoute: typeof PathlessLayoutRoute + } '/posts/': { id: '/posts/' path: '/' @@ -171,12 +178,12 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_pathlessLayout/_nested-layout': { - id: '/_pathlessLayout/_nested-layout' - path: '' - fullPath: '/' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport - parentRoute: typeof PathlessLayoutRoute + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -185,13 +192,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute - } } } diff --git a/examples/solid/basic-virtual-file-based/package.json b/examples/solid/basic-virtual-file-based/package.json index 461b72f958..801b452192 100644 --- a/examples/solid/basic-virtual-file-based/package.json +++ b/examples/solid/basic-virtual-file-based/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.168.20", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "@tanstack/virtual-file-routes": "^1.162.0", "redaxios": "^0.5.1", "solid-js": "^1.9.10", @@ -20,7 +20,8 @@ "zod": "^4.4.3" }, "devDependencies": { - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/basic-virtual-file-based/src/routeTree.gen.ts b/examples/solid/basic-virtual-file-based/src/routeTree.gen.ts index cb96aee7ba..c41eda86bf 100644 --- a/examples/solid/basic-virtual-file-based/src/routeTree.gen.ts +++ b/examples/solid/basic-virtual-file-based/src/routeTree.gen.ts @@ -9,77 +9,77 @@ // 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 postsPostsRouteImport } from './routes/posts/posts' -import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' import { Route as homeRouteImport } from './routes/home' -import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' +import { Route as layoutFirstLayoutRouteImport } from './routes/layout/first-layout' +import { Route as postsPostsRouteImport } from './routes/posts/posts' import { Route as layoutSecondLayoutRouteImport } from './routes/layout/second-layout' -import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' import { Route as ClassicHelloRouteRouteImport } from './routes/file-based-subtree/hello/route' +import { Route as postsPostsHomeRouteImport } from './routes/posts/posts-home' +import { Route as postsPostsDetailRouteImport } from './routes/posts/posts-detail' import { Route as ClassicHelloIndexRouteImport } from './routes/file-based-subtree/hello/index' -import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' import { Route as ClassicHelloUniverseRouteImport } from './routes/file-based-subtree/hello/universe' -import { Route as bRouteImport } from './routes/b' +import { Route as ClassicHelloWorldRouteImport } from './routes/file-based-subtree/hello/world' import { Route as aRouteImport } from './routes/a' +import { Route as bRouteImport } from './routes/b' -const postsPostsRoute = postsPostsRouteImport.update({ - id: '/posts', - path: '/posts', +const homeRoute = homeRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const layoutFirstLayoutRoute = layoutFirstLayoutRouteImport.update({ id: '/_first', getParentRoute: () => rootRouteImport, } as any) -const homeRoute = homeRouteImport.update({ - id: '/', - path: '/', +const postsPostsRoute = postsPostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const postsPostsDetailRoute = postsPostsDetailRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => postsPostsRoute, -} as any) const layoutSecondLayoutRoute = layoutSecondLayoutRouteImport.update({ id: '/_second-layout', getParentRoute: () => layoutFirstLayoutRoute, } as any) -const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => postsPostsRoute, -} as any) const ClassicHelloRouteRoute = ClassicHelloRouteRouteImport.update({ id: '/classic/hello', path: '/classic/hello', getParentRoute: () => rootRouteImport, } as any) +const postsPostsHomeRoute = postsPostsHomeRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => postsPostsRoute, +} as any) +const postsPostsDetailRoute = postsPostsDetailRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => postsPostsRoute, +} as any) const ClassicHelloIndexRoute = ClassicHelloIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ - id: '/world', - path: '/world', - getParentRoute: () => ClassicHelloRouteRoute, -} as any) const ClassicHelloUniverseRoute = ClassicHelloUniverseRouteImport.update({ id: '/universe', path: '/universe', getParentRoute: () => ClassicHelloRouteRoute, } as any) -const bRoute = bRouteImport.update({ - id: '/route-without-file/layout-b', - path: '/route-without-file/layout-b', - getParentRoute: () => layoutSecondLayoutRoute, +const ClassicHelloWorldRoute = ClassicHelloWorldRouteImport.update({ + id: '/world', + path: '/world', + getParentRoute: () => ClassicHelloRouteRoute, } as any) const aRoute = aRouteImport.update({ id: '/route-without-file/layout-a', path: '/route-without-file/layout-a', getParentRoute: () => layoutSecondLayoutRoute, } as any) +const bRoute = bRouteImport.update({ + id: '/route-without-file/layout-b', + path: '/route-without-file/layout-b', + getParentRoute: () => layoutSecondLayoutRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof homeRoute @@ -166,11 +166,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof postsPostsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof homeRouteImport parentRoute: typeof rootRouteImport } '/_first': { @@ -180,20 +180,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof layoutFirstLayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof homeRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof postsPostsRouteImport parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof postsPostsDetailRouteImport - parentRoute: typeof postsPostsRoute - } '/_first/_second-layout': { id: '/_first/_second-layout' path: '' @@ -201,13 +194,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof layoutSecondLayoutRouteImport parentRoute: typeof layoutFirstLayoutRoute } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof postsPostsHomeRouteImport - parentRoute: typeof postsPostsRoute - } '/classic/hello': { id: '/classic/hello' path: '/classic/hello' @@ -215,6 +201,20 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ClassicHelloRouteRouteImport parentRoute: typeof rootRouteImport } + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof postsPostsHomeRouteImport + parentRoute: typeof postsPostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof postsPostsDetailRouteImport + parentRoute: typeof postsPostsRoute + } '/classic/hello/': { id: '/classic/hello/' path: '/' @@ -222,13 +222,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ClassicHelloIndexRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/classic/hello/world': { - id: '/classic/hello/world' - path: '/world' - fullPath: '/classic/hello/world' - preLoaderRoute: typeof ClassicHelloWorldRouteImport - parentRoute: typeof ClassicHelloRouteRoute - } '/classic/hello/universe': { id: '/classic/hello/universe' path: '/universe' @@ -236,12 +229,12 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ClassicHelloUniverseRouteImport parentRoute: typeof ClassicHelloRouteRoute } - '/_first/_second-layout/route-without-file/layout-b': { - id: '/_first/_second-layout/route-without-file/layout-b' - path: '/route-without-file/layout-b' - fullPath: '/route-without-file/layout-b' - preLoaderRoute: typeof bRouteImport - parentRoute: typeof layoutSecondLayoutRoute + '/classic/hello/world': { + id: '/classic/hello/world' + path: '/world' + fullPath: '/classic/hello/world' + preLoaderRoute: typeof ClassicHelloWorldRouteImport + parentRoute: typeof ClassicHelloRouteRoute } '/_first/_second-layout/route-without-file/layout-a': { id: '/_first/_second-layout/route-without-file/layout-a' @@ -250,6 +243,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof aRouteImport parentRoute: typeof layoutSecondLayoutRoute } + '/_first/_second-layout/route-without-file/layout-b': { + id: '/_first/_second-layout/route-without-file/layout-b' + path: '/route-without-file/layout-b' + fullPath: '/route-without-file/layout-b' + preLoaderRoute: typeof bRouteImport + parentRoute: typeof layoutSecondLayoutRoute + } } } diff --git a/examples/solid/basic-virtual-inside-file-based/package.json b/examples/solid/basic-virtual-inside-file-based/package.json index 449c620d69..a9cc6360a5 100644 --- a/examples/solid/basic-virtual-inside-file-based/package.json +++ b/examples/solid/basic-virtual-inside-file-based/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.168.20", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "@tanstack/virtual-file-routes": "^1.162.0", "redaxios": "^0.5.1", "solid-js": "^1.9.10", @@ -20,7 +20,8 @@ "zod": "^4.4.3" }, "devDependencies": { - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/basic-virtual-inside-file-based/src/routeTree.gen.ts b/examples/solid/basic-virtual-inside-file-based/src/routeTree.gen.ts index 037dac78a3..6117330aa3 100644 --- a/examples/solid/basic-virtual-inside-file-based/src/routeTree.gen.ts +++ b/examples/solid/basic-virtual-inside-file-based/src/routeTree.gen.ts @@ -9,36 +9,31 @@ // 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 PostsRouteImport } from './routes/posts' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as IndexRouteImport } from './routes/index' -import { Route as PostsDetailsRouteImport } from './routes/posts/details' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as PostsRouteImport } from './routes/posts' import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' import { Route as PostsHomeRouteImport } from './routes/posts/home' -import { Route as PostsLetsGoIndexRouteImport } from './routes/posts/lets-go/index' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as PostsDetailsRouteImport } from './routes/posts/details' import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as PostsLetsGoIndexRouteImport } from './routes/posts/lets-go/index' import { Route as PostsLetsGoDeeperHomeRouteImport } from './routes/posts/lets-go/deeper/home' -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const LayoutRoute = LayoutRouteImport.update({ id: '/_layout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const PostsDetailsRoute = PostsDetailsRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) const LayoutLayout2Route = LayoutLayout2RouteImport.update({ id: '/_layout-2', getParentRoute: () => LayoutRoute, @@ -48,20 +43,25 @@ const PostsHomeRoute = PostsHomeRouteImport.update({ path: '/', getParentRoute: () => PostsRoute, } as any) -const PostsLetsGoIndexRoute = PostsLetsGoIndexRouteImport.update({ - id: '/inception/', - path: '/inception/', +const PostsDetailsRoute = PostsDetailsRouteImport.update({ + id: '/$postId', + path: '/$postId', getParentRoute: () => PostsRoute, } as any) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, +} as any) const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ id: '/layout-b', path: '/layout-b', getParentRoute: () => LayoutLayout2Route, } as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const PostsLetsGoIndexRoute = PostsLetsGoIndexRouteImport.update({ + id: '/inception/', + path: '/inception/', + getParentRoute: () => PostsRoute, } as any) const PostsLetsGoDeeperHomeRoute = PostsLetsGoDeeperHomeRouteImport.update({ id: '/inception/deeper/', @@ -143,11 +143,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -157,20 +157,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsDetailsRouteImport - parentRoute: typeof PostsRoute - } '/_layout/_layout-2': { id: '/_layout/_layout-2' path: '' @@ -185,13 +178,20 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostsHomeRouteImport parentRoute: typeof PostsRoute } - '/posts/inception/': { - id: '/posts/inception/' - path: '/inception' - fullPath: '/posts/inception/' - preLoaderRoute: typeof PostsLetsGoIndexRouteImport + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsDetailsRouteImport parentRoute: typeof PostsRoute } + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route + } '/_layout/_layout-2/layout-b': { id: '/_layout/_layout-2/layout-b' path: '/layout-b' @@ -199,12 +199,12 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport parentRoute: typeof LayoutLayout2Route } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/posts/inception/': { + id: '/posts/inception/' + path: '/inception' + fullPath: '/posts/inception/' + preLoaderRoute: typeof PostsLetsGoIndexRouteImport + parentRoute: typeof PostsRoute } '/posts/inception/deeper/': { id: '/posts/inception/deeper/' diff --git a/examples/solid/basic/package.json b/examples/solid/basic/package.json index f13e5f3afb..95ec804011 100644 --- a/examples/solid/basic/package.json +++ b/examples/solid/basic/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" @@ -19,7 +19,8 @@ "devDependencies": { "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/deferred-data/package.json b/examples/solid/deferred-data/package.json index c9851e71e5..56114afd04 100644 --- a/examples/solid/deferred-data/package.json +++ b/examples/solid/deferred-data/package.json @@ -10,15 +10,16 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, "devDependencies": { - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/i18n-paraglide/package.json b/examples/solid/i18n-paraglide/package.json index a6c4136a40..6493a3c7c8 100644 --- a/examples/solid/i18n-paraglide/package.json +++ b/examples/solid/i18n-paraglide/package.json @@ -11,16 +11,28 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/router-plugin": "^1.169.0", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, "devDependencies": { "@types/node": "^22.18.6", "vite-plugin-solid": "^2.11.11", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "@inlang/paraglide-js": "^2.4.0" + }, + "nx": { + "targets": { + "build": { + "outputs": [ + "...", + "{projectRoot}/src/paraglide", + "{projectRoot}/project.inlang/cache" + ] + } + } } } diff --git a/examples/solid/i18n-paraglide/src/routeTree.gen.ts b/examples/solid/i18n-paraglide/src/routeTree.gen.ts index 333a815c38..98df1e83d8 100644 --- a/examples/solid/i18n-paraglide/src/routeTree.gen.ts +++ b/examples/solid/i18n-paraglide/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/kitchen-sink-file-based/package.json b/examples/solid/kitchen-sink-file-based/package.json index d38afe3bb5..8cd73e38ff 100644 --- a/examples/solid/kitchen-sink-file-based/package.json +++ b/examples/solid/kitchen-sink-file-based/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "immer": "^10.1.1", "redaxios": "^0.5.1", "solid-js": "^1.9.10", @@ -19,8 +19,9 @@ "zod": "^4.4.3" }, "devDependencies": { - "@tanstack/router-plugin": "^1.168.20", - "typescript": "^6.0.2", + "@tanstack/router-plugin": "^1.169.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/kitchen-sink-file-based/src/routeTree.gen.ts b/examples/solid/kitchen-sink-file-based/src/routeTree.gen.ts index 0c6e04f63d..76bb314a71 100644 --- a/examples/solid/kitchen-sink-file-based/src/routeTree.gen.ts +++ b/examples/solid/kitchen-sink-file-based/src/routeTree.gen.ts @@ -9,81 +9,71 @@ // 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 LoginRouteImport } from './routes/login' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as AuthRouteImport } from './routes/_auth' -import { Route as DashboardRouteRouteImport } from './routes/dashboard.route' import { Route as IndexRouteImport } from './routes/index' -import { Route as ExpensiveIndexRouteImport } from './routes/expensive/index' -import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' -import { Route as PathlessLayoutRouteBRouteImport } from './routes/_pathlessLayout.route-b' -import { Route as PathlessLayoutRouteARouteImport } from './routes/_pathlessLayout.route-a' -import { Route as AuthProfileRouteImport } from './routes/_auth.profile' +import { Route as AuthRouteImport } from './routes/_auth' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as DashboardRouteRouteImport } from './routes/dashboard.route' +import { Route as LoginRouteImport } from './routes/login' import { Route as thisFolderIsNotInTheUrlRouteGroupRouteImport } from './routes/(this-folder-is-not-in-the-url)/route-group' -import { Route as DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as AuthProfileRouteImport } from './routes/_auth.profile' +import { Route as PathlessLayoutRouteARouteImport } from './routes/_pathlessLayout.route-a' +import { Route as PathlessLayoutRouteBRouteImport } from './routes/_pathlessLayout.route-b' +import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' import { Route as DashboardInvoicesRouteRouteImport } from './routes/dashboard.invoices.route' -import { Route as DashboardUsersIndexRouteImport } from './routes/dashboard.users.index' +import { Route as DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as ExpensiveIndexRouteImport } from './routes/expensive/index' import { Route as DashboardInvoicesIndexRouteImport } from './routes/dashboard.invoices.index' -import { Route as DashboardUsersUserRouteImport } from './routes/dashboard.users.user' import { Route as DashboardInvoicesInvoiceIdRouteImport } from './routes/dashboard.invoices.$invoiceId' +import { Route as DashboardUsersIndexRouteImport } from './routes/dashboard.users.index' +import { Route as DashboardUsersUserRouteImport } from './routes/dashboard.users.user' -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthRoute = AuthRouteImport.update({ id: '/_auth', getParentRoute: () => rootRouteImport, } as any) +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', + getParentRoute: () => rootRouteImport, +} as any) const DashboardRouteRoute = DashboardRouteRouteImport.update({ id: '/dashboard', path: '/dashboard', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) -const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ - id: '/expensive/', - path: '/expensive/', - getParentRoute: () => rootRouteImport, -} as any) -const DashboardIndexRoute = DashboardIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardRouteRoute, -} as any) -const PathlessLayoutRouteBRoute = PathlessLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutRoute, -} as any) -const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutRoute, -} as any) -const AuthProfileRoute = AuthProfileRouteImport.update({ - id: '/profile', - path: '/profile', - getParentRoute: () => AuthRoute, -} as any) const thisFolderIsNotInTheUrlRouteGroupRoute = thisFolderIsNotInTheUrlRouteGroupRouteImport.update({ id: '/(this-folder-is-not-in-the-url)/route-group', path: '/route-group', getParentRoute: () => rootRouteImport, } as any) -const DashboardUsersRouteRoute = DashboardUsersRouteRouteImport.update({ - id: '/users', - path: '/users', +const AuthProfileRoute = AuthProfileRouteImport.update({ + id: '/profile', + path: '/profile', + getParentRoute: () => AuthRoute, +} as any) +const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutRoute, +} as any) +const PathlessLayoutRouteBRoute = PathlessLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutRoute, +} as any) +const DashboardIndexRoute = DashboardIndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => DashboardRouteRoute, } as any) const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ @@ -91,27 +81,37 @@ const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ path: '/invoices', getParentRoute: () => DashboardRouteRoute, } as any) -const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardUsersRouteRoute, +const DashboardUsersRouteRoute = DashboardUsersRouteRouteImport.update({ + id: '/users', + path: '/users', + getParentRoute: () => DashboardRouteRoute, +} as any) +const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ + id: '/expensive/', + path: '/expensive/', + getParentRoute: () => rootRouteImport, } as any) const DashboardInvoicesIndexRoute = DashboardInvoicesIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => DashboardInvoicesRouteRoute, } as any) -const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ - id: '/user', - path: '/user', - getParentRoute: () => DashboardUsersRouteRoute, -} as any) const DashboardInvoicesInvoiceIdRoute = DashboardInvoicesInvoiceIdRouteImport.update({ id: '/$invoiceId', path: '/$invoiceId', getParentRoute: () => DashboardInvoicesRouteRoute, } as any) +const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => DashboardUsersRouteRoute, +} as any) +const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ + id: '/user', + path: '/user', + getParentRoute: () => DashboardUsersRouteRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -229,18 +229,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' + '/': { + id: '/' + path: '/' fullPath: '/' - preLoaderRoute: typeof PathlessLayoutRouteImport + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_auth': { @@ -250,6 +243,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AuthRouteImport parentRoute: typeof rootRouteImport } + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof rootRouteImport + } '/dashboard': { id: '/dashboard' path: '/dashboard' @@ -257,48 +257,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DashboardRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/expensive/': { - id: '/expensive/' - path: '/expensive' - fullPath: '/expensive/' - preLoaderRoute: typeof ExpensiveIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/dashboard/': { - id: '/dashboard/' - path: '/' - fullPath: '/dashboard/' - preLoaderRoute: typeof DashboardIndexRouteImport - parentRoute: typeof DashboardRouteRoute - } - '/_pathlessLayout/route-b': { - id: '/_pathlessLayout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/_pathlessLayout/route-a': { - id: '/_pathlessLayout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/_auth/profile': { - id: '/_auth/profile' - path: '/profile' - fullPath: '/profile' - preLoaderRoute: typeof AuthProfileRouteImport - parentRoute: typeof AuthRoute - } '/(this-folder-is-not-in-the-url)/route-group': { id: '/(this-folder-is-not-in-the-url)/route-group' path: '/route-group' @@ -306,11 +271,32 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof thisFolderIsNotInTheUrlRouteGroupRouteImport parentRoute: typeof rootRouteImport } - '/dashboard/users': { - id: '/dashboard/users' - path: '/users' - fullPath: '/dashboard/users' - preLoaderRoute: typeof DashboardUsersRouteRouteImport + '/_auth/profile': { + id: '/_auth/profile' + path: '/profile' + fullPath: '/profile' + preLoaderRoute: typeof AuthProfileRouteImport + parentRoute: typeof AuthRoute + } + '/_pathlessLayout/route-a': { + id: '/_pathlessLayout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutRoute + } + '/_pathlessLayout/route-b': { + id: '/_pathlessLayout/route-b' + path: '/route-b' + fullPath: '/route-b' + preLoaderRoute: typeof PathlessLayoutRouteBRouteImport + parentRoute: typeof PathlessLayoutRoute + } + '/dashboard/': { + id: '/dashboard/' + path: '/' + fullPath: '/dashboard/' + preLoaderRoute: typeof DashboardIndexRouteImport parentRoute: typeof DashboardRouteRoute } '/dashboard/invoices': { @@ -320,12 +306,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DashboardInvoicesRouteRouteImport parentRoute: typeof DashboardRouteRoute } - '/dashboard/users/': { - id: '/dashboard/users/' - path: '/' - fullPath: '/dashboard/users/' - preLoaderRoute: typeof DashboardUsersIndexRouteImport - parentRoute: typeof DashboardUsersRouteRoute + '/dashboard/users': { + id: '/dashboard/users' + path: '/users' + fullPath: '/dashboard/users' + preLoaderRoute: typeof DashboardUsersRouteRouteImport + parentRoute: typeof DashboardRouteRoute + } + '/expensive/': { + id: '/expensive/' + path: '/expensive' + fullPath: '/expensive/' + preLoaderRoute: typeof ExpensiveIndexRouteImport + parentRoute: typeof rootRouteImport } '/dashboard/invoices/': { id: '/dashboard/invoices/' @@ -334,13 +327,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DashboardInvoicesIndexRouteImport parentRoute: typeof DashboardInvoicesRouteRoute } - '/dashboard/users/user': { - id: '/dashboard/users/user' - path: '/user' - fullPath: '/dashboard/users/user' - preLoaderRoute: typeof DashboardUsersUserRouteImport - parentRoute: typeof DashboardUsersRouteRoute - } '/dashboard/invoices/$invoiceId': { id: '/dashboard/invoices/$invoiceId' path: '/$invoiceId' @@ -348,6 +334,20 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DashboardInvoicesInvoiceIdRouteImport parentRoute: typeof DashboardInvoicesRouteRoute } + '/dashboard/users/': { + id: '/dashboard/users/' + path: '/' + fullPath: '/dashboard/users/' + preLoaderRoute: typeof DashboardUsersIndexRouteImport + parentRoute: typeof DashboardUsersRouteRoute + } + '/dashboard/users/user': { + id: '/dashboard/users/user' + path: '/user' + fullPath: '/dashboard/users/user' + preLoaderRoute: typeof DashboardUsersUserRouteImport + parentRoute: typeof DashboardUsersRouteRoute + } } } diff --git a/examples/solid/kitchen-sink-solid-query-file-based/package.json b/examples/solid/kitchen-sink-solid-query-file-based/package.json index fe71bf13e9..25a1c29953 100644 --- a/examples/solid/kitchen-sink-solid-query-file-based/package.json +++ b/examples/solid/kitchen-sink-solid-query-file-based/package.json @@ -10,11 +10,11 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/router-plugin": "^1.169.0", "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "immer": "^10.1.1", "redaxios": "^0.5.1", "solid-js": "^1.9.10", @@ -22,7 +22,8 @@ "zod": "^4.4.3" }, "devDependencies": { - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/kitchen-sink-solid-query-file-based/src/routeTree.gen.ts b/examples/solid/kitchen-sink-solid-query-file-based/src/routeTree.gen.ts index e296846127..8235344782 100644 --- a/examples/solid/kitchen-sink-solid-query-file-based/src/routeTree.gen.ts +++ b/examples/solid/kitchen-sink-solid-query-file-based/src/routeTree.gen.ts @@ -9,80 +9,65 @@ // 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 LoginRouteImport } from './routes/login' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as AuthRouteImport } from './routes/_auth' -import { Route as DashboardRouteRouteImport } from './routes/dashboard.route' import { Route as IndexRouteImport } from './routes/index' -import { Route as ExpensiveIndexRouteImport } from './routes/expensive/index' -import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' -import { Route as FooBarRouteImport } from './routes/foo/bar' -import { Route as PathlessLayoutRouteBRouteImport } from './routes/_pathlessLayout.route-b' -import { Route as PathlessLayoutRouteARouteImport } from './routes/_pathlessLayout.route-a' +import { Route as AuthRouteImport } from './routes/_auth' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as DashboardRouteRouteImport } from './routes/dashboard.route' +import { Route as LoginRouteImport } from './routes/login' import { Route as AuthProfileRouteImport } from './routes/_auth.profile' -import { Route as DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as PathlessLayoutRouteARouteImport } from './routes/_pathlessLayout.route-a' +import { Route as PathlessLayoutRouteBRouteImport } from './routes/_pathlessLayout.route-b' +import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' import { Route as DashboardInvoicesRouteRouteImport } from './routes/dashboard.invoices.route' -import { Route as DashboardUsersIndexRouteImport } from './routes/dashboard.users.index' +import { Route as DashboardUsersRouteRouteImport } from './routes/dashboard.users.route' +import { Route as ExpensiveIndexRouteImport } from './routes/expensive/index' +import { Route as FooBarRouteImport } from './routes/foo/bar' import { Route as DashboardInvoicesIndexRouteImport } from './routes/dashboard.invoices.index' -import { Route as DashboardUsersUserRouteImport } from './routes/dashboard.users.user' import { Route as DashboardInvoicesInvoiceIdRouteImport } from './routes/dashboard.invoices.$invoiceId' +import { Route as DashboardUsersIndexRouteImport } from './routes/dashboard.users.index' +import { Route as DashboardUsersUserRouteImport } from './routes/dashboard.users.user' -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthRoute = AuthRouteImport.update({ id: '/_auth', getParentRoute: () => rootRouteImport, } as any) +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', + getParentRoute: () => rootRouteImport, +} as any) const DashboardRouteRoute = DashboardRouteRouteImport.update({ id: '/dashboard', path: '/dashboard', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', getParentRoute: () => rootRouteImport, } as any) -const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ - id: '/expensive/', - path: '/expensive/', - getParentRoute: () => rootRouteImport, -} as any) -const DashboardIndexRoute = DashboardIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardRouteRoute, -} as any) -const FooBarRoute = FooBarRouteImport.update({ - id: '/foo/bar', - path: '/foo/bar', - getParentRoute: () => rootRouteImport, -} as any) -const PathlessLayoutRouteBRoute = PathlessLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutRoute, -} as any) -const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ - id: '/route-a', - path: '/route-a', - getParentRoute: () => PathlessLayoutRoute, -} as any) const AuthProfileRoute = AuthProfileRouteImport.update({ id: '/profile', path: '/profile', getParentRoute: () => AuthRoute, } as any) -const DashboardUsersRouteRoute = DashboardUsersRouteRouteImport.update({ - id: '/users', - path: '/users', +const PathlessLayoutRouteARoute = PathlessLayoutRouteARouteImport.update({ + id: '/route-a', + path: '/route-a', + getParentRoute: () => PathlessLayoutRoute, +} as any) +const PathlessLayoutRouteBRoute = PathlessLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutRoute, +} as any) +const DashboardIndexRoute = DashboardIndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => DashboardRouteRoute, } as any) const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ @@ -90,27 +75,42 @@ const DashboardInvoicesRouteRoute = DashboardInvoicesRouteRouteImport.update({ path: '/invoices', getParentRoute: () => DashboardRouteRoute, } as any) -const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => DashboardUsersRouteRoute, +const DashboardUsersRouteRoute = DashboardUsersRouteRouteImport.update({ + id: '/users', + path: '/users', + getParentRoute: () => DashboardRouteRoute, +} as any) +const ExpensiveIndexRoute = ExpensiveIndexRouteImport.update({ + id: '/expensive/', + path: '/expensive/', + getParentRoute: () => rootRouteImport, +} as any) +const FooBarRoute = FooBarRouteImport.update({ + id: '/foo/bar', + path: '/foo/bar', + getParentRoute: () => rootRouteImport, } as any) const DashboardInvoicesIndexRoute = DashboardInvoicesIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => DashboardInvoicesRouteRoute, } as any) -const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ - id: '/user', - path: '/user', - getParentRoute: () => DashboardUsersRouteRoute, -} as any) const DashboardInvoicesInvoiceIdRoute = DashboardInvoicesInvoiceIdRouteImport.update({ id: '/$invoiceId', path: '/$invoiceId', getParentRoute: () => DashboardInvoicesRouteRoute, } as any) +const DashboardUsersIndexRoute = DashboardUsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => DashboardUsersRouteRoute, +} as any) +const DashboardUsersUserRoute = DashboardUsersUserRouteImport.update({ + id: '/user', + path: '/user', + getParentRoute: () => DashboardUsersRouteRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -228,18 +228,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout': { - id: '/_pathlessLayout' - path: '' + '/': { + id: '/' + path: '/' fullPath: '/' - preLoaderRoute: typeof PathlessLayoutRouteImport + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_auth': { @@ -249,6 +242,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AuthRouteImport parentRoute: typeof rootRouteImport } + '/_pathlessLayout': { + id: '/_pathlessLayout' + path: '' + fullPath: '/' + preLoaderRoute: typeof PathlessLayoutRouteImport + parentRoute: typeof rootRouteImport + } '/dashboard': { id: '/dashboard' path: '/dashboard' @@ -256,48 +256,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DashboardRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/expensive/': { - id: '/expensive/' - path: '/expensive' - fullPath: '/expensive/' - preLoaderRoute: typeof ExpensiveIndexRouteImport - parentRoute: typeof rootRouteImport - } - '/dashboard/': { - id: '/dashboard/' - path: '/' - fullPath: '/dashboard/' - preLoaderRoute: typeof DashboardIndexRouteImport - parentRoute: typeof DashboardRouteRoute - } - '/foo/bar': { - id: '/foo/bar' - path: '/foo/bar' - fullPath: '/foo/bar' - preLoaderRoute: typeof FooBarRouteImport - parentRoute: typeof rootRouteImport - } - '/_pathlessLayout/route-b': { - id: '/_pathlessLayout/route-b' - path: '/route-b' - fullPath: '/route-b' - preLoaderRoute: typeof PathlessLayoutRouteBRouteImport - parentRoute: typeof PathlessLayoutRoute - } - '/_pathlessLayout/route-a': { - id: '/_pathlessLayout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutRoute - } '/_auth/profile': { id: '/_auth/profile' path: '/profile' @@ -305,11 +270,25 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AuthProfileRouteImport parentRoute: typeof AuthRoute } - '/dashboard/users': { - id: '/dashboard/users' - path: '/users' - fullPath: '/dashboard/users' - preLoaderRoute: typeof DashboardUsersRouteRouteImport + '/_pathlessLayout/route-a': { + id: '/_pathlessLayout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutRoute + } + '/_pathlessLayout/route-b': { + id: '/_pathlessLayout/route-b' + path: '/route-b' + fullPath: '/route-b' + preLoaderRoute: typeof PathlessLayoutRouteBRouteImport + parentRoute: typeof PathlessLayoutRoute + } + '/dashboard/': { + id: '/dashboard/' + path: '/' + fullPath: '/dashboard/' + preLoaderRoute: typeof DashboardIndexRouteImport parentRoute: typeof DashboardRouteRoute } '/dashboard/invoices': { @@ -319,12 +298,26 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DashboardInvoicesRouteRouteImport parentRoute: typeof DashboardRouteRoute } - '/dashboard/users/': { - id: '/dashboard/users/' - path: '/' - fullPath: '/dashboard/users/' - preLoaderRoute: typeof DashboardUsersIndexRouteImport - parentRoute: typeof DashboardUsersRouteRoute + '/dashboard/users': { + id: '/dashboard/users' + path: '/users' + fullPath: '/dashboard/users' + preLoaderRoute: typeof DashboardUsersRouteRouteImport + parentRoute: typeof DashboardRouteRoute + } + '/expensive/': { + id: '/expensive/' + path: '/expensive' + fullPath: '/expensive/' + preLoaderRoute: typeof ExpensiveIndexRouteImport + parentRoute: typeof rootRouteImport + } + '/foo/bar': { + id: '/foo/bar' + path: '/foo/bar' + fullPath: '/foo/bar' + preLoaderRoute: typeof FooBarRouteImport + parentRoute: typeof rootRouteImport } '/dashboard/invoices/': { id: '/dashboard/invoices/' @@ -333,13 +326,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DashboardInvoicesIndexRouteImport parentRoute: typeof DashboardInvoicesRouteRoute } - '/dashboard/users/user': { - id: '/dashboard/users/user' - path: '/user' - fullPath: '/dashboard/users/user' - preLoaderRoute: typeof DashboardUsersUserRouteImport - parentRoute: typeof DashboardUsersRouteRoute - } '/dashboard/invoices/$invoiceId': { id: '/dashboard/invoices/$invoiceId' path: '/$invoiceId' @@ -347,6 +333,20 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DashboardInvoicesInvoiceIdRouteImport parentRoute: typeof DashboardInvoicesRouteRoute } + '/dashboard/users/': { + id: '/dashboard/users/' + path: '/' + fullPath: '/dashboard/users/' + preLoaderRoute: typeof DashboardUsersIndexRouteImport + parentRoute: typeof DashboardUsersRouteRoute + } + '/dashboard/users/user': { + id: '/dashboard/users/user' + path: '/user' + fullPath: '/dashboard/users/user' + preLoaderRoute: typeof DashboardUsersUserRouteImport + parentRoute: typeof DashboardUsersRouteRoute + } } } diff --git a/examples/solid/kitchen-sink-solid-query/package.json b/examples/solid/kitchen-sink-solid-query/package.json index 73b9eb16aa..7a7dc81025 100644 --- a/examples/solid/kitchen-sink-solid-query/package.json +++ b/examples/solid/kitchen-sink-solid-query/package.json @@ -12,8 +12,8 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "immer": "^10.1.1", "redaxios": "^0.5.1", "solid-js": "^1.9.10", @@ -21,7 +21,8 @@ "zod": "^4.4.3" }, "devDependencies": { - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/kitchen-sink/package.json b/examples/solid/kitchen-sink/package.json index 25833261e7..08ad918a60 100644 --- a/examples/solid/kitchen-sink/package.json +++ b/examples/solid/kitchen-sink/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "immer": "^10.1.1", "redaxios": "^0.5.1", "solid-js": "^1.9.10", @@ -19,7 +19,8 @@ "zod": "^4.4.3" }, "devDependencies": { - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/large-file-based/package.json b/examples/solid/large-file-based/package.json index bfdff9eaba..cd758ab704 100644 --- a/examples/solid/large-file-based/package.json +++ b/examples/solid/large-file-based/package.json @@ -12,17 +12,18 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/router-plugin": "^1.169.0", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, "devDependencies": { - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/large-file-based/src/routeTree.gen.ts b/examples/solid/large-file-based/src/routeTree.gen.ts index d345b69acf..ea7329778c 100644 --- a/examples/solid/large-file-based/src/routeTree.gen.ts +++ b/examples/solid/large-file-based/src/routeTree.gen.ts @@ -9,23 +9,18 @@ // 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 RelativeRouteImport } from './routes/relative' -import { Route as LinkPropsRouteImport } from './routes/linkProps' -import { Route as AbsoluteRouteImport } from './routes/absolute' -import { Route as SearchRouteRouteImport } from './routes/search/route' -import { Route as ParamsRouteRouteImport } from './routes/params/route' import { Route as IndexRouteImport } from './routes/index' -import { Route as SearchSearchPlaceholderRouteImport } from './routes/search/searchPlaceholder' +import { Route as AbsoluteRouteImport } from './routes/absolute' +import { Route as LinkPropsRouteImport } from './routes/linkProps' +import { Route as ParamsRouteRouteImport } from './routes/params/route' +import { Route as RelativeRouteImport } from './routes/relative' +import { Route as SearchRouteRouteImport } from './routes/search/route' import { Route as ParamsParamsPlaceholderRouteImport } from './routes/params/$paramsPlaceholder' +import { Route as SearchSearchPlaceholderRouteImport } from './routes/search/searchPlaceholder' -const RelativeRoute = RelativeRouteImport.update({ - id: '/relative', - path: '/relative', - getParentRoute: () => rootRouteImport, -} as any) -const LinkPropsRoute = LinkPropsRouteImport.update({ - id: '/linkProps', - path: '/linkProps', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AbsoluteRoute = AbsoluteRouteImport.update({ @@ -33,9 +28,9 @@ const AbsoluteRoute = AbsoluteRouteImport.update({ path: '/absolute', getParentRoute: () => rootRouteImport, } as any) -const SearchRouteRoute = SearchRouteRouteImport.update({ - id: '/search', - path: '/search', +const LinkPropsRoute = LinkPropsRouteImport.update({ + id: '/linkProps', + path: '/linkProps', getParentRoute: () => rootRouteImport, } as any) const ParamsRouteRoute = ParamsRouteRouteImport.update({ @@ -43,21 +38,26 @@ const ParamsRouteRoute = ParamsRouteRouteImport.update({ path: '/params', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const RelativeRoute = RelativeRouteImport.update({ + id: '/relative', + path: '/relative', getParentRoute: () => rootRouteImport, } as any) -const SearchSearchPlaceholderRoute = SearchSearchPlaceholderRouteImport.update({ - id: '/searchPlaceholder', - path: '/searchPlaceholder', - getParentRoute: () => SearchRouteRoute, +const SearchRouteRoute = SearchRouteRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => rootRouteImport, } as any) const ParamsParamsPlaceholderRoute = ParamsParamsPlaceholderRouteImport.update({ id: '/$paramsPlaceholder', path: '/$paramsPlaceholder', getParentRoute: () => ParamsRouteRoute, } as any) +const SearchSearchPlaceholderRoute = SearchSearchPlaceholderRouteImport.update({ + id: '/searchPlaceholder', + path: '/searchPlaceholder', + getParentRoute: () => SearchRouteRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -134,18 +134,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/relative': { - id: '/relative' - path: '/relative' - fullPath: '/relative' - preLoaderRoute: typeof RelativeRouteImport - parentRoute: typeof rootRouteImport - } - '/linkProps': { - id: '/linkProps' - path: '/linkProps' - fullPath: '/linkProps' - preLoaderRoute: typeof LinkPropsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/absolute': { @@ -155,11 +148,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AbsoluteRouteImport parentRoute: typeof rootRouteImport } - '/search': { - id: '/search' - path: '/search' - fullPath: '/search' - preLoaderRoute: typeof SearchRouteRouteImport + '/linkProps': { + id: '/linkProps' + path: '/linkProps' + fullPath: '/linkProps' + preLoaderRoute: typeof LinkPropsRouteImport parentRoute: typeof rootRouteImport } '/params': { @@ -169,19 +162,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ParamsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/relative': { + id: '/relative' + path: '/relative' + fullPath: '/relative' + preLoaderRoute: typeof RelativeRouteImport parentRoute: typeof rootRouteImport } - '/search/searchPlaceholder': { - id: '/search/searchPlaceholder' - path: '/searchPlaceholder' - fullPath: '/search/searchPlaceholder' - preLoaderRoute: typeof SearchSearchPlaceholderRouteImport - parentRoute: typeof SearchRouteRoute + '/search': { + id: '/search' + path: '/search' + fullPath: '/search' + preLoaderRoute: typeof SearchRouteRouteImport + parentRoute: typeof rootRouteImport } '/params/$paramsPlaceholder': { id: '/params/$paramsPlaceholder' @@ -190,6 +183,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ParamsParamsPlaceholderRouteImport parentRoute: typeof ParamsRouteRoute } + '/search/searchPlaceholder': { + id: '/search/searchPlaceholder' + path: '/searchPlaceholder' + fullPath: '/search/searchPlaceholder' + preLoaderRoute: typeof SearchSearchPlaceholderRouteImport + parentRoute: typeof SearchRouteRoute + } } } diff --git a/examples/solid/location-masking/package.json b/examples/solid/location-masking/package.json index 5b0b9df7e3..7d2fbb6756 100644 --- a/examples/solid/location-masking/package.json +++ b/examples/solid/location-masking/package.json @@ -11,15 +11,16 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "solid-js": "^1.9.10", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2" }, "devDependencies": { "vite-plugin-solid": "^2.11.11", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/solid/navigation-blocking/package.json b/examples/solid/navigation-blocking/package.json index 9b2ef78745..2338d32305 100644 --- a/examples/solid/navigation-blocking/package.json +++ b/examples/solid/navigation-blocking/package.json @@ -11,15 +11,16 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "solid-js": "^1.9.10", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2" }, "devDependencies": { "vite-plugin-solid": "^2.11.11", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/solid/quickstart-esbuild-file-based/build.js b/examples/solid/quickstart-esbuild-file-based/build.js index f8d31fbbd9..af5e01b4cd 100644 --- a/examples/solid/quickstart-esbuild-file-based/build.js +++ b/examples/solid/quickstart-esbuild-file-based/build.js @@ -14,10 +14,7 @@ const ctx = await esbuild.context({ target: ['esnext'], sourcemap: true, conditions: ['style'], - plugins: [ - solidPlugin(), - tanstackRouter({ target: 'solid', autoCodeSplitting: true }), - ], + plugins: [solidPlugin(), tanstackRouter({ target: 'solid' })], }) if (isDev) { diff --git a/examples/solid/quickstart-esbuild-file-based/package.json b/examples/solid/quickstart-esbuild-file-based/package.json index 71bac328eb..9bcc9a08d0 100644 --- a/examples/solid/quickstart-esbuild-file-based/package.json +++ b/examples/solid/quickstart-esbuild-file-based/package.json @@ -9,9 +9,9 @@ "start": "dev" }, "dependencies": { - "@tanstack/router-plugin": "^1.168.20", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", diff --git a/examples/solid/quickstart-file-based/package.json b/examples/solid/quickstart-file-based/package.json index 619c6d00f7..920154566d 100644 --- a/examples/solid/quickstart-file-based/package.json +++ b/examples/solid/quickstart-file-based/package.json @@ -10,16 +10,17 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, "devDependencies": { - "@tanstack/router-plugin": "^1.168.20", - "typescript": "^6.0.2", + "@tanstack/router-plugin": "^1.169.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/quickstart-file-based/src/routeTree.gen.ts b/examples/solid/quickstart-file-based/src/routeTree.gen.ts index 333a815c38..98df1e83d8 100644 --- a/examples/solid/quickstart-file-based/src/routeTree.gen.ts +++ b/examples/solid/quickstart-file-based/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/quickstart-rspack-file-based/package.json b/examples/solid/quickstart-rspack-file-based/package.json index 5b80ce7428..2d9c886ac3 100644 --- a/examples/solid/quickstart-rspack-file-based/package.json +++ b/examples/solid/quickstart-rspack-file-based/package.json @@ -9,17 +9,18 @@ }, "dependencies": { "@tailwindcss/postcss": "^4.2.2", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "postcss": "^8.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, "devDependencies": { - "@rsbuild/core": "^2.0.11", + "@rsbuild/core": "^2.3.1", "@rsbuild/plugin-babel": "^1.1.2", "@rsbuild/plugin-solid": "^1.1.1", - "@tanstack/router-plugin": "^1.168.20", - "typescript": "^6.0.2" + "@tanstack/router-plugin": "^1.169.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2" } } diff --git a/examples/solid/quickstart-rspack-file-based/src/routeTree.gen.ts b/examples/solid/quickstart-rspack-file-based/src/routeTree.gen.ts index 333a815c38..98df1e83d8 100644 --- a/examples/solid/quickstart-rspack-file-based/src/routeTree.gen.ts +++ b/examples/solid/quickstart-rspack-file-based/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/quickstart-webpack-file-based/package.json b/examples/solid/quickstart-webpack-file-based/package.json index e8b66516d7..16167be207 100644 --- a/examples/solid/quickstart-webpack-file-based/package.json +++ b/examples/solid/quickstart-webpack-file-based/package.json @@ -7,15 +7,15 @@ "build": "webpack build && tsc --noEmit" }, "dependencies": { - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, "devDependencies": { "@babel/core": "^7.28.5", "@babel/preset-typescript": "^7.27.1", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/router-plugin": "^1.169.0", "babel-loader": "^10.0.0", "babel-preset-solid": "^1.9.10", "css-loader": "^7.1.2", @@ -23,7 +23,8 @@ "postcss": "^8.5.6", "postcss-loader": "^8.2.0", "style-loader": "^4.0.0", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "webpack": "^5.97.1", "webpack-cli": "^5.1.4", "webpack-dev-server": "^5.2.4" diff --git a/examples/solid/quickstart-webpack-file-based/src/routeTree.gen.ts b/examples/solid/quickstart-webpack-file-based/src/routeTree.gen.ts index 333a815c38..98df1e83d8 100644 --- a/examples/solid/quickstart-webpack-file-based/src/routeTree.gen.ts +++ b/examples/solid/quickstart-webpack-file-based/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/quickstart/package.json b/examples/solid/quickstart/package.json index b8ee528ba1..454382e8cc 100644 --- a/examples/solid/quickstart/package.json +++ b/examples/solid/quickstart/package.json @@ -10,14 +10,15 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, "devDependencies": { "vite-plugin-solid": "^2.11.11", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/solid/router-monorepo-simple-lazy/package.json b/examples/solid/router-monorepo-simple-lazy/package.json index ccbe70b582..1d60ab2765 100644 --- a/examples/solid/router-monorepo-simple-lazy/package.json +++ b/examples/solid/router-monorepo-simple-lazy/package.json @@ -8,16 +8,17 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "solid-js": "^1.9.10", "redaxios": "^0.5.1" }, "devDependencies": { "@types/node": "^22.7.4", "vite-plugin-solid": "^2.11.11", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" }, diff --git a/examples/solid/router-monorepo-simple-lazy/packages/app/package.json b/examples/solid/router-monorepo-simple-lazy/packages/app/package.json index 23b7a2bdfa..a2e018fa96 100644 --- a/examples/solid/router-monorepo-simple-lazy/packages/app/package.json +++ b/examples/solid/router-monorepo-simple-lazy/packages/app/package.json @@ -18,8 +18,9 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "typescript": "^6.0.2", - "@tanstack/solid-router-devtools": "^1.167.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "@tanstack/solid-router-devtools": "^1.167.3", "tailwindcss": "^4.2.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4", diff --git a/examples/solid/router-monorepo-simple-lazy/packages/post-feature/package.json b/examples/solid/router-monorepo-simple-lazy/packages/post-feature/package.json index dd09d18b06..849be06ce6 100644 --- a/examples/solid/router-monorepo-simple-lazy/packages/post-feature/package.json +++ b/examples/solid/router-monorepo-simple-lazy/packages/post-feature/package.json @@ -22,7 +22,8 @@ }, "devDependencies": { "vite-plugin-solid": "^2.11.11", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } diff --git a/examples/solid/router-monorepo-simple-lazy/packages/router/package.json b/examples/solid/router-monorepo-simple-lazy/packages/router/package.json index d6f18e536d..0672c42931 100644 --- a/examples/solid/router-monorepo-simple-lazy/packages/router/package.json +++ b/examples/solid/router-monorepo-simple-lazy/packages/router/package.json @@ -8,16 +8,17 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.162.0", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/history": "^1.162.5", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/router-plugin": "^1.169.0", "redaxios": "^0.5.1", "zod": "^4.4.3", "solid-js": "^1.9.10" }, "devDependencies": { "vite-plugin-solid": "^2.11.11", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } diff --git a/examples/solid/router-monorepo-simple-lazy/packages/router/src/routeTree.gen.ts b/examples/solid/router-monorepo-simple-lazy/packages/router/src/routeTree.gen.ts index e8f1a5370b..8760312d24 100644 --- a/examples/solid/router-monorepo-simple-lazy/packages/router/src/routeTree.gen.ts +++ b/examples/solid/router-monorepo-simple-lazy/packages/router/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 PostIdRouteImport } from './routes/$postId' import { Route as IndexRouteImport } from './routes/index' +import { Route as PostIdRouteImport } from './routes/$postId' -const PostIdRoute = PostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const PostIdRoute = PostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/$postId': { - id: '/$postId' - path: '/$postId' - fullPath: '/$postId' - preLoaderRoute: typeof PostIdRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/$postId': { + id: '/$postId' + path: '/$postId' + fullPath: '/$postId' + preLoaderRoute: typeof PostIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/router-monorepo-simple/package.json b/examples/solid/router-monorepo-simple/package.json index 52a1d9386a..3770256692 100644 --- a/examples/solid/router-monorepo-simple/package.json +++ b/examples/solid/router-monorepo-simple/package.json @@ -8,16 +8,17 @@ "dev": "pnpm router build && pnpm post-feature build && pnpm app dev" }, "dependencies": { - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "solid-js": "^1.9.10", "redaxios": "^0.5.1" }, "devDependencies": { "@types/node": "^22.7.4", "vite-plugin-solid": "^2.11.11", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" }, diff --git a/examples/solid/router-monorepo-simple/packages/app/package.json b/examples/solid/router-monorepo-simple/packages/app/package.json index cf6e11f42c..61234ac455 100644 --- a/examples/solid/router-monorepo-simple/packages/app/package.json +++ b/examples/solid/router-monorepo-simple/packages/app/package.json @@ -15,8 +15,9 @@ }, "devDependencies": { "vite-plugin-solid": "^2.11.11", - "typescript": "^6.0.2", - "@tanstack/solid-router-devtools": "^1.167.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "@tanstack/solid-router-devtools": "^1.167.3", "vite": "^8.0.14", "tailwindcss": "^4.2.2", "vite-plugin-dts": "^4.5.4", diff --git a/examples/solid/router-monorepo-simple/packages/post-feature/package.json b/examples/solid/router-monorepo-simple/packages/post-feature/package.json index 798eca44ab..eb8005b953 100644 --- a/examples/solid/router-monorepo-simple/packages/post-feature/package.json +++ b/examples/solid/router-monorepo-simple/packages/post-feature/package.json @@ -13,7 +13,8 @@ }, "devDependencies": { "vite-plugin-solid": "^2.11.11", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } diff --git a/examples/solid/router-monorepo-simple/packages/router/package.json b/examples/solid/router-monorepo-simple/packages/router/package.json index b1ac76acab..ca08511d3e 100644 --- a/examples/solid/router-monorepo-simple/packages/router/package.json +++ b/examples/solid/router-monorepo-simple/packages/router/package.json @@ -8,16 +8,17 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.162.0", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/history": "^1.162.5", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/router-plugin": "^1.169.0", "redaxios": "^0.5.1", "zod": "^4.4.3", "solid-js": "^1.9.10" }, "devDependencies": { "vite-plugin-solid": "^2.11.11", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } diff --git a/examples/solid/router-monorepo-simple/packages/router/src/routeTree.gen.ts b/examples/solid/router-monorepo-simple/packages/router/src/routeTree.gen.ts index e8f1a5370b..8760312d24 100644 --- a/examples/solid/router-monorepo-simple/packages/router/src/routeTree.gen.ts +++ b/examples/solid/router-monorepo-simple/packages/router/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 PostIdRouteImport } from './routes/$postId' import { Route as IndexRouteImport } from './routes/index' +import { Route as PostIdRouteImport } from './routes/$postId' -const PostIdRoute = PostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const PostIdRoute = PostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/$postId': { - id: '/$postId' - path: '/$postId' - fullPath: '/$postId' - preLoaderRoute: typeof PostIdRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/$postId': { + id: '/$postId' + path: '/$postId' + fullPath: '/$postId' + preLoaderRoute: typeof PostIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/router-monorepo-solid-query/package.json b/examples/solid/router-monorepo-solid-query/package.json index 9acd494517..3d9fd2e2d0 100644 --- a/examples/solid/router-monorepo-solid-query/package.json +++ b/examples/solid/router-monorepo-solid-query/package.json @@ -12,15 +12,16 @@ "dependencies": { "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "solid-js": "^1.9.10", "redaxios": "^0.5.1" }, "devDependencies": { "@types/node": "^22.10.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite-plugin-solid": "^2.11.11", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" diff --git a/examples/solid/router-monorepo-solid-query/packages/app/package.json b/examples/solid/router-monorepo-solid-query/packages/app/package.json index 39481dc9ad..76bb059de5 100644 --- a/examples/solid/router-monorepo-solid-query/packages/app/package.json +++ b/examples/solid/router-monorepo-solid-query/packages/app/package.json @@ -16,8 +16,9 @@ }, "devDependencies": { "vite-plugin-solid": "^2.11.11", - "typescript": "^6.0.2", - "@tanstack/solid-router-devtools": "^1.167.0", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "@tanstack/solid-router-devtools": "^1.167.3", "tailwindcss": "^4.2.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4", diff --git a/examples/solid/router-monorepo-solid-query/packages/post-feature/package.json b/examples/solid/router-monorepo-solid-query/packages/post-feature/package.json index 842b0c3049..39b57c7dfa 100644 --- a/examples/solid/router-monorepo-solid-query/packages/post-feature/package.json +++ b/examples/solid/router-monorepo-solid-query/packages/post-feature/package.json @@ -15,7 +15,8 @@ }, "devDependencies": { "vite-plugin-solid": "^2.11.11", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } diff --git a/examples/solid/router-monorepo-solid-query/packages/post-query/package.json b/examples/solid/router-monorepo-solid-query/packages/post-query/package.json index cc9a5a18ed..8e3a4b0e71 100644 --- a/examples/solid/router-monorepo-solid-query/packages/post-query/package.json +++ b/examples/solid/router-monorepo-solid-query/packages/post-query/package.json @@ -14,7 +14,8 @@ }, "devDependencies": { "vite-plugin-solid": "^2.11.11", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/solid/router-monorepo-solid-query/packages/router/package.json b/examples/solid/router-monorepo-solid-query/packages/router/package.json index d96aa3ab09..93943a1df8 100644 --- a/examples/solid/router-monorepo-solid-query/packages/router/package.json +++ b/examples/solid/router-monorepo-solid-query/packages/router/package.json @@ -8,10 +8,10 @@ "main": "./dist/index.js", "types": "./dist/index.d.ts", "dependencies": { - "@tanstack/history": "^1.162.0", + "@tanstack/history": "^1.162.5", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/router-plugin": "^1.169.0", "@router-solid-mono-solid-query/post-query": "workspace:*", "redaxios": "^0.5.1", "zod": "^4.4.3", @@ -19,7 +19,8 @@ }, "devDependencies": { "vite-plugin-solid": "^2.11.11", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4" } diff --git a/examples/solid/router-monorepo-solid-query/packages/router/src/routeTree.gen.ts b/examples/solid/router-monorepo-solid-query/packages/router/src/routeTree.gen.ts index e8f1a5370b..8760312d24 100644 --- a/examples/solid/router-monorepo-solid-query/packages/router/src/routeTree.gen.ts +++ b/examples/solid/router-monorepo-solid-query/packages/router/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 PostIdRouteImport } from './routes/$postId' import { Route as IndexRouteImport } from './routes/index' +import { Route as PostIdRouteImport } from './routes/$postId' -const PostIdRoute = PostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const PostIdRoute = PostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/$postId': { - id: '/$postId' - path: '/$postId' - fullPath: '/$postId' - preLoaderRoute: typeof PostIdRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/$postId': { + id: '/$postId' + path: '/$postId' + fullPath: '/$postId' + preLoaderRoute: typeof PostIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/router-monorepo-solid-query/packages/router/src/router.tsx b/examples/solid/router-monorepo-solid-query/packages/router/src/router.tsx index 6153a54a8b..99874f49e5 100644 --- a/examples/solid/router-monorepo-solid-query/packages/router/src/router.tsx +++ b/examples/solid/router-monorepo-solid-query/packages/router/src/router.tsx @@ -1,4 +1,3 @@ -import React from 'react' import { createRouter } from '@tanstack/solid-router' // Import the generated route tree diff --git a/examples/solid/scroll-restoration/package.json b/examples/solid/scroll-restoration/package.json index e80c7aea3b..eaa5a5aaea 100644 --- a/examples/solid/scroll-restoration/package.json +++ b/examples/solid/scroll-restoration/package.json @@ -10,15 +10,16 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "@tanstack/solid-virtual": "^3.13.0", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, "devDependencies": { "vite-plugin-solid": "^2.11.11", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" } } diff --git a/examples/solid/search-validator-adapters/package.json b/examples/solid/search-validator-adapters/package.json index 17e74dcc7a..59991edb36 100644 --- a/examples/solid/search-validator-adapters/package.json +++ b/examples/solid/search-validator-adapters/package.json @@ -13,9 +13,9 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/arktype-adapter": "^1.167.0", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/router-plugin": "^1.169.0", "@tanstack/valibot-adapter": "^1.167.0", "@tanstack/zod-adapter": "^1.167.0", "arktype": "^2.1.7", @@ -25,10 +25,13 @@ "zod": "^3.24.2" }, "devDependencies": { - "@testing-library/jest-dom": "^6.6.3", + "@testing-library/jest-dom": "^7.0.1", "@solidjs/testing-library": "^0.8.10", "vite-plugin-solid": "^2.11.11", - "typescript": "^6.0.2", - "vite": "^8.0.14" + "@typescript/native": "npm:typescript@^7.0.2", + "jsdom": "^27.0.0", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "^8.0.14", + "vitest": "^5.0.4" } } diff --git a/examples/solid/search-validator-adapters/src/routeTree.gen.ts b/examples/solid/search-validator-adapters/src/routeTree.gen.ts index 24089ece84..4cb97b08e9 100644 --- a/examples/solid/search-validator-adapters/src/routeTree.gen.ts +++ b/examples/solid/search-validator-adapters/src/routeTree.gen.ts @@ -10,18 +10,18 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersZodIndexRouteImport } from './routes/users/zod.index' -import { Route as UsersValibotIndexRouteImport } from './routes/users/valibot.index' import { Route as UsersArktypeIndexRouteImport } from './routes/users/arktype.index' +import { Route as UsersValibotIndexRouteImport } from './routes/users/valibot.index' +import { Route as UsersZodIndexRouteImport } from './routes/users/zod.index' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const UsersZodIndexRoute = UsersZodIndexRouteImport.update({ - id: '/users/zod/', - path: '/users/zod/', +const UsersArktypeIndexRoute = UsersArktypeIndexRouteImport.update({ + id: '/users/arktype/', + path: '/users/arktype/', getParentRoute: () => rootRouteImport, } as any) const UsersValibotIndexRoute = UsersValibotIndexRouteImport.update({ @@ -29,9 +29,9 @@ const UsersValibotIndexRoute = UsersValibotIndexRouteImport.update({ path: '/users/valibot/', getParentRoute: () => rootRouteImport, } as any) -const UsersArktypeIndexRoute = UsersArktypeIndexRouteImport.update({ - id: '/users/arktype/', - path: '/users/arktype/', +const UsersZodIndexRoute = UsersZodIndexRouteImport.update({ + id: '/users/zod/', + path: '/users/zod/', getParentRoute: () => rootRouteImport, } as any) @@ -78,11 +78,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/users/zod/': { - id: '/users/zod/' - path: '/users/zod' - fullPath: '/users/zod/' - preLoaderRoute: typeof UsersZodIndexRouteImport + '/users/arktype/': { + id: '/users/arktype/' + path: '/users/arktype' + fullPath: '/users/arktype/' + preLoaderRoute: typeof UsersArktypeIndexRouteImport parentRoute: typeof rootRouteImport } '/users/valibot/': { @@ -92,11 +92,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof UsersValibotIndexRouteImport parentRoute: typeof rootRouteImport } - '/users/arktype/': { - id: '/users/arktype/' - path: '/users/arktype' - fullPath: '/users/arktype/' - preLoaderRoute: typeof UsersArktypeIndexRouteImport + '/users/zod/': { + id: '/users/zod/' + path: '/users/zod' + fullPath: '/users/zod/' + preLoaderRoute: typeof UsersZodIndexRouteImport parentRoute: typeof rootRouteImport } } diff --git a/examples/solid/search-validator-adapters/tests/arktype.test.tsx b/examples/solid/search-validator-adapters/tests/arktype.test.tsx index 4ec555fc7b..f22a359995 100644 --- a/examples/solid/search-validator-adapters/tests/arktype.test.tsx +++ b/examples/solid/search-validator-adapters/tests/arktype.test.tsx @@ -8,7 +8,6 @@ import { createRouter, } from '@tanstack/solid-router' -import '@testing-library/jest-dom/vitest' import { type } from 'arktype' test('can navigate to the route', async () => { diff --git a/examples/solid/search-validator-adapters/tests/jest-dom.setup.ts b/examples/solid/search-validator-adapters/tests/jest-dom.setup.ts new file mode 100644 index 0000000000..8f7cbf15be --- /dev/null +++ b/examples/solid/search-validator-adapters/tests/jest-dom.setup.ts @@ -0,0 +1,18 @@ +import * as jestDomMatchers from '@testing-library/jest-dom/matchers' +import { expect } from 'vitest' +import type { TestingLibraryMatchers } from '@testing-library/jest-dom/matchers' + +// Workaround for Vitest 5: remove once testing-library/jest-dom#742 is merged +// and released, and go back to `import '@testing-library/jest-dom/vitest'`. +// That entry imports `vitest` from its own install location, which can resolve +// a different Vitest copy than the one running these tests, and its types +// augment Vitest 4's `Assertion` instead of Vitest 5's `Matchers`. +// Keep `jest-dom` in this file name: vite-plugin-solid only skips injecting +// `@testing-library/jest-dom/vitest` when a setup file path contains it. +expect.extend(jestDomMatchers) + +declare module 'vitest' { + // Type parameter names must match Vitest's declaration for the interfaces to merge. + // eslint-disable-next-line @typescript-eslint/naming-convention + interface Matchers extends TestingLibraryMatchers {} +} diff --git a/examples/solid/search-validator-adapters/tests/valibot.test.tsx b/examples/solid/search-validator-adapters/tests/valibot.test.tsx index cd4545397c..8594c1cb29 100644 --- a/examples/solid/search-validator-adapters/tests/valibot.test.tsx +++ b/examples/solid/search-validator-adapters/tests/valibot.test.tsx @@ -8,7 +8,6 @@ import { createRouter, } from '@tanstack/solid-router' import * as v from 'valibot' -import '@testing-library/jest-dom/vitest' test('can navigate to the route', async () => { const rootRoute = createRootRoute() diff --git a/examples/solid/search-validator-adapters/vite.config.ts b/examples/solid/search-validator-adapters/vite.config.ts index 5b9dbebfef..4e05d81e75 100644 --- a/examples/solid/search-validator-adapters/vite.config.ts +++ b/examples/solid/search-validator-adapters/vite.config.ts @@ -11,6 +11,7 @@ export default defineConfig({ watch: false, environment: 'jsdom', typecheck: { enabled: true }, + setupFiles: ['./tests/jest-dom.setup.ts'], server: { deps: { inline: [/@solidjs/, /@tanstack\/solid-store/], diff --git a/examples/solid/start-basic-auth/README.md b/examples/solid/start-basic-auth/README.md index 90cba4aac1..313c930051 100644 --- a/examples/solid/start-basic-auth/README.md +++ b/examples/solid/start-basic-auth/README.md @@ -70,3 +70,13 @@ pnpm dev > [!WARNING] > You will need to update the `docs/config.json` file (in the project's repo) if you add a new doc page! + +## Session configuration + +This example uses [iron-session](https://github.com/vvo/iron-session) through Start's `getCookie` and `setCookie` helpers. Set `SESSION_PASSWORD` to a random secret of at least 32 characters before starting the app, for example: + +```sh +export SESSION_PASSWORD="$(openssl rand -base64 32)" +``` + +Keep the same secret across instances and deployments that must read the same sessions. The cookie requires HTTPS in production. Each handler reads its own session, then awaits `session.save()` before redirecting or returning. diff --git a/examples/solid/start-basic-auth/package.json b/examples/solid/start-basic-auth/package.json index 108a260b20..d686fdf616 100644 --- a/examples/solid/start-basic-auth/package.json +++ b/examples/solid/start-basic-auth/package.json @@ -14,9 +14,10 @@ "@libsql/client": "^0.15.15", "@prisma/adapter-libsql": "^7.0.0", "@prisma/client": "^7.0.0", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.28", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", + "iron-session": "^9.0.1", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwind-merge": "^3.6.0" @@ -27,7 +28,8 @@ "dotenv": "^17.2.3", "prisma": "^7.0.0", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/start-basic-auth/src/routeTree.gen.ts b/examples/solid/start-basic-auth/src/routeTree.gen.ts index bad0f1b074..07924d102a 100644 --- a/examples/solid/start-basic-auth/src/routeTree.gen.ts +++ b/examples/solid/start-basic-auth/src/routeTree.gen.ts @@ -9,23 +9,22 @@ // 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 SignupRouteImport } from './routes/signup' -import { Route as LogoutRouteImport } from './routes/logout' -import { Route as LoginRouteImport } from './routes/login' -import { Route as AuthedRouteImport } from './routes/_authed' import { Route as IndexRouteImport } from './routes/index' +import { Route as AuthedRouteImport } from './routes/_authed' +import { Route as LoginRouteImport } from './routes/login' +import { Route as LogoutRouteImport } from './routes/logout' +import { Route as SignupRouteImport } from './routes/signup' import { Route as AuthedPostsRouteRouteImport } from './routes/_authed/posts.route' import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' -const SignupRoute = SignupRouteImport.update({ - id: '/signup', - path: '/signup', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', getParentRoute: () => rootRouteImport, } as any) const LoginRoute = LoginRouteImport.update({ @@ -33,13 +32,14 @@ const LoginRoute = LoginRouteImport.update({ path: '/login', getParentRoute: () => rootRouteImport, } as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', +const LogoutRoute = LogoutRouteImport.update({ + id: '/logout', + path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SignupRoute = SignupRouteImport.update({ + id: '/signup', + path: '/signup', getParentRoute: () => rootRouteImport, } as any) const AuthedPostsRouteRoute = AuthedPostsRouteRouteImport.update({ @@ -120,25 +120,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/signup': { - id: '/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof SignupRouteImport - parentRoute: typeof rootRouteImport - } - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport - parentRoute: typeof rootRouteImport - } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_authed': { @@ -148,11 +134,25 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AuthedRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport + } + '/logout': { + id: '/logout' + path: '/logout' + fullPath: '/logout' + preLoaderRoute: typeof LogoutRouteImport + parentRoute: typeof rootRouteImport + } + '/signup': { + id: '/signup' + path: '/signup' + fullPath: '/signup' + preLoaderRoute: typeof SignupRouteImport parentRoute: typeof rootRouteImport } '/_authed/posts': { diff --git a/examples/solid/start-basic-auth/src/routes/__root.tsx b/examples/solid/start-basic-auth/src/routes/__root.tsx index 3aa0bfa18b..05ad0d298a 100644 --- a/examples/solid/start-basic-auth/src/routes/__root.tsx +++ b/examples/solid/start-basic-auth/src/routes/__root.tsx @@ -14,18 +14,18 @@ import { DefaultCatchBoundary } from '~/components/DefaultCatchBoundary.js' import { NotFound } from '~/components/NotFound.js' import appCss from '~/styles/app.css?url' import { seo } from '~/utils/seo.js' -import { useAppSession } from '~/utils/session.js' +import { getAppSession } from '~/utils/session.js' const fetchUser = createServerFn({ method: 'GET' }).handler(async () => { // We need to auth on the server so we have access to secure cookies - const session = await useAppSession() + const session = await getAppSession() - if (!session.data.userEmail) { + if (!session.userEmail) { return null } return { - email: session.data.userEmail, + email: session.userEmail, } }) diff --git a/examples/solid/start-basic-auth/src/routes/_authed.tsx b/examples/solid/start-basic-auth/src/routes/_authed.tsx index 60ad613e56..cded7ca880 100644 --- a/examples/solid/start-basic-auth/src/routes/_authed.tsx +++ b/examples/solid/start-basic-auth/src/routes/_authed.tsx @@ -2,7 +2,7 @@ import { createFileRoute } from '@tanstack/solid-router' import { createServerFn } from '@tanstack/solid-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { Login } from '~/components/Login' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST' }) .validator((d: { email: string; password: string }) => d) @@ -33,13 +33,10 @@ export const loginFn = createServerFn({ method: 'POST' }) } } - // Create a session - const session = await useAppSession() - // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + const session = await getAppSession() + session.userEmail = user.email + await session.save() }) export const Route = createFileRoute('/_authed')({ diff --git a/examples/solid/start-basic-auth/src/routes/logout.tsx b/examples/solid/start-basic-auth/src/routes/logout.tsx index f7d624ff15..56cd70cbc2 100644 --- a/examples/solid/start-basic-auth/src/routes/logout.tsx +++ b/examples/solid/start-basic-auth/src/routes/logout.tsx @@ -1,11 +1,10 @@ import { createFileRoute, redirect } from '@tanstack/solid-router' import { createServerFn } from '@tanstack/solid-start' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' const logoutFn = createServerFn().handler(async () => { - const session = await useAppSession() - - session.clear() + const session = await getAppSession() + session.destroy() throw redirect({ href: '/', diff --git a/examples/solid/start-basic-auth/src/routes/signup.tsx b/examples/solid/start-basic-auth/src/routes/signup.tsx index 7cb9ae7161..b8d6bf89fa 100644 --- a/examples/solid/start-basic-auth/src/routes/signup.tsx +++ b/examples/solid/start-basic-auth/src/routes/signup.tsx @@ -3,7 +3,7 @@ import { createServerFn, useServerFn } from '@tanstack/solid-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { useMutation } from '~/hooks/useMutation' import { Auth } from '~/components/Auth' -import { useAppSession } from '~/utils/session' +import { getAppSession } from '~/utils/session' export const signupFn = createServerFn({ method: 'POST' }) .validator( @@ -20,9 +20,6 @@ export const signupFn = createServerFn({ method: 'POST' }) // Encrypt the password using Sha256 into plaintext const password = await hashPassword(data.password) - // Create a session - const session = await useAppSession() - if (found) { if (found.password !== password) { return { @@ -33,9 +30,9 @@ export const signupFn = createServerFn({ method: 'POST' }) } // Store the user's email in the session - await session.update({ - userEmail: found.email, - }) + const session = await getAppSession() + session.userEmail = found.email + await session.save() // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -52,9 +49,9 @@ export const signupFn = createServerFn({ method: 'POST' }) }) // Store the user's email in the session - await session.update({ - userEmail: user.email, - }) + const session = await getAppSession() + session.userEmail = user.email + await session.save() // Redirect to the prev page stored in the "redirect" search param throw redirect({ diff --git a/examples/solid/start-basic-auth/src/utils/session.ts b/examples/solid/start-basic-auth/src/utils/session.ts index 120a410b60..4577764d28 100644 --- a/examples/solid/start-basic-auth/src/utils/session.ts +++ b/examples/solid/start-basic-auth/src/utils/session.ts @@ -1,13 +1,29 @@ -// src/services/session.server.ts -import { useSession } from '@tanstack/solid-start/server' +import { getIronSession } from 'iron-session' +import { getCookie, setCookie } from '@tanstack/solid-start/server' import type { User } from '@prisma/client' type SessionUser = { userEmail: User['email'] } -export function useAppSession() { - return useSession({ - password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', - }) +export function getAppSession() { + const password = process.env.SESSION_PASSWORD + if (!password || password.length < 32) { + throw new Error('Set SESSION_PASSWORD to at least 32 characters') + } + + return getIronSession( + { read: getCookie, write: setCookie }, + { + cookieName: 'app-session', + password, + ttl: 7 * 24 * 60 * 60, + cookieOptions: { + httpOnly: true, + sameSite: 'lax', + secure: process.env.NODE_ENV === 'production', + path: '/', + }, + }, + ) } diff --git a/examples/solid/start-basic-authjs/package.json b/examples/solid/start-basic-authjs/package.json index f6fde8367f..2c910663bd 100644 --- a/examples/solid/start-basic-authjs/package.json +++ b/examples/solid/start-basic-authjs/package.json @@ -11,9 +11,9 @@ }, "dependencies": { "@auth/core": "^0.41.1", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.28", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "solid-js": "^1.9.10", "start-authjs": "^1.0.0", "tailwind-merge": "^3.6.0" @@ -22,7 +22,8 @@ "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/start-basic-authjs/src/routeTree.gen.ts b/examples/solid/start-basic-authjs/src/routeTree.gen.ts index e772ba9c3e..7cc6d28cf7 100644 --- a/examples/solid/start-basic-authjs/src/routeTree.gen.ts +++ b/examples/solid/start-basic-authjs/src/routeTree.gen.ts @@ -9,14 +9,14 @@ // 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 ProtectedRouteImport } from './routes/protected' -import { Route as LoginRouteImport } from './routes/login' import { Route as IndexRouteImport } from './routes/index' +import { Route as LoginRouteImport } from './routes/login' +import { Route as ProtectedRouteImport } from './routes/protected' import { Route as ApiAuthSplatRouteImport } from './routes/api/auth/$' -const ProtectedRoute = ProtectedRouteImport.update({ - id: '/protected', - path: '/protected', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const LoginRoute = LoginRouteImport.update({ @@ -24,9 +24,9 @@ const LoginRoute = LoginRouteImport.update({ path: '/login', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ProtectedRoute = ProtectedRouteImport.update({ + id: '/protected', + path: '/protected', getParentRoute: () => rootRouteImport, } as any) const ApiAuthSplatRoute = ApiAuthSplatRouteImport.update({ @@ -71,11 +71,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/protected': { - id: '/protected' - path: '/protected' - fullPath: '/protected' - preLoaderRoute: typeof ProtectedRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/login': { @@ -85,11 +85,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/protected': { + id: '/protected' + path: '/protected' + fullPath: '/protected' + preLoaderRoute: typeof ProtectedRouteImport parentRoute: typeof rootRouteImport } '/api/auth/$': { diff --git a/examples/solid/start-basic-cloudflare/package.json b/examples/solid/start-basic-cloudflare/package.json index 936fb0d20d..7ece143f61 100644 --- a/examples/solid/start-basic-cloudflare/package.json +++ b/examples/solid/start-basic-cloudflare/package.json @@ -12,9 +12,9 @@ "postinstall": "WRANGLER_LOG=warn npm run --silent cf-typegen" }, "dependencies": { - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.28", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "solid-js": "^1.9.10" }, "devDependencies": { @@ -22,7 +22,8 @@ "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11", "wrangler": "^4.74.0" diff --git a/examples/solid/start-basic-cloudflare/src/routeTree.gen.ts b/examples/solid/start-basic-cloudflare/src/routeTree.gen.ts index c3f6976d03..7cba7e8958 100644 --- a/examples/solid/start-basic-cloudflare/src/routeTree.gen.ts +++ b/examples/solid/start-basic-cloudflare/src/routeTree.gen.ts @@ -9,42 +9,31 @@ // 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 UsersRouteImport } from './routes/users' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as UsersRouteImport } from './routes/users' import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ @@ -52,38 +41,24 @@ const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ path: '/customScript.js', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', + getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = @@ -91,28 +66,53 @@ const PathlessLayoutNestedLayoutRoute = id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) -const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', - getParentRoute: () => ApiUsersRoute, + getParentRoute: () => UsersRoute, } as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) const PathlessLayoutNestedLayoutRouteARoute = PathlessLayoutNestedLayoutRouteARouteImport.update({ id: '/route-a', path: '/route-a', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteBRoute = + PathlessLayoutNestedLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => ApiUsersRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -234,39 +234,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/customScript.js': { - id: '/customScript.js' - path: '/customScript.js' - fullPath: '/customScript.js' - preLoaderRoute: typeof CustomScriptDotjsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout': { @@ -276,46 +248,39 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/customScript.js': { + id: '/customScript.js' + path: '/customScript.js' + fullPath: '/customScript.js' + preLoaderRoute: typeof CustomScriptDotjsRouteImport parentRoute: typeof rootRouteImport } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout/_nested-layout': { @@ -325,19 +290,47 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport parentRoute: typeof PathlessLayoutRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/api/users/$userId': { - id: '/api/users/$userId' + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute + } + '/users/$userId': { + id: '/users/$userId' path: '/$userId' - fullPath: '/api/users/$userId' - preLoaderRoute: typeof ApiUsersUserIdRouteImport - parentRoute: typeof ApiUsersRoute + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -346,12 +339,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/api/users/$userId': { + id: '/api/users/$userId' + path: '/$userId' + fullPath: '/api/users/$userId' + preLoaderRoute: typeof ApiUsersUserIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/examples/solid/start-basic-netlify/package.json b/examples/solid/start-basic-netlify/package.json index c727191374..69299cdb79 100644 --- a/examples/solid/start-basic-netlify/package.json +++ b/examples/solid/start-basic-netlify/package.json @@ -9,17 +9,18 @@ "preview": "vite preview" }, "dependencies": { - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.28", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "solid-js": "^1.9.10" }, "devDependencies": { - "@netlify/vite-plugin-tanstack-start": "^1.1.4", + "@netlify/vite-plugin-tanstack-start": "^1.3.19", "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/start-basic-netlify/src/routeTree.gen.ts b/examples/solid/start-basic-netlify/src/routeTree.gen.ts index c3f6976d03..7cba7e8958 100644 --- a/examples/solid/start-basic-netlify/src/routeTree.gen.ts +++ b/examples/solid/start-basic-netlify/src/routeTree.gen.ts @@ -9,42 +9,31 @@ // 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 UsersRouteImport } from './routes/users' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as UsersRouteImport } from './routes/users' import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ @@ -52,38 +41,24 @@ const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ path: '/customScript.js', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', + getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = @@ -91,28 +66,53 @@ const PathlessLayoutNestedLayoutRoute = id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) -const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', - getParentRoute: () => ApiUsersRoute, + getParentRoute: () => UsersRoute, } as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) const PathlessLayoutNestedLayoutRouteARoute = PathlessLayoutNestedLayoutRouteARouteImport.update({ id: '/route-a', path: '/route-a', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteBRoute = + PathlessLayoutNestedLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => ApiUsersRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -234,39 +234,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/customScript.js': { - id: '/customScript.js' - path: '/customScript.js' - fullPath: '/customScript.js' - preLoaderRoute: typeof CustomScriptDotjsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout': { @@ -276,46 +248,39 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/customScript.js': { + id: '/customScript.js' + path: '/customScript.js' + fullPath: '/customScript.js' + preLoaderRoute: typeof CustomScriptDotjsRouteImport parentRoute: typeof rootRouteImport } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout/_nested-layout': { @@ -325,19 +290,47 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport parentRoute: typeof PathlessLayoutRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/api/users/$userId': { - id: '/api/users/$userId' + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute + } + '/users/$userId': { + id: '/users/$userId' path: '/$userId' - fullPath: '/api/users/$userId' - preLoaderRoute: typeof ApiUsersUserIdRouteImport - parentRoute: typeof ApiUsersRoute + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -346,12 +339,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/api/users/$userId': { + id: '/api/users/$userId' + path: '/$userId' + fullPath: '/api/users/$userId' + preLoaderRoute: typeof ApiUsersUserIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/examples/solid/start-basic-nitro/package.json b/examples/solid/start-basic-nitro/package.json index a0fad2103f..2c0dc7dad6 100644 --- a/examples/solid/start-basic-nitro/package.json +++ b/examples/solid/start-basic-nitro/package.json @@ -9,17 +9,18 @@ "preview": "vite preview" }, "dependencies": { - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.28", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "solid-js": "^1.9.10" }, "devDependencies": { "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", - "nitro": "^3.0.260311-beta", + "nitro": "^3.0.260903-beta", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/start-basic-nitro/src/routeTree.gen.ts b/examples/solid/start-basic-nitro/src/routeTree.gen.ts index c3f6976d03..7cba7e8958 100644 --- a/examples/solid/start-basic-nitro/src/routeTree.gen.ts +++ b/examples/solid/start-basic-nitro/src/routeTree.gen.ts @@ -9,42 +9,31 @@ // 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 UsersRouteImport } from './routes/users' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as CustomScriptDotjsRouteImport } from './routes/customScript[.]js' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as UsersRouteImport } from './routes/users' import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', - getParentRoute: () => rootRouteImport, -} as any) -const DeferredRoute = DeferredRouteImport.update({ - id: '/deferred', - path: '/deferred', +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ @@ -52,38 +41,24 @@ const CustomScriptDotjsRoute = CustomScriptDotjsRouteImport.update({ path: '/customScript.js', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const DeferredRoute = DeferredRouteImport.update({ + id: '/deferred', + path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', + getParentRoute: () => rootRouteImport, } as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = @@ -91,28 +66,53 @@ const PathlessLayoutNestedLayoutRoute = id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) -const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', - getParentRoute: () => ApiUsersRoute, + getParentRoute: () => UsersRoute, } as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) const PathlessLayoutNestedLayoutRouteARoute = PathlessLayoutNestedLayoutRouteARouteImport.update({ id: '/route-a', path: '/route-a', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteBRoute = + PathlessLayoutNestedLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => ApiUsersRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -234,39 +234,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport - parentRoute: typeof rootRouteImport - } - '/customScript.js': { - id: '/customScript.js' - path: '/customScript.js' - fullPath: '/customScript.js' - preLoaderRoute: typeof CustomScriptDotjsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout': { @@ -276,46 +248,39 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/customScript.js': { + id: '/customScript.js' + path: '/customScript.js' + fullPath: '/customScript.js' + preLoaderRoute: typeof CustomScriptDotjsRouteImport parentRoute: typeof rootRouteImport } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport + parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout/_nested-layout': { @@ -325,19 +290,47 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport parentRoute: typeof PathlessLayoutRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/api/users/$userId': { - id: '/api/users/$userId' + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute + } + '/users/$userId': { + id: '/users/$userId' path: '/$userId' - fullPath: '/api/users/$userId' - preLoaderRoute: typeof ApiUsersUserIdRouteImport - parentRoute: typeof ApiUsersRoute + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -346,12 +339,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/api/users/$userId': { + id: '/api/users/$userId' + path: '/$userId' + fullPath: '/api/users/$userId' + preLoaderRoute: typeof ApiUsersUserIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/examples/solid/start-basic-solid-query/package.json b/examples/solid/start-basic-solid-query/package.json index 5fe6a67c26..ddbb7d8764 100644 --- a/examples/solid/start-basic-solid-query/package.json +++ b/examples/solid/start-basic-solid-query/package.json @@ -12,10 +12,10 @@ "dependencies": { "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-router-ssr-query": "^1.167.1", - "@tanstack/solid-start": "^1.168.28", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router-ssr-query": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwind-merge": "^3.6.0" @@ -24,7 +24,8 @@ "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/start-basic-solid-query/src/routeTree.gen.ts b/examples/solid/start-basic-solid-query/src/routeTree.gen.ts index 226b599b8c..4a1747ae36 100644 --- a/examples/solid/start-basic-solid-query/src/routeTree.gen.ts +++ b/examples/solid/start-basic-solid-query/src/routeTree.gen.ts @@ -9,26 +9,30 @@ // 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 RedirectRouteImport } from './routes/redirect' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' -import { Route as UsersRouteRouteImport } from './routes/users.route' -import { Route as PostsRouteRouteImport } from './routes/posts.route' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteRouteImport } from './routes/posts.route' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as UsersRouteRouteImport } from './routes/users.route' import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersIdRouteImport } from './routes/api/users.$id' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const DeferredRoute = DeferredRouteImport.update({ @@ -36,8 +40,14 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const PostsRouteRoute = PostsRouteRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', getParentRoute: () => rootRouteImport, } as any) const UsersRouteRoute = UsersRouteRouteImport.update({ @@ -45,68 +55,58 @@ const UsersRouteRoute = UsersRouteRouteImport.update({ path: '/users', getParentRoute: () => rootRouteImport, } as any) -const PostsRouteRoute = PostsRouteRouteImport.update({ - id: '/posts', - path: '/posts', +const PathlessLayoutNestedLayoutRoute = + PathlessLayoutNestedLayoutRouteImport.update({ + id: '/_nested-layout', + getParentRoute: () => PathlessLayoutRoute, + } as any) +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRouteRoute, -} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => PostsRouteRoute, } as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRouteRoute, -} as any) const PostsPostIdRoute = PostsPostIdRouteImport.update({ id: '/$postId', path: '/$postId', getParentRoute: () => PostsRouteRoute, } as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', - getParentRoute: () => rootRouteImport, +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRouteRoute, } as any) -const PathlessLayoutNestedLayoutRoute = - PathlessLayoutNestedLayoutRouteImport.update({ - id: '/_nested-layout', - getParentRoute: () => PathlessLayoutRoute, - } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRouteRoute, } as any) -const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ - id: '/$id', - path: '/$id', - getParentRoute: () => ApiUsersRoute, -} as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) const PathlessLayoutNestedLayoutRouteARoute = PathlessLayoutNestedLayoutRouteARouteImport.update({ id: '/route-a', path: '/route-a', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteBRoute = + PathlessLayoutNestedLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const ApiUsersIdRoute = ApiUsersIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => ApiUsersRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -221,18 +221,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout': { @@ -242,11 +235,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteRouteImport + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } '/posts': { @@ -256,46 +249,18 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport parentRoute: typeof rootRouteImport } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRouteRoute - } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRouteRoute - } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRouteRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRouteRoute - } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout/_nested-layout': { @@ -305,19 +270,47 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport parentRoute: typeof PathlessLayoutRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/api/users/$id': { - id: '/api/users/$id' - path: '/$id' - fullPath: '/api/users/$id' - preLoaderRoute: typeof ApiUsersIdRouteImport - parentRoute: typeof ApiUsersRoute + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRouteRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRouteRoute + } + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRouteRoute + } + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRouteRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -326,12 +319,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/api/users/$id': { + id: '/api/users/$id' + path: '/$id' + fullPath: '/api/users/$id' + preLoaderRoute: typeof ApiUsersIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/examples/solid/start-basic-static/package.json b/examples/solid/start-basic-static/package.json index 636e3cc8db..8b639da68a 100644 --- a/examples/solid/start-basic-static/package.json +++ b/examples/solid/start-basic-static/package.json @@ -10,10 +10,10 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.28", - "@tanstack/start-static-server-functions": "^1.167.19", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", + "@tanstack/start-static-server-functions": "^1.167.44", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwind-merge": "^3.6.0" @@ -22,7 +22,8 @@ "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/start-basic-static/src/routeTree.gen.ts b/examples/solid/start-basic-static/src/routeTree.gen.ts index 7cad5523aa..a94e0fcf2e 100644 --- a/examples/solid/start-basic-static/src/routeTree.gen.ts +++ b/examples/solid/start-basic-static/src/routeTree.gen.ts @@ -9,34 +9,28 @@ // 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 UsersRouteImport } from './routes/users' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as UsersRouteImport } from './routes/users' import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const DeferredRoute = DeferredRouteImport.update({ @@ -44,57 +38,63 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, -} as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', + getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = PathlessLayoutNestedLayoutRouteImport.update({ id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', - getParentRoute: () => rootRouteImport, +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => UsersRoute, } as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) const PathlessLayoutNestedLayoutRouteARoute = PathlessLayoutNestedLayoutRouteARouteImport.update({ id: '/route-a', path: '/route-a', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteBRoute = + PathlessLayoutNestedLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -196,32 +196,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout': { @@ -231,40 +210,33 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport + parentRoute: typeof rootRouteImport } '/_pathlessLayout/_nested-layout': { id: '/_pathlessLayout/_nested-layout' @@ -273,12 +245,40 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport parentRoute: typeof PathlessLayoutRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport - parentRoute: typeof rootRouteImport + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute + } + '/users/$userId': { + id: '/users/$userId' + path: '/$userId' + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -287,12 +287,12 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/examples/solid/start-basic/package.json b/examples/solid/start-basic/package.json index 2c7d7936d5..758815b669 100644 --- a/examples/solid/start-basic/package.json +++ b/examples/solid/start-basic/package.json @@ -10,9 +10,9 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.28", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwind-merge": "^3.6.0" @@ -20,9 +20,10 @@ "devDependencies": { "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", - "nitro": "^3.0.260311-beta", + "nitro": "^3.0.260903-beta", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/start-basic/src/routeTree.gen.ts b/examples/solid/start-basic/src/routeTree.gen.ts index 722133b41e..8d6c8ffc2b 100644 --- a/examples/solid/start-basic/src/routeTree.gen.ts +++ b/examples/solid/start-basic/src/routeTree.gen.ts @@ -9,36 +9,30 @@ // 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 UsersRouteImport } from './routes/users' -import { Route as RedirectRouteImport } from './routes/redirect' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as DeferredRouteImport } from './routes/deferred' -import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' import { Route as IndexRouteImport } from './routes/index' -import { Route as UsersIndexRouteImport } from './routes/users.index' -import { Route as PostsIndexRouteImport } from './routes/posts.index' -import { Route as UsersUserIdRouteImport } from './routes/users.$userId' -import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PathlessLayoutRouteImport } from './routes/_pathlessLayout' +import { Route as DeferredRouteImport } from './routes/deferred' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RedirectRouteImport } from './routes/redirect' +import { Route as UsersRouteImport } from './routes/users' import { Route as PathlessLayoutNestedLayoutRouteImport } from './routes/_pathlessLayout/_nested-layout' -import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' -import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersRouteImport } from './routes/api/users' +import { Route as PostsIndexRouteImport } from './routes/posts.index' +import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' +import { Route as UsersIndexRouteImport } from './routes/users.index' +import { Route as UsersUserIdRouteImport } from './routes/users.$userId' import { Route as PathlessLayoutNestedLayoutRouteARouteImport } from './routes/_pathlessLayout/_nested-layout/route-a' +import { Route as PathlessLayoutNestedLayoutRouteBRouteImport } from './routes/_pathlessLayout/_nested-layout/route-b' +import { Route as ApiUsersUserIdRouteImport } from './routes/api/users.$userId' +import { Route as PostsPostIdDeepRouteImport } from './routes/posts_.$postId.deep' -const UsersRoute = UsersRouteImport.update({ - id: '/users', - path: '/users', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const RedirectRoute = RedirectRouteImport.update({ - id: '/redirect', - path: '/redirect', - getParentRoute: () => rootRouteImport, -} as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ + id: '/_pathlessLayout', getParentRoute: () => rootRouteImport, } as any) const DeferredRoute = DeferredRouteImport.update({ @@ -46,38 +40,19 @@ const DeferredRoute = DeferredRouteImport.update({ path: '/deferred', getParentRoute: () => rootRouteImport, } as any) -const PathlessLayoutRoute = PathlessLayoutRouteImport.update({ - id: '/_pathlessLayout', +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const RedirectRoute = RedirectRouteImport.update({ + id: '/redirect', + path: '/redirect', getParentRoute: () => rootRouteImport, } as any) -const UsersIndexRoute = UsersIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => UsersRoute, -} as any) -const PostsIndexRoute = PostsIndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => PostsRoute, -} as any) -const UsersUserIdRoute = UsersUserIdRouteImport.update({ - id: '/$userId', - path: '/$userId', - getParentRoute: () => UsersRoute, -} as any) -const PostsPostIdRoute = PostsPostIdRouteImport.update({ - id: '/$postId', - path: '/$postId', - getParentRoute: () => PostsRoute, -} as any) -const ApiUsersRoute = ApiUsersRouteImport.update({ - id: '/api/users', - path: '/api/users', +const UsersRoute = UsersRouteImport.update({ + id: '/users', + path: '/users', getParentRoute: () => rootRouteImport, } as any) const PathlessLayoutNestedLayoutRoute = @@ -85,28 +60,53 @@ const PathlessLayoutNestedLayoutRoute = id: '/_nested-layout', getParentRoute: () => PathlessLayoutRoute, } as any) -const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ - id: '/posts_/$postId/deep', - path: '/posts/$postId/deep', +const ApiUsersRoute = ApiUsersRouteImport.update({ + id: '/api/users', + path: '/api/users', getParentRoute: () => rootRouteImport, } as any) -const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ +const PostsIndexRoute = PostsIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => PostsRoute, +} as any) +const PostsPostIdRoute = PostsPostIdRouteImport.update({ + id: '/$postId', + path: '/$postId', + getParentRoute: () => PostsRoute, +} as any) +const UsersIndexRoute = UsersIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => UsersRoute, +} as any) +const UsersUserIdRoute = UsersUserIdRouteImport.update({ id: '/$userId', path: '/$userId', - getParentRoute: () => ApiUsersRoute, + getParentRoute: () => UsersRoute, } as any) -const PathlessLayoutNestedLayoutRouteBRoute = - PathlessLayoutNestedLayoutRouteBRouteImport.update({ - id: '/route-b', - path: '/route-b', - getParentRoute: () => PathlessLayoutNestedLayoutRoute, - } as any) const PathlessLayoutNestedLayoutRouteARoute = PathlessLayoutNestedLayoutRouteARouteImport.update({ id: '/route-a', path: '/route-a', getParentRoute: () => PathlessLayoutNestedLayoutRoute, } as any) +const PathlessLayoutNestedLayoutRouteBRoute = + PathlessLayoutNestedLayoutRouteBRouteImport.update({ + id: '/route-b', + path: '/route-b', + getParentRoute: () => PathlessLayoutNestedLayoutRoute, + } as any) +const ApiUsersUserIdRoute = ApiUsersUserIdRouteImport.update({ + id: '/$userId', + path: '/$userId', + getParentRoute: () => ApiUsersRoute, +} as any) +const PostsPostIdDeepRoute = PostsPostIdDeepRouteImport.update({ + id: '/posts_/$postId/deep', + path: '/posts/$postId/deep', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -221,32 +221,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/users': { - id: '/users' - path: '/users' - fullPath: '/users' - preLoaderRoute: typeof UsersRouteImport - parentRoute: typeof rootRouteImport - } - '/redirect': { - id: '/redirect' - path: '/redirect' - fullPath: '/redirect' - preLoaderRoute: typeof RedirectRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/deferred': { - id: '/deferred' - path: '/deferred' - fullPath: '/deferred' - preLoaderRoute: typeof DeferredRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout': { @@ -256,46 +235,32 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/deferred': { + id: '/deferred' + path: '/deferred' + fullPath: '/deferred' + preLoaderRoute: typeof DeferredRouteImport parentRoute: typeof rootRouteImport } - '/users/': { - id: '/users/' - path: '/' - fullPath: '/users/' - preLoaderRoute: typeof UsersIndexRouteImport - parentRoute: typeof UsersRoute + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport } - '/posts/': { - id: '/posts/' - path: '/' - fullPath: '/posts/' - preLoaderRoute: typeof PostsIndexRouteImport - parentRoute: typeof PostsRoute + '/redirect': { + id: '/redirect' + path: '/redirect' + fullPath: '/redirect' + preLoaderRoute: typeof RedirectRouteImport + parentRoute: typeof rootRouteImport } - '/users/$userId': { - id: '/users/$userId' - path: '/$userId' - fullPath: '/users/$userId' - preLoaderRoute: typeof UsersUserIdRouteImport - parentRoute: typeof UsersRoute - } - '/posts/$postId': { - id: '/posts/$postId' - path: '/$postId' - fullPath: '/posts/$postId' - preLoaderRoute: typeof PostsPostIdRouteImport - parentRoute: typeof PostsRoute - } - '/api/users': { - id: '/api/users' - path: '/api/users' - fullPath: '/api/users' - preLoaderRoute: typeof ApiUsersRouteImport + '/users': { + id: '/users' + path: '/users' + fullPath: '/users' + preLoaderRoute: typeof UsersRouteImport parentRoute: typeof rootRouteImport } '/_pathlessLayout/_nested-layout': { @@ -305,19 +270,47 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteImport parentRoute: typeof PathlessLayoutRoute } - '/posts_/$postId/deep': { - id: '/posts_/$postId/deep' - path: '/posts/$postId/deep' - fullPath: '/posts/$postId/deep' - preLoaderRoute: typeof PostsPostIdDeepRouteImport + '/api/users': { + id: '/api/users' + path: '/api/users' + fullPath: '/api/users' + preLoaderRoute: typeof ApiUsersRouteImport parentRoute: typeof rootRouteImport } - '/api/users/$userId': { - id: '/api/users/$userId' + '/posts/': { + id: '/posts/' + path: '/' + fullPath: '/posts/' + preLoaderRoute: typeof PostsIndexRouteImport + parentRoute: typeof PostsRoute + } + '/posts/$postId': { + id: '/posts/$postId' + path: '/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof PostsPostIdRouteImport + parentRoute: typeof PostsRoute + } + '/users/': { + id: '/users/' + path: '/' + fullPath: '/users/' + preLoaderRoute: typeof UsersIndexRouteImport + parentRoute: typeof UsersRoute + } + '/users/$userId': { + id: '/users/$userId' path: '/$userId' - fullPath: '/api/users/$userId' - preLoaderRoute: typeof ApiUsersUserIdRouteImport - parentRoute: typeof ApiUsersRoute + fullPath: '/users/$userId' + preLoaderRoute: typeof UsersUserIdRouteImport + parentRoute: typeof UsersRoute + } + '/_pathlessLayout/_nested-layout/route-a': { + id: '/_pathlessLayout/_nested-layout/route-a' + path: '/route-a' + fullPath: '/route-a' + preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport + parentRoute: typeof PathlessLayoutNestedLayoutRoute } '/_pathlessLayout/_nested-layout/route-b': { id: '/_pathlessLayout/_nested-layout/route-b' @@ -326,12 +319,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteBRouteImport parentRoute: typeof PathlessLayoutNestedLayoutRoute } - '/_pathlessLayout/_nested-layout/route-a': { - id: '/_pathlessLayout/_nested-layout/route-a' - path: '/route-a' - fullPath: '/route-a' - preLoaderRoute: typeof PathlessLayoutNestedLayoutRouteARouteImport - parentRoute: typeof PathlessLayoutNestedLayoutRoute + '/api/users/$userId': { + id: '/api/users/$userId' + path: '/$userId' + fullPath: '/api/users/$userId' + preLoaderRoute: typeof ApiUsersUserIdRouteImport + parentRoute: typeof ApiUsersRoute + } + '/posts_/$postId/deep': { + id: '/posts_/$postId/deep' + path: '/posts/$postId/deep' + fullPath: '/posts/$postId/deep' + preLoaderRoute: typeof PostsPostIdDeepRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/examples/solid/start-bun/package.json b/examples/solid/start-bun/package.json index 7ae945fa42..d1ad9a9563 100644 --- a/examples/solid/start-bun/package.json +++ b/examples/solid/start-bun/package.json @@ -15,11 +15,11 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/solid-devtools": "^0.7.0", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-router-ssr-query": "^1.167.1", - "@tanstack/solid-start": "^1.168.28", - "@tanstack/router-plugin": "^1.168.20", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-router-ssr-query": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", + "@tanstack/router-plugin": "^1.169.0", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2" }, @@ -32,9 +32,10 @@ "vite-plugin-solid": "^2.11.11", "jsdom": "^27.0.0", "prettier": "^3.6.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", - "vitest": "^4.1.4", + "vitest": "^5.0.4", "web-vitals": "^5.1.0" } } diff --git a/examples/solid/start-bun/src/routeTree.gen.ts b/examples/solid/start-bun/src/routeTree.gen.ts index 19009b2f5b..353db2cd02 100644 --- a/examples/solid/start-bun/src/routeTree.gen.ts +++ b/examples/solid/start-bun/src/routeTree.gen.ts @@ -11,8 +11,8 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' import { Route as ApiDemoNamesRouteImport } from './routes/api.demo-names' -import { Route as DemoStartServerFuncsRouteImport } from './routes/demo.start.server-funcs' import { Route as DemoStartApiRequestRouteImport } from './routes/demo.start.api-request' +import { Route as DemoStartServerFuncsRouteImport } from './routes/demo.start.server-funcs' const IndexRoute = IndexRouteImport.update({ id: '/', @@ -24,16 +24,16 @@ const ApiDemoNamesRoute = ApiDemoNamesRouteImport.update({ path: '/api/demo-names', getParentRoute: () => rootRouteImport, } as any) -const DemoStartServerFuncsRoute = DemoStartServerFuncsRouteImport.update({ - id: '/demo/start/server-funcs', - path: '/demo/start/server-funcs', - getParentRoute: () => rootRouteImport, -} as any) const DemoStartApiRequestRoute = DemoStartApiRequestRouteImport.update({ id: '/demo/start/api-request', path: '/demo/start/api-request', getParentRoute: () => rootRouteImport, } as any) +const DemoStartServerFuncsRoute = DemoStartServerFuncsRouteImport.update({ + id: '/demo/start/server-funcs', + path: '/demo/start/server-funcs', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -98,13 +98,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ApiDemoNamesRouteImport parentRoute: typeof rootRouteImport } - '/demo/start/server-funcs': { - id: '/demo/start/server-funcs' - path: '/demo/start/server-funcs' - fullPath: '/demo/start/server-funcs' - preLoaderRoute: typeof DemoStartServerFuncsRouteImport - parentRoute: typeof rootRouteImport - } '/demo/start/api-request': { id: '/demo/start/api-request' path: '/demo/start/api-request' @@ -112,6 +105,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DemoStartApiRequestRouteImport parentRoute: typeof rootRouteImport } + '/demo/start/server-funcs': { + id: '/demo/start/server-funcs' + path: '/demo/start/server-funcs' + fullPath: '/demo/start/server-funcs' + preLoaderRoute: typeof DemoStartServerFuncsRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/start-convex-better-auth/package.json b/examples/solid/start-convex-better-auth/package.json index 7924c5e68d..ea13a1c1e3 100644 --- a/examples/solid/start-convex-better-auth/package.json +++ b/examples/solid/start-convex-better-auth/package.json @@ -13,9 +13,9 @@ "dependencies": { "@convex-dev/better-auth": "^0.9.7", "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.28", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "better-auth": "^1.6.19", "clsx": "^2.1.1", "convex": "^1.28.2", @@ -29,7 +29,8 @@ "devDependencies": { "@types/node": "^22.10.2", "combinate": "^1.1.11", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/start-convex-better-auth/src/routeTree.gen.ts b/examples/solid/start-convex-better-auth/src/routeTree.gen.ts index 27dc0ca88c..d2307d1277 100644 --- a/examples/solid/start-convex-better-auth/src/routeTree.gen.ts +++ b/examples/solid/start-convex-better-auth/src/routeTree.gen.ts @@ -9,24 +9,24 @@ // 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 AboutRouteImport } from './routes/about' -import { Route as AuthedRouteImport } from './routes/_authed' import { Route as IndexRouteImport } from './routes/index' +import { Route as AuthedRouteImport } from './routes/_authed' +import { Route as AboutRouteImport } from './routes/about' import { Route as AuthedDashboardRouteImport } from './routes/_authed/dashboard' import { Route as ApiAuthSplatRouteImport } from './routes/api/auth/$' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AuthedRoute = AuthedRouteImport.update({ id: '/_authed', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', getParentRoute: () => rootRouteImport, } as any) const AuthedDashboardRoute = AuthedDashboardRouteImport.update({ @@ -83,11 +83,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_authed': { @@ -97,11 +97,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AuthedRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } '/_authed/dashboard': { diff --git a/examples/solid/start-counter/package.json b/examples/solid/start-counter/package.json index 0f5ea8e496..8b49c516bd 100644 --- a/examples/solid/start-counter/package.json +++ b/examples/solid/start-counter/package.json @@ -10,9 +10,9 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.28", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwind-merge": "^3.6.0", @@ -21,7 +21,8 @@ "devDependencies": { "@types/node": "^22.10.2", "combinate": "^1.1.11", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/start-counter/src/routeTree.gen.ts b/examples/solid/start-counter/src/routeTree.gen.ts index 3cc45c071e..7495244535 100644 --- a/examples/solid/start-counter/src/routeTree.gen.ts +++ b/examples/solid/start-counter/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/start-i18n-paraglide/package.json b/examples/solid/start-i18n-paraglide/package.json index d81127d045..076c9b41dc 100644 --- a/examples/solid/start-i18n-paraglide/package.json +++ b/examples/solid/start-i18n-paraglide/package.json @@ -10,18 +10,30 @@ }, "dependencies": { "@tanstack/solid-devtools": "^0.7.0", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.28", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "solid-js": "^1.9.10" }, "devDependencies": { "@types/node": "^22.18.6", "vite-plugin-solid": "^2.11.11", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "@tailwindcss/vite": "^4.2.2", "tailwindcss": "^4.2.2", "@inlang/paraglide-js": "^2.4.0" + }, + "nx": { + "targets": { + "build": { + "outputs": [ + "...", + "{projectRoot}/src/paraglide", + "{projectRoot}/project.inlang/cache" + ] + } + } } } diff --git a/examples/solid/start-i18n-paraglide/src/routeTree.gen.ts b/examples/solid/start-i18n-paraglide/src/routeTree.gen.ts index 3cc45c071e..7495244535 100644 --- a/examples/solid/start-i18n-paraglide/src/routeTree.gen.ts +++ b/examples/solid/start-i18n-paraglide/src/routeTree.gen.ts @@ -9,19 +9,19 @@ // 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 AboutRouteImport } from './routes/about' import { Route as IndexRouteImport } from './routes/index' +import { Route as AboutRouteImport } from './routes/about' -const AboutRoute = AboutRouteImport.update({ - id: '/about', - path: '/about', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -51,13 +51,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/about': { - id: '/about' - path: '/about' - fullPath: '/about' - preLoaderRoute: typeof AboutRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/examples/solid/start-large/package.json b/examples/solid/start-large/package.json index 0e941745d5..83f3589cc2 100644 --- a/examples/solid/start-large/package.json +++ b/examples/solid/start-large/package.json @@ -13,9 +13,9 @@ }, "dependencies": { "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.28", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwind-merge": "^3.6.0", @@ -25,7 +25,8 @@ "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" }, diff --git a/examples/solid/start-large/src/routeTree.gen.ts b/examples/solid/start-large/src/routeTree.gen.ts index 3fb99e1aca..1febe90621 100644 --- a/examples/solid/start-large/src/routeTree.gen.ts +++ b/examples/solid/start-large/src/routeTree.gen.ts @@ -9,23 +9,18 @@ // 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 RelativeRouteImport } from './routes/relative' -import { Route as LinkPropsRouteImport } from './routes/linkProps' -import { Route as AbsoluteRouteImport } from './routes/absolute' -import { Route as SearchRouteRouteImport } from './routes/search/route' -import { Route as ParamsRouteRouteImport } from './routes/params/route' import { Route as IndexRouteImport } from './routes/index' -import { Route as SearchSearchPlaceholderRouteImport } from './routes/search/searchPlaceholder' +import { Route as AbsoluteRouteImport } from './routes/absolute' +import { Route as LinkPropsRouteImport } from './routes/linkProps' +import { Route as ParamsRouteRouteImport } from './routes/params/route' +import { Route as RelativeRouteImport } from './routes/relative' +import { Route as SearchRouteRouteImport } from './routes/search/route' import { Route as ParamsParamsPlaceholderRouteImport } from './routes/params/$paramsPlaceholder' +import { Route as SearchSearchPlaceholderRouteImport } from './routes/search/searchPlaceholder' -const RelativeRoute = RelativeRouteImport.update({ - id: '/relative', - path: '/relative', - getParentRoute: () => rootRouteImport, -} as any) -const LinkPropsRoute = LinkPropsRouteImport.update({ - id: '/linkProps', - path: '/linkProps', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const AbsoluteRoute = AbsoluteRouteImport.update({ @@ -33,9 +28,9 @@ const AbsoluteRoute = AbsoluteRouteImport.update({ path: '/absolute', getParentRoute: () => rootRouteImport, } as any) -const SearchRouteRoute = SearchRouteRouteImport.update({ - id: '/search', - path: '/search', +const LinkPropsRoute = LinkPropsRouteImport.update({ + id: '/linkProps', + path: '/linkProps', getParentRoute: () => rootRouteImport, } as any) const ParamsRouteRoute = ParamsRouteRouteImport.update({ @@ -43,21 +38,26 @@ const ParamsRouteRoute = ParamsRouteRouteImport.update({ path: '/params', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const RelativeRoute = RelativeRouteImport.update({ + id: '/relative', + path: '/relative', getParentRoute: () => rootRouteImport, } as any) -const SearchSearchPlaceholderRoute = SearchSearchPlaceholderRouteImport.update({ - id: '/searchPlaceholder', - path: '/searchPlaceholder', - getParentRoute: () => SearchRouteRoute, +const SearchRouteRoute = SearchRouteRouteImport.update({ + id: '/search', + path: '/search', + getParentRoute: () => rootRouteImport, } as any) const ParamsParamsPlaceholderRoute = ParamsParamsPlaceholderRouteImport.update({ id: '/$paramsPlaceholder', path: '/$paramsPlaceholder', getParentRoute: () => ParamsRouteRoute, } as any) +const SearchSearchPlaceholderRoute = SearchSearchPlaceholderRouteImport.update({ + id: '/searchPlaceholder', + path: '/searchPlaceholder', + getParentRoute: () => SearchRouteRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -134,18 +134,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/relative': { - id: '/relative' - path: '/relative' - fullPath: '/relative' - preLoaderRoute: typeof RelativeRouteImport - parentRoute: typeof rootRouteImport - } - '/linkProps': { - id: '/linkProps' - path: '/linkProps' - fullPath: '/linkProps' - preLoaderRoute: typeof LinkPropsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/absolute': { @@ -155,11 +148,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AbsoluteRouteImport parentRoute: typeof rootRouteImport } - '/search': { - id: '/search' - path: '/search' - fullPath: '/search' - preLoaderRoute: typeof SearchRouteRouteImport + '/linkProps': { + id: '/linkProps' + path: '/linkProps' + fullPath: '/linkProps' + preLoaderRoute: typeof LinkPropsRouteImport parentRoute: typeof rootRouteImport } '/params': { @@ -169,19 +162,19 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ParamsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/relative': { + id: '/relative' + path: '/relative' + fullPath: '/relative' + preLoaderRoute: typeof RelativeRouteImport parentRoute: typeof rootRouteImport } - '/search/searchPlaceholder': { - id: '/search/searchPlaceholder' - path: '/searchPlaceholder' - fullPath: '/search/searchPlaceholder' - preLoaderRoute: typeof SearchSearchPlaceholderRouteImport - parentRoute: typeof SearchRouteRoute + '/search': { + id: '/search' + path: '/search' + fullPath: '/search' + preLoaderRoute: typeof SearchRouteRouteImport + parentRoute: typeof rootRouteImport } '/params/$paramsPlaceholder': { id: '/params/$paramsPlaceholder' @@ -190,6 +183,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ParamsParamsPlaceholderRouteImport parentRoute: typeof ParamsRouteRoute } + '/search/searchPlaceholder': { + id: '/search/searchPlaceholder' + path: '/searchPlaceholder' + fullPath: '/search/searchPlaceholder' + preLoaderRoute: typeof SearchSearchPlaceholderRouteImport + parentRoute: typeof SearchRouteRoute + } } } diff --git a/examples/solid/start-streaming-data-from-server-functions/package.json b/examples/solid/start-streaming-data-from-server-functions/package.json index 6ca3946475..83e0719b39 100644 --- a/examples/solid/start-streaming-data-from-server-functions/package.json +++ b/examples/solid/start-streaming-data-from-server-functions/package.json @@ -10,15 +10,16 @@ "start": "pnpx srvx --prod -s ../client dist/server/server.js" }, "dependencies": { - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.28", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "solid-js": "^1.9.10", "zod": "^4.4.3" }, "devDependencies": { "@types/node": "^22.5.4", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/start-supabase-basic/package.json b/examples/solid/start-supabase-basic/package.json index a003a3eb47..81ab5cd63c 100644 --- a/examples/solid/start-supabase-basic/package.json +++ b/examples/solid/start-supabase-basic/package.json @@ -14,9 +14,9 @@ "dependencies": { "@supabase/ssr": "^0.5.2", "@supabase/supabase-js": "^2.48.1", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.28", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "solid-js": "^1.9.9", "redaxios": "^0.5.1" }, @@ -24,7 +24,8 @@ "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/start-supabase-basic/src/routeTree.gen.ts b/examples/solid/start-supabase-basic/src/routeTree.gen.ts index 7019a6c21a..bbebb19df3 100644 --- a/examples/solid/start-supabase-basic/src/routeTree.gen.ts +++ b/examples/solid/start-supabase-basic/src/routeTree.gen.ts @@ -9,23 +9,22 @@ // 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 SignupRouteImport } from './routes/signup' -import { Route as LogoutRouteImport } from './routes/logout' -import { Route as LoginRouteImport } from './routes/login' -import { Route as AuthedRouteImport } from './routes/_authed' import { Route as IndexRouteImport } from './routes/index' +import { Route as AuthedRouteImport } from './routes/_authed' +import { Route as LoginRouteImport } from './routes/login' +import { Route as LogoutRouteImport } from './routes/logout' +import { Route as SignupRouteImport } from './routes/signup' import { Route as AuthedPostsRouteImport } from './routes/_authed/posts' import { Route as AuthedPostsIndexRouteImport } from './routes/_authed/posts.index' import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' -const SignupRoute = SignupRouteImport.update({ - id: '/signup', - path: '/signup', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) -const LogoutRoute = LogoutRouteImport.update({ - id: '/logout', - path: '/logout', +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', getParentRoute: () => rootRouteImport, } as any) const LoginRoute = LoginRouteImport.update({ @@ -33,13 +32,14 @@ const LoginRoute = LoginRouteImport.update({ path: '/login', getParentRoute: () => rootRouteImport, } as any) -const AuthedRoute = AuthedRouteImport.update({ - id: '/_authed', +const LogoutRoute = LogoutRouteImport.update({ + id: '/logout', + path: '/logout', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SignupRoute = SignupRouteImport.update({ + id: '/signup', + path: '/signup', getParentRoute: () => rootRouteImport, } as any) const AuthedPostsRoute = AuthedPostsRouteImport.update({ @@ -120,25 +120,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/signup': { - id: '/signup' - path: '/signup' - fullPath: '/signup' - preLoaderRoute: typeof SignupRouteImport - parentRoute: typeof rootRouteImport - } - '/logout': { - id: '/logout' - path: '/logout' - fullPath: '/logout' - preLoaderRoute: typeof LogoutRouteImport - parentRoute: typeof rootRouteImport - } - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_authed': { @@ -148,11 +134,25 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AuthedRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport + } + '/logout': { + id: '/logout' + path: '/logout' + fullPath: '/logout' + preLoaderRoute: typeof LogoutRouteImport + parentRoute: typeof rootRouteImport + } + '/signup': { + id: '/signup' + path: '/signup' + fullPath: '/signup' + preLoaderRoute: typeof SignupRouteImport parentRoute: typeof rootRouteImport } '/_authed/posts': { diff --git a/examples/solid/start-tailwind-v4/package.json b/examples/solid/start-tailwind-v4/package.json index 57adb50957..94db6ac790 100644 --- a/examples/solid/start-tailwind-v4/package.json +++ b/examples/solid/start-tailwind-v4/package.json @@ -10,9 +10,9 @@ "start": "node .output/server/index.mjs" }, "dependencies": { - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.28", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", + "@tanstack/solid-start": "^1.169.6", "solid-js": "^1.9.10", "tailwind-merge": "^3.6.0", "zod": "^4.4.3" @@ -21,7 +21,8 @@ "@tailwindcss/vite": "^4.2.2", "@types/node": "^22.5.4", "tailwindcss": "^4.2.2", - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/start-tailwind-v4/src/routes/__root.tsx b/examples/solid/start-tailwind-v4/src/routes/__root.tsx index 8347bb3b5a..489680b739 100644 --- a/examples/solid/start-tailwind-v4/src/routes/__root.tsx +++ b/examples/solid/start-tailwind-v4/src/routes/__root.tsx @@ -7,7 +7,6 @@ import { createRootRoute, } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' -import * as React from 'react' import { HydrationScript } from 'solid-js/web' import type { JSX } from 'solid-js' import appCss from '~/styles/app.css?url' diff --git a/examples/solid/view-transitions/package.json b/examples/solid/view-transitions/package.json index cf4631b96f..2acb2432bf 100644 --- a/examples/solid/view-transitions/package.json +++ b/examples/solid/view-transitions/package.json @@ -10,16 +10,17 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.168.20", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, "devDependencies": { - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/view-transitions/src/routeTree.gen.ts b/examples/solid/view-transitions/src/routeTree.gen.ts index 114e34ed9d..01843027dc 100644 --- a/examples/solid/view-transitions/src/routeTree.gen.ts +++ b/examples/solid/view-transitions/src/routeTree.gen.ts @@ -9,16 +9,16 @@ // 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 HowItWorksRouteImport } from './routes/how-it-works' -import { Route as ExploreRouteImport } from './routes/explore' -import { Route as PostsRouteRouteImport } from './routes/posts.route' import { Route as IndexRouteImport } from './routes/index' +import { Route as ExploreRouteImport } from './routes/explore' +import { Route as HowItWorksRouteImport } from './routes/how-it-works' +import { Route as PostsRouteRouteImport } from './routes/posts.route' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -const HowItWorksRoute = HowItWorksRouteImport.update({ - id: '/how-it-works', - path: '/how-it-works', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const ExploreRoute = ExploreRouteImport.update({ @@ -26,16 +26,16 @@ const ExploreRoute = ExploreRouteImport.update({ path: '/explore', getParentRoute: () => rootRouteImport, } as any) +const HowItWorksRoute = HowItWorksRouteImport.update({ + id: '/how-it-works', + path: '/how-it-works', + getParentRoute: () => rootRouteImport, +} as any) const PostsRouteRoute = PostsRouteRouteImport.update({ id: '/posts', path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -101,11 +101,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/how-it-works': { - id: '/how-it-works' - path: '/how-it-works' - fullPath: '/how-it-works' - preLoaderRoute: typeof HowItWorksRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/explore': { @@ -115,6 +115,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ExploreRouteImport parentRoute: typeof rootRouteImport } + '/how-it-works': { + id: '/how-it-works' + path: '/how-it-works' + fullPath: '/how-it-works' + preLoaderRoute: typeof HowItWorksRouteImport + parentRoute: typeof rootRouteImport + } '/posts': { id: '/posts' path: '/posts' @@ -122,13 +129,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PostsRouteRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/posts/': { id: '/posts/' path: '/' diff --git a/examples/solid/with-framer-motion/package.json b/examples/solid/with-framer-motion/package.json index 898d248ec9..449d8a3927 100644 --- a/examples/solid/with-framer-motion/package.json +++ b/examples/solid/with-framer-motion/package.json @@ -10,8 +10,8 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "solid-js": "^1.9.10", "solid-motionone": "^1.0.4", @@ -19,7 +19,8 @@ "zod": "^4.4.3" }, "devDependencies": { - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" } diff --git a/examples/solid/with-trpc/package.json b/examples/solid/with-trpc/package.json index 8b68448842..46d33436db 100644 --- a/examples/solid/with-trpc/package.json +++ b/examples/solid/with-trpc/package.json @@ -11,9 +11,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.168.20", - "@tanstack/solid-router": "^1.170.18", - "@tanstack/solid-router-devtools": "^1.167.0", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/solid-router": "^1.170.43", + "@tanstack/solid-router-devtools": "^1.167.3", "@trpc/client": "^11.4.3", "@trpc/server": "^11.4.3", "express": "^5.2.1", diff --git a/examples/solid/with-trpc/src/routeTree.gen.ts b/examples/solid/with-trpc/src/routeTree.gen.ts index fd93507694..aa08570aca 100644 --- a/examples/solid/with-trpc/src/routeTree.gen.ts +++ b/examples/solid/with-trpc/src/routeTree.gen.ts @@ -9,23 +9,23 @@ // 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 DashboardRouteImport } from './routes/dashboard' import { Route as IndexRouteImport } from './routes/index' +import { Route as DashboardRouteImport } from './routes/dashboard' import { Route as DashboardIndexRouteImport } from './routes/dashboard.index' import { Route as DashboardPostsRouteImport } from './routes/dashboard.posts' import { Route as DashboardPostsIndexRouteImport } from './routes/dashboard.posts.index' import { Route as DashboardPostsPostIdRouteImport } from './routes/dashboard.posts.$postId' -const DashboardRoute = DashboardRouteImport.update({ - id: '/dashboard', - path: '/dashboard', - getParentRoute: () => rootRouteImport, -} as any) const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) +const DashboardRoute = DashboardRouteImport.update({ + id: '/dashboard', + path: '/dashboard', + getParentRoute: () => rootRouteImport, +} as any) const DashboardIndexRoute = DashboardIndexRouteImport.update({ id: '/', path: '/', @@ -98,13 +98,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/dashboard': { - id: '/dashboard' - path: '/dashboard' - fullPath: '/dashboard' - preLoaderRoute: typeof DashboardRouteImport - parentRoute: typeof rootRouteImport - } '/': { id: '/' path: '/' @@ -112,6 +105,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } + '/dashboard': { + id: '/dashboard' + path: '/dashboard' + fullPath: '/dashboard' + preLoaderRoute: typeof DashboardRouteImport + parentRoute: typeof rootRouteImport + } '/dashboard/': { id: '/dashboard/' path: '/' diff --git a/examples/vue/basic-file-based-jsx/package.json b/examples/vue/basic-file-based-jsx/package.json index fdeefd2f88..9cc36a6991 100644 --- a/examples/vue/basic-file-based-jsx/package.json +++ b/examples/vue/basic-file-based-jsx/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.168.20", - "@tanstack/vue-router": "^1.170.17", - "@tanstack/vue-router-devtools": "^1.167.0", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/vue-router": "^1.170.42", + "@tanstack/vue-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", "vue": "^3.5.16", @@ -28,6 +28,6 @@ "typescript": "~5.8.3", "vite": "^8.0.14", "vue-eslint-parser": "^9.4.3", - "vue-tsc": "^3.1.5" + "vue-tsc": "^3.3.8" } } diff --git a/examples/vue/basic-file-based-jsx/src/posts.tsx b/examples/vue/basic-file-based-jsx/src/posts.tsx index 1b4c92b41d..f7a1941605 100644 --- a/examples/vue/basic-file-based-jsx/src/posts.tsx +++ b/examples/vue/basic-file-based-jsx/src/posts.tsx @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/examples/vue/basic-file-based-jsx/src/routeTree.gen.ts b/examples/vue/basic-file-based-jsx/src/routeTree.gen.ts index f5cd519d7f..5922c5f7b1 100644 --- a/examples/vue/basic-file-based-jsx/src/routeTree.gen.ts +++ b/examples/vue/basic-file-based-jsx/src/routeTree.gen.ts @@ -11,34 +11,62 @@ import { lazyRouteComponent } from '@tanstack/vue-router' import { Route as rootRouteImport } from './routes/__root' -import { Route as Char45824Char54620Char48124Char44397RouteImport } from './routes/대한민국' -import { Route as SfcComponentRouteImport } from './routes/sfcComponent' -import { Route as RemountDepsRouteImport } from './routes/remountDeps' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as NotRemountDepsRouteImport } from './routes/notRemountDeps' -import { Route as EditingBRouteImport } from './routes/editing-b' -import { Route as EditingARouteImport } from './routes/editing-a' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as IndexRouteImport } from './routes/index' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as EditingARouteImport } from './routes/editing-a' +import { Route as EditingBRouteImport } from './routes/editing-b' +import { Route as NotRemountDepsRouteImport } from './routes/notRemountDeps' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RemountDepsRouteImport } from './routes/remountDeps' +import { Route as SfcComponentRouteImport } from './routes/sfcComponent' +import { Route as Char45824Char54620Char48124Char44397RouteImport } from './routes/대한민국' +import { Route as anotherGroupOnlyrouteinsideRouteImport } from './routes/(another-group)/onlyrouteinside' +import { Route as groupLayoutRouteImport } from './routes/(group)/_layout' +import { Route as groupInsideRouteImport } from './routes/(group)/inside' +import { Route as groupLazyinsideRouteImport } from './routes/(group)/lazyinside' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as groupLazyinsideRouteImport } from './routes/(group)/lazyinside' -import { Route as groupInsideRouteImport } from './routes/(group)/inside' -import { Route as groupLayoutRouteImport } from './routes/(group)/_layout' -import { Route as anotherGroupOnlyrouteinsideRouteImport } from './routes/(another-group)/onlyrouteinside' -import { Route as PostsPostIdEditRouteImport } from './routes/posts_.$postId.edit' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' -import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -import { Route as groupSubfolderInsideRouteImport } from './routes/(group)/subfolder/inside' import { Route as groupLayoutInsidelayoutRouteImport } from './routes/(group)/_layout.insidelayout' +import { Route as groupSubfolderInsideRouteImport } from './routes/(group)/subfolder/inside' +import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as PostsPostIdEditRouteImport } from './routes/posts_.$postId.edit' -const Char45824Char54620Char48124Char44397Route = - Char45824Char54620Char48124Char44397RouteImport.update({ - id: '/대한민국', - path: '/대한민국', - getParentRoute: () => rootRouteImport, - } as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const EditingARoute = EditingARouteImport.update({ + id: '/editing-a', + path: '/editing-a', + getParentRoute: () => rootRouteImport, +} as any) +const EditingBRoute = EditingBRouteImport.update({ + id: '/editing-b', + path: '/editing-b', + getParentRoute: () => rootRouteImport, +} as any) +const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ + id: '/notRemountDeps', + path: '/notRemountDeps', + getParentRoute: () => rootRouteImport, +} as any) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any) +const RemountDepsRoute = RemountDepsRouteImport.update({ + id: '/remountDeps', + path: '/remountDeps', + getParentRoute: () => rootRouteImport, +} as any) const SfcComponentRoute = SfcComponentRouteImport.update({ id: '/sfcComponent', path: '/sfcComponent', @@ -49,39 +77,35 @@ const SfcComponentRoute = SfcComponentRouteImport.update({ 'default', ), }) -const RemountDepsRoute = RemountDepsRouteImport.update({ - id: '/remountDeps', - path: '/remountDeps', +const Char45824Char54620Char48124Char44397Route = + Char45824Char54620Char48124Char44397RouteImport.update({ + id: '/대한민국', + path: '/대한민국', + getParentRoute: () => rootRouteImport, + } as any) +const anotherGroupOnlyrouteinsideRoute = + anotherGroupOnlyrouteinsideRouteImport.update({ + id: '/(another-group)/onlyrouteinside', + path: '/onlyrouteinside', + getParentRoute: () => rootRouteImport, + } as any) +const groupLayoutRoute = groupLayoutRouteImport.update({ + id: '/(group)/_layout', getParentRoute: () => rootRouteImport, } as any) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const groupInsideRoute = groupInsideRouteImport.update({ + id: '/(group)/inside', + path: '/inside', getParentRoute: () => rootRouteImport, } as any) -const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ - id: '/notRemountDeps', - path: '/notRemountDeps', +const groupLazyinsideRoute = groupLazyinsideRouteImport.update({ + id: '/(group)/lazyinside', + path: '/lazyinside', getParentRoute: () => rootRouteImport, } as any) -const EditingBRoute = EditingBRouteImport.update({ - id: '/editing-b', - path: '/editing-b', - getParentRoute: () => rootRouteImport, -} as any) -const EditingARoute = EditingARouteImport.update({ - id: '/editing-a', - path: '/editing-a', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, } as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', @@ -93,54 +117,30 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ path: '/$postId', getParentRoute: () => PostsRoute, } as any) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, -} as any) -const groupLazyinsideRoute = groupLazyinsideRouteImport.update({ - id: '/(group)/lazyinside', - path: '/lazyinside', - getParentRoute: () => rootRouteImport, -} as any) -const groupInsideRoute = groupInsideRouteImport.update({ - id: '/(group)/inside', - path: '/inside', - getParentRoute: () => rootRouteImport, -} as any) -const groupLayoutRoute = groupLayoutRouteImport.update({ - id: '/(group)/_layout', - getParentRoute: () => rootRouteImport, -} as any) -const anotherGroupOnlyrouteinsideRoute = - anotherGroupOnlyrouteinsideRouteImport.update({ - id: '/(another-group)/onlyrouteinside', - path: '/onlyrouteinside', - getParentRoute: () => rootRouteImport, - } as any) -const PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ - id: '/posts_/$postId/edit', - path: '/posts/$postId/edit', - getParentRoute: () => rootRouteImport, -} as any) -const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ - id: '/layout-b', - path: '/layout-b', - getParentRoute: () => LayoutLayout2Route, -} as any) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport.update({ + id: '/insidelayout', + path: '/insidelayout', + getParentRoute: () => groupLayoutRoute, } as any) const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport.update({ id: '/(group)/subfolder/inside', path: '/subfolder/inside', getParentRoute: () => rootRouteImport, } as any) -const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport.update({ - id: '/insidelayout', - path: '/insidelayout', - getParentRoute: () => groupLayoutRoute, +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, +} as any) +const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ + id: '/layout-b', + path: '/layout-b', + getParentRoute: () => LayoutLayout2Route, +} as any) +const PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ + id: '/posts_/$postId/edit', + path: '/posts/$postId/edit', + getParentRoute: () => rootRouteImport, } as any) export interface FileRoutesByFullPath { @@ -291,53 +291,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/대한민국': { - id: '/대한민국' - path: '/대한민국' - fullPath: '/대한민국' - preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport - parentRoute: typeof rootRouteImport - } - '/sfcComponent': { - id: '/sfcComponent' - path: '/sfcComponent' - fullPath: '/sfcComponent' - preLoaderRoute: typeof SfcComponentRouteImport - parentRoute: typeof rootRouteImport - } - '/remountDeps': { - id: '/remountDeps' - path: '/remountDeps' - fullPath: '/remountDeps' - preLoaderRoute: typeof RemountDepsRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/notRemountDeps': { - id: '/notRemountDeps' - path: '/notRemountDeps' - fullPath: '/notRemountDeps' - preLoaderRoute: typeof NotRemountDepsRouteImport - parentRoute: typeof rootRouteImport - } - '/editing-b': { - id: '/editing-b' - path: '/editing-b' - fullPath: '/editing-b' - preLoaderRoute: typeof EditingBRouteImport - parentRoute: typeof rootRouteImport - } - '/editing-a': { - id: '/editing-a' - path: '/editing-a' - fullPath: '/editing-a' - preLoaderRoute: typeof EditingARouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -347,13 +305,90 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/editing-a': { + id: '/editing-a' + path: '/editing-a' + fullPath: '/editing-a' + preLoaderRoute: typeof EditingARouteImport parentRoute: typeof rootRouteImport } + '/editing-b': { + id: '/editing-b' + path: '/editing-b' + fullPath: '/editing-b' + preLoaderRoute: typeof EditingBRouteImport + parentRoute: typeof rootRouteImport + } + '/notRemountDeps': { + id: '/notRemountDeps' + path: '/notRemountDeps' + fullPath: '/notRemountDeps' + preLoaderRoute: typeof NotRemountDepsRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/remountDeps': { + id: '/remountDeps' + path: '/remountDeps' + fullPath: '/remountDeps' + preLoaderRoute: typeof RemountDepsRouteImport + parentRoute: typeof rootRouteImport + } + '/sfcComponent': { + id: '/sfcComponent' + path: '/sfcComponent' + fullPath: '/sfcComponent' + preLoaderRoute: typeof SfcComponentRouteImport + parentRoute: typeof rootRouteImport + } + '/대한민국': { + id: '/대한민국' + path: '/대한민국' + fullPath: '/대한민국' + preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport + parentRoute: typeof rootRouteImport + } + '/(another-group)/onlyrouteinside': { + id: '/(another-group)/onlyrouteinside' + path: '/onlyrouteinside' + fullPath: '/onlyrouteinside' + preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/_layout': { + id: '/(group)/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof groupLayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/inside': { + id: '/(group)/inside' + path: '/inside' + fullPath: '/inside' + preLoaderRoute: typeof groupInsideRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/lazyinside': { + id: '/(group)/lazyinside' + path: '/lazyinside' + fullPath: '/lazyinside' + preLoaderRoute: typeof groupLazyinsideRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute + } '/posts/': { id: '/posts/' path: '/' @@ -368,61 +403,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute - } - '/(group)/lazyinside': { - id: '/(group)/lazyinside' - path: '/lazyinside' - fullPath: '/lazyinside' - preLoaderRoute: typeof groupLazyinsideRouteImport - parentRoute: typeof rootRouteImport - } - '/(group)/inside': { - id: '/(group)/inside' - path: '/inside' - fullPath: '/inside' - preLoaderRoute: typeof groupInsideRouteImport - parentRoute: typeof rootRouteImport - } - '/(group)/_layout': { - id: '/(group)/_layout' - path: '' - fullPath: '' - preLoaderRoute: typeof groupLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/(another-group)/onlyrouteinside': { - id: '/(another-group)/onlyrouteinside' - path: '/onlyrouteinside' - fullPath: '/onlyrouteinside' - preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport - parentRoute: typeof rootRouteImport - } - '/posts_/$postId/edit': { - id: '/posts_/$postId/edit' - path: '/posts/$postId/edit' - fullPath: '/posts/$postId/edit' - preLoaderRoute: typeof PostsPostIdEditRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout/_layout-2/layout-b': { - id: '/_layout/_layout-2/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport - parentRoute: typeof LayoutLayout2Route - } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/(group)/_layout/insidelayout': { + id: '/(group)/_layout/insidelayout' + path: '/insidelayout' + fullPath: '/insidelayout' + preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport + parentRoute: typeof groupLayoutRoute } '/(group)/subfolder/inside': { id: '/(group)/subfolder/inside' @@ -431,12 +417,26 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof groupSubfolderInsideRouteImport parentRoute: typeof rootRouteImport } - '/(group)/_layout/insidelayout': { - id: '/(group)/_layout/insidelayout' - path: '/insidelayout' - fullPath: '/insidelayout' - preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport - parentRoute: typeof groupLayoutRoute + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route + } + '/_layout/_layout-2/layout-b': { + id: '/_layout/_layout-2/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport + parentRoute: typeof LayoutLayout2Route + } + '/posts_/$postId/edit': { + id: '/posts_/$postId/edit' + path: '/posts/$postId/edit' + fullPath: '/posts/$postId/edit' + preLoaderRoute: typeof PostsPostIdEditRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/examples/vue/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx b/examples/vue/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx index 727c1b4d94..e475111e40 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/(another-group)/onlyrouteinside.tsx @@ -1,27 +1,32 @@ import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' +import { defineComponent } from 'vue' import { z } from 'zod' +const OnlyRouteInsideComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ + from: '/(another-group)/onlyrouteinside', + }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) + }, +}) + export const Route = createFileRoute('/(another-group)/onlyrouteinside')({ validateSearch: z.object({ hello: z.string().optional() }), component: OnlyRouteInsideComponent, }) const routeApi = getRouteApi('/(another-group)/onlyrouteinside') - -function OnlyRouteInsideComponent() { - const searchViaHook = useSearch({ from: '/(another-group)/onlyrouteinside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) -} diff --git a/examples/vue/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx b/examples/vue/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx index 4b239f3ef4..869e536811 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/(group)/_layout.insidelayout.tsx @@ -1,27 +1,30 @@ import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' +import { defineComponent } from 'vue' import { z } from 'zod' +const InsideLayoutComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ from: '/(group)/_layout/insidelayout' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) + }, +}) + export const Route = createFileRoute('/(group)/_layout/insidelayout')({ validateSearch: z.object({ hello: z.string().optional() }), component: InsideLayoutComponent, }) const routeApi = getRouteApi('/(group)/_layout/insidelayout') - -function InsideLayoutComponent() { - const searchViaHook = useSearch({ from: '/(group)/_layout/insidelayout' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) -} diff --git a/examples/vue/basic-file-based-jsx/src/routes/(group)/inside.tsx b/examples/vue/basic-file-based-jsx/src/routes/(group)/inside.tsx index f12ca517d3..4a0caa8f8d 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/(group)/inside.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/(group)/inside.tsx @@ -1,27 +1,30 @@ import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' +import { defineComponent } from 'vue' import { z } from 'zod' +const InsideComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ from: '/(group)/inside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) + }, +}) + export const Route = createFileRoute('/(group)/inside')({ validateSearch: z.object({ hello: z.string().optional() }), component: InsideComponent, }) const routeApi = getRouteApi('/(group)/inside') - -function InsideComponent() { - const searchViaHook = useSearch({ from: '/(group)/inside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) -} diff --git a/examples/vue/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx b/examples/vue/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx index 05b34eb201..fdae632aee 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/(group)/lazyinside.tsx @@ -1,27 +1,30 @@ import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' +import { defineComponent } from 'vue' import { z } from 'zod' +const LazyInsideComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ from: '/(group)/lazyinside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) + }, +}) + export const Route = createFileRoute('/(group)/lazyinside')({ validateSearch: z.object({ hello: z.string().optional() }), component: LazyInsideComponent, }) const routeApi = getRouteApi('/(group)/lazyinside') - -function LazyInsideComponent() { - const searchViaHook = useSearch({ from: '/(group)/lazyinside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) -} diff --git a/examples/vue/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx b/examples/vue/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx index 317c766186..8c7222ee70 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/(group)/subfolder/inside.tsx @@ -1,27 +1,30 @@ import { createFileRoute, getRouteApi, useSearch } from '@tanstack/vue-router' +import { defineComponent } from 'vue' import { z } from 'zod' +const SubfolderInsideComponent = defineComponent({ + setup() { + const searchViaHook = useSearch({ from: '/(group)/subfolder/inside' }) + const searchViaRouteHook = routeApi.useSearch() + const searchViaRouteApi = routeApi.useSearch() + + return () => ( +
+
{searchViaHook.value.hello}
+
+ {searchViaRouteHook.value.hello} +
+
+ {searchViaRouteApi.value.hello} +
+
+ ) + }, +}) + export const Route = createFileRoute('/(group)/subfolder/inside')({ validateSearch: z.object({ hello: z.string().optional() }), component: SubfolderInsideComponent, }) const routeApi = getRouteApi('/(group)/subfolder/inside') - -function SubfolderInsideComponent() { - const searchViaHook = useSearch({ from: '/(group)/subfolder/inside' }) - const searchViaRouteHook = routeApi.useSearch() - const searchViaRouteApi = routeApi.useSearch() - - return ( -
-
{searchViaHook.value.hello}
-
- {searchViaRouteHook.value.hello} -
-
- {searchViaRouteApi.value.hello} -
-
- ) -} diff --git a/examples/vue/basic-file-based-jsx/src/routes/__root.tsx b/examples/vue/basic-file-based-jsx/src/routes/__root.tsx index 59c9e6fa48..adcc3acbd7 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/__root.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/__root.tsx @@ -8,97 +8,100 @@ import { useRouterState, } from '@tanstack/vue-router' import { TanStackRouterDevtools } from '@tanstack/vue-router-devtools' +import { defineComponent } from 'vue' import NotFoundComponent from '../components/NotFoundComponent.vue' +const RootComponent = defineComponent({ + setup() { + const router = useRouter() + const canGoBack = useCanGoBack() + // test useRouterState doesn't crash client side navigation + const _state = useRouterState() + + return () => ( + <> + +
+ + + Home + + + Posts + + + Layout + + + Only Route Inside Group + + + Inside Group + + + Inside Subfolder Inside Group + + + Inside Group Inside Layout + + + Lazy Inside Group + + + unicode path + + + This Route Does Not Exist + +
+
+ + + + ) + }, +}) + export const Route = createRootRoute({ component: RootComponent, notFoundComponent: NotFoundComponent, }) - -function RootComponent() { - const router = useRouter() - const canGoBack = useCanGoBack() - // test useRouterState doesn't crash client side navigation - const _state = useRouterState() - - return ( - <> - -
- - - Home - - - Posts - - - Layout - - - Only Route Inside Group - - - Inside Group - - - Inside Subfolder Inside Group - - - Inside Group Inside Layout - - - Lazy Inside Group - - - unicode path - - - This Route Does Not Exist - -
-
- - - - ) -} diff --git a/examples/vue/basic-file-based-jsx/src/routes/posts.$postId.tsx b/examples/vue/basic-file-based-jsx/src/routes/posts.$postId.tsx index 15d17387c8..bc1dbfbbd0 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/posts.$postId.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/posts.$postId.tsx @@ -1,24 +1,27 @@ import { createFileRoute } from '@tanstack/vue-router' +import { defineComponent } from 'vue' import PostErrorComponent from '../components/PostErrorComponent.vue' import { fetchPost } from '../posts' import type { PostType } from '../posts' +const PostComponent = defineComponent({ + setup() { + const post = Route.useLoaderData() + + return () => ( +
+

+ {(post.value as PostType).title} +

+
{(post.value as PostType).body}
+
+ ) + }, +}) + export const Route = createFileRoute('/posts/$postId')({ loader: async ({ params: { postId } }) => fetchPost(postId), component: PostComponent, errorComponent: PostErrorComponent, notFoundComponent: () =>

Post not found

, }) - -function PostComponent() { - const post = Route.useLoaderData() - - return ( -
-

- {(post.value as PostType).title} -

-
{(post.value as PostType).body}
-
- ) -} diff --git a/examples/vue/basic-file-based-jsx/src/routes/posts.tsx b/examples/vue/basic-file-based-jsx/src/routes/posts.tsx index ae580dfc02..522988e52b 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/posts.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/posts.tsx @@ -1,7 +1,38 @@ import { Link, Outlet, createFileRoute } from '@tanstack/vue-router' +import { defineComponent } from 'vue' import { fetchPosts } from '../posts' import type { PostType } from '../posts' +const PostsComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + + return () => ( +
+
    + {[ + ...(posts.value as Array), + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ))} +
+
+ +
+ ) + }, +}) + export const Route = createFileRoute('/posts')({ head: () => ({ meta: [ @@ -13,31 +44,3 @@ export const Route = createFileRoute('/posts')({ loader: fetchPosts, component: PostsComponent, }) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[ - ...(posts.value as Array), - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ))} -
-
- -
- ) -} diff --git a/examples/vue/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx b/examples/vue/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx index 57963c6b64..ad20bcdf97 100644 --- a/examples/vue/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx +++ b/examples/vue/basic-file-based-jsx/src/routes/posts_.$postId.edit.tsx @@ -1,23 +1,28 @@ import { createFileRoute, getRouteApi, useParams } from '@tanstack/vue-router' +import { defineComponent } from 'vue' + +const PostEditComponent = defineComponent({ + setup() { + const paramsViaApi = api.useParams() + const paramsViaHook = useParams({ from: '/posts_/$postId/edit' }) + const paramsViaRouteHook = api.useParams() + + return () => ( +
+
{paramsViaHook.value.postId}
+
+ {paramsViaRouteHook.value.postId} +
+
+ {paramsViaApi.value.postId} +
+
+ ) + }, +}) export const Route = createFileRoute('/posts_/$postId/edit')({ component: PostEditComponent, }) const api = getRouteApi('/posts_/$postId/edit') - -function PostEditComponent() { - const paramsViaApi = api.useParams() - const paramsViaHook = useParams({ from: '/posts_/$postId/edit' }) - const paramsViaRouteHook = api.useParams() - - return ( -
-
{paramsViaHook.value.postId}
-
- {paramsViaRouteHook.value.postId} -
-
{paramsViaApi.value.postId}
-
- ) -} diff --git a/examples/vue/basic-file-based-sfc/package.json b/examples/vue/basic-file-based-sfc/package.json index bef5799572..87ab2c332b 100644 --- a/examples/vue/basic-file-based-sfc/package.json +++ b/examples/vue/basic-file-based-sfc/package.json @@ -10,9 +10,9 @@ }, "dependencies": { "@tailwindcss/vite": "^4.2.2", - "@tanstack/router-plugin": "^1.168.20", - "@tanstack/vue-router": "^1.170.17", - "@tanstack/vue-router-devtools": "^1.167.0", + "@tanstack/router-plugin": "^1.169.0", + "@tanstack/vue-router": "^1.170.42", + "@tanstack/vue-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "tailwindcss": "^4.2.2", "vue": "^3.5.16", @@ -23,6 +23,6 @@ "@vitejs/plugin-vue-jsx": "^5.1.5", "typescript": "~5.8.3", "vite": "^8.0.14", - "vue-tsc": "^3.1.5" + "vue-tsc": "^3.3.8" } } diff --git a/examples/vue/basic-file-based-sfc/src/posts.ts b/examples/vue/basic-file-based-sfc/src/posts.ts index 1b4c92b41d..f7a1941605 100644 --- a/examples/vue/basic-file-based-sfc/src/posts.ts +++ b/examples/vue/basic-file-based-sfc/src/posts.ts @@ -7,11 +7,7 @@ export type PostType = { body: string } -let queryURL = 'https://jsonplaceholder.typicode.com' - -if (import.meta.env.VITE_NODE_ENV === 'test') { - queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` -} +const queryURL = 'https://jsonplaceholder.typicode.com' export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/examples/vue/basic-file-based-sfc/src/routeTree.gen.ts b/examples/vue/basic-file-based-sfc/src/routeTree.gen.ts index fa00eb1ce0..0bfdddab3d 100644 --- a/examples/vue/basic-file-based-sfc/src/routeTree.gen.ts +++ b/examples/vue/basic-file-based-sfc/src/routeTree.gen.ts @@ -11,75 +11,43 @@ import { lazyRouteComponent } from '@tanstack/vue-router' import { Route as rootRouteImport } from './routes/__root' -import { Route as Char45824Char54620Char48124Char44397RouteImport } from './routes/대한민국' -import { Route as RemountDepsRouteImport } from './routes/remountDeps' -import { Route as PostsRouteImport } from './routes/posts' -import { Route as NotRemountDepsRouteImport } from './routes/notRemountDeps' -import { Route as EditingBRouteImport } from './routes/editing-b' -import { Route as EditingARouteImport } from './routes/editing-a' -import { Route as LayoutRouteImport } from './routes/_layout' import { Route as IndexRouteImport } from './routes/index' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as EditingARouteImport } from './routes/editing-a' +import { Route as EditingBRouteImport } from './routes/editing-b' +import { Route as NotRemountDepsRouteImport } from './routes/notRemountDeps' +import { Route as PostsRouteImport } from './routes/posts' +import { Route as RemountDepsRouteImport } from './routes/remountDeps' +import { Route as Char45824Char54620Char48124Char44397RouteImport } from './routes/대한민국' +import { Route as anotherGroupOnlyrouteinsideRouteImport } from './routes/(another-group)/onlyrouteinside' +import { Route as groupLayoutRouteImport } from './routes/(group)/_layout' +import { Route as groupInsideRouteImport } from './routes/(group)/inside' +import { Route as groupLazyinsideRouteImport } from './routes/(group)/lazyinside' +import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' import { Route as PostsIndexRouteImport } from './routes/posts.index' import { Route as PostsPostIdRouteImport } from './routes/posts.$postId' -import { Route as LayoutLayout2RouteImport } from './routes/_layout/_layout-2' -import { Route as groupLazyinsideRouteImport } from './routes/(group)/lazyinside' -import { Route as groupInsideRouteImport } from './routes/(group)/inside' -import { Route as groupLayoutRouteImport } from './routes/(group)/_layout' -import { Route as anotherGroupOnlyrouteinsideRouteImport } from './routes/(another-group)/onlyrouteinside' -import { Route as PostsPostIdEditRouteImport } from './routes/posts_.$postId.edit' -import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' -import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' -import { Route as groupSubfolderInsideRouteImport } from './routes/(group)/subfolder/inside' import { Route as groupLayoutInsidelayoutRouteImport } from './routes/(group)/_layout.insidelayout' +import { Route as groupSubfolderInsideRouteImport } from './routes/(group)/subfolder/inside' +import { Route as LayoutLayout2LayoutARouteImport } from './routes/_layout/_layout-2/layout-a' +import { Route as LayoutLayout2LayoutBRouteImport } from './routes/_layout/_layout-2/layout-b' +import { Route as PostsPostIdEditRouteImport } from './routes/posts_.$postId.edit' -const Char45824Char54620Char48124Char44397Route = - Char45824Char54620Char48124Char44397RouteImport.update({ - id: '/대한민국', - path: '/대한민국', - getParentRoute: () => rootRouteImport, - } as any).update({ - component: lazyRouteComponent( - () => import('./routes/대한민국.component.vue'), - 'default', - ), - }) -const RemountDepsRoute = RemountDepsRouteImport.update({ - id: '/remountDeps', - path: '/remountDeps', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/remountDeps.component.vue'), + () => import('./routes/index.component.vue'), 'default', ), }) -const PostsRoute = PostsRouteImport.update({ - id: '/posts', - path: '/posts', +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/posts.component.vue'), - 'default', - ), -}) -const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ - id: '/notRemountDeps', - path: '/notRemountDeps', - getParentRoute: () => rootRouteImport, -} as any).update({ - component: lazyRouteComponent( - () => import('./routes/notRemountDeps.component.vue'), - 'default', - ), -}) -const EditingBRoute = EditingBRouteImport.update({ - id: '/editing-b', - path: '/editing-b', - getParentRoute: () => rootRouteImport, -} as any).update({ - component: lazyRouteComponent( - () => import('./routes/editing-b.component.vue'), + () => import('./routes/_layout.component.vue'), 'default', ), }) @@ -93,22 +61,110 @@ const EditingARoute = EditingARouteImport.update({ 'default', ), }) -const LayoutRoute = LayoutRouteImport.update({ - id: '/_layout', +const EditingBRoute = EditingBRouteImport.update({ + id: '/editing-b', + path: '/editing-b', getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/_layout.component.vue'), + () => import('./routes/editing-b.component.vue'), 'default', ), }) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const NotRemountDepsRoute = NotRemountDepsRouteImport.update({ + id: '/notRemountDeps', + path: '/notRemountDeps', getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/index.component.vue'), + () => import('./routes/notRemountDeps.component.vue'), + 'default', + ), +}) +const PostsRoute = PostsRouteImport.update({ + id: '/posts', + path: '/posts', + getParentRoute: () => rootRouteImport, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/posts.component.vue'), + 'default', + ), +}) +const RemountDepsRoute = RemountDepsRouteImport.update({ + id: '/remountDeps', + path: '/remountDeps', + getParentRoute: () => rootRouteImport, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/remountDeps.component.vue'), + 'default', + ), +}) +const Char45824Char54620Char48124Char44397Route = + Char45824Char54620Char48124Char44397RouteImport.update({ + id: '/대한민국', + path: '/대한민국', + getParentRoute: () => rootRouteImport, + } as any).update({ + component: lazyRouteComponent( + () => import('./routes/대한민국.component.vue'), + 'default', + ), + }) +const anotherGroupOnlyrouteinsideRoute = anotherGroupOnlyrouteinsideRouteImport + .update({ + id: '/(another-group)/onlyrouteinside', + path: '/onlyrouteinside', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(another-group)/onlyrouteinside.component.vue'), + 'default', + ), + }) +const groupLayoutRoute = groupLayoutRouteImport + .update({ + id: '/(group)/_layout', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/_layout.component.vue'), + 'default', + ), + }) +const groupInsideRoute = groupInsideRouteImport + .update({ + id: '/(group)/inside', + path: '/inside', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/inside.component.vue'), + 'default', + ), + }) +const groupLazyinsideRoute = groupLazyinsideRouteImport + .update({ + id: '/(group)/lazyinside', + path: '/lazyinside', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/lazyinside.component.vue'), + 'default', + ), + }) +const LayoutLayout2Route = LayoutLayout2RouteImport.update({ + id: '/_layout-2', + getParentRoute: () => LayoutRoute, +} as any).update({ + component: lazyRouteComponent( + () => import('./routes/_layout/_layout-2.component.vue'), 'default', ), }) @@ -136,69 +192,37 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ 'default', ), }) -const LayoutLayout2Route = LayoutLayout2RouteImport.update({ - id: '/_layout-2', - getParentRoute: () => LayoutRoute, +const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport + .update({ + id: '/insidelayout', + path: '/insidelayout', + getParentRoute: () => groupLayoutRoute, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/_layout.insidelayout.component.vue'), + 'default', + ), + }) +const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport + .update({ + id: '/(group)/subfolder/inside', + path: '/subfolder/inside', + getParentRoute: () => rootRouteImport, + } as any) + .update({ + component: lazyRouteComponent( + () => import('./routes/(group)/subfolder/inside.component.vue'), + 'default', + ), + }) +const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ + id: '/layout-a', + path: '/layout-a', + getParentRoute: () => LayoutLayout2Route, } as any).update({ component: lazyRouteComponent( - () => import('./routes/_layout/_layout-2.component.vue'), - 'default', - ), -}) -const groupLazyinsideRoute = groupLazyinsideRouteImport - .update({ - id: '/(group)/lazyinside', - path: '/lazyinside', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/lazyinside.component.vue'), - 'default', - ), - }) -const groupInsideRoute = groupInsideRouteImport - .update({ - id: '/(group)/inside', - path: '/inside', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/inside.component.vue'), - 'default', - ), - }) -const groupLayoutRoute = groupLayoutRouteImport - .update({ - id: '/(group)/_layout', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/_layout.component.vue'), - 'default', - ), - }) -const anotherGroupOnlyrouteinsideRoute = anotherGroupOnlyrouteinsideRouteImport - .update({ - id: '/(another-group)/onlyrouteinside', - path: '/onlyrouteinside', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(another-group)/onlyrouteinside.component.vue'), - 'default', - ), - }) -const PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ - id: '/posts_/$postId/edit', - path: '/posts/$postId/edit', - getParentRoute: () => rootRouteImport, -} as any).update({ - component: lazyRouteComponent( - () => import('./routes/posts_.$postId.edit.component.vue'), + () => import('./routes/_layout/_layout-2/layout-a.component.vue'), 'default', ), }) @@ -212,40 +236,16 @@ const LayoutLayout2LayoutBRoute = LayoutLayout2LayoutBRouteImport.update({ 'default', ), }) -const LayoutLayout2LayoutARoute = LayoutLayout2LayoutARouteImport.update({ - id: '/layout-a', - path: '/layout-a', - getParentRoute: () => LayoutLayout2Route, +const PostsPostIdEditRoute = PostsPostIdEditRouteImport.update({ + id: '/posts_/$postId/edit', + path: '/posts/$postId/edit', + getParentRoute: () => rootRouteImport, } as any).update({ component: lazyRouteComponent( - () => import('./routes/_layout/_layout-2/layout-a.component.vue'), + () => import('./routes/posts_.$postId.edit.component.vue'), 'default', ), }) -const groupSubfolderInsideRoute = groupSubfolderInsideRouteImport - .update({ - id: '/(group)/subfolder/inside', - path: '/subfolder/inside', - getParentRoute: () => rootRouteImport, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/subfolder/inside.component.vue'), - 'default', - ), - }) -const groupLayoutInsidelayoutRoute = groupLayoutInsidelayoutRouteImport - .update({ - id: '/insidelayout', - path: '/insidelayout', - getParentRoute: () => groupLayoutRoute, - } as any) - .update({ - component: lazyRouteComponent( - () => import('./routes/(group)/_layout.insidelayout.component.vue'), - 'default', - ), - }) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -388,46 +388,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/대한민국': { - id: '/대한민국' - path: '/대한민국' - fullPath: '/대한민국' - preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport - parentRoute: typeof rootRouteImport - } - '/remountDeps': { - id: '/remountDeps' - path: '/remountDeps' - fullPath: '/remountDeps' - preLoaderRoute: typeof RemountDepsRouteImport - parentRoute: typeof rootRouteImport - } - '/posts': { - id: '/posts' - path: '/posts' - fullPath: '/posts' - preLoaderRoute: typeof PostsRouteImport - parentRoute: typeof rootRouteImport - } - '/notRemountDeps': { - id: '/notRemountDeps' - path: '/notRemountDeps' - fullPath: '/notRemountDeps' - preLoaderRoute: typeof NotRemountDepsRouteImport - parentRoute: typeof rootRouteImport - } - '/editing-b': { - id: '/editing-b' - path: '/editing-b' - fullPath: '/editing-b' - preLoaderRoute: typeof EditingBRouteImport - parentRoute: typeof rootRouteImport - } - '/editing-a': { - id: '/editing-a' - path: '/editing-a' - fullPath: '/editing-a' - preLoaderRoute: typeof EditingARouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/_layout': { @@ -437,13 +402,83 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/editing-a': { + id: '/editing-a' + path: '/editing-a' + fullPath: '/editing-a' + preLoaderRoute: typeof EditingARouteImport parentRoute: typeof rootRouteImport } + '/editing-b': { + id: '/editing-b' + path: '/editing-b' + fullPath: '/editing-b' + preLoaderRoute: typeof EditingBRouteImport + parentRoute: typeof rootRouteImport + } + '/notRemountDeps': { + id: '/notRemountDeps' + path: '/notRemountDeps' + fullPath: '/notRemountDeps' + preLoaderRoute: typeof NotRemountDepsRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + '/remountDeps': { + id: '/remountDeps' + path: '/remountDeps' + fullPath: '/remountDeps' + preLoaderRoute: typeof RemountDepsRouteImport + parentRoute: typeof rootRouteImport + } + '/대한민국': { + id: '/대한민국' + path: '/대한민국' + fullPath: '/대한민국' + preLoaderRoute: typeof Char45824Char54620Char48124Char44397RouteImport + parentRoute: typeof rootRouteImport + } + '/(another-group)/onlyrouteinside': { + id: '/(another-group)/onlyrouteinside' + path: '/onlyrouteinside' + fullPath: '/onlyrouteinside' + preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/_layout': { + id: '/(group)/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof groupLayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/inside': { + id: '/(group)/inside' + path: '/inside' + fullPath: '/inside' + preLoaderRoute: typeof groupInsideRouteImport + parentRoute: typeof rootRouteImport + } + '/(group)/lazyinside': { + id: '/(group)/lazyinside' + path: '/lazyinside' + fullPath: '/lazyinside' + preLoaderRoute: typeof groupLazyinsideRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/_layout-2': { + id: '/_layout/_layout-2' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutLayout2RouteImport + parentRoute: typeof LayoutRoute + } '/posts/': { id: '/posts/' path: '/' @@ -458,61 +493,12 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsPostIdRouteImport parentRoute: typeof PostsRoute } - '/_layout/_layout-2': { - id: '/_layout/_layout-2' - path: '' - fullPath: '/' - preLoaderRoute: typeof LayoutLayout2RouteImport - parentRoute: typeof LayoutRoute - } - '/(group)/lazyinside': { - id: '/(group)/lazyinside' - path: '/lazyinside' - fullPath: '/lazyinside' - preLoaderRoute: typeof groupLazyinsideRouteImport - parentRoute: typeof rootRouteImport - } - '/(group)/inside': { - id: '/(group)/inside' - path: '/inside' - fullPath: '/inside' - preLoaderRoute: typeof groupInsideRouteImport - parentRoute: typeof rootRouteImport - } - '/(group)/_layout': { - id: '/(group)/_layout' - path: '' - fullPath: '' - preLoaderRoute: typeof groupLayoutRouteImport - parentRoute: typeof rootRouteImport - } - '/(another-group)/onlyrouteinside': { - id: '/(another-group)/onlyrouteinside' - path: '/onlyrouteinside' - fullPath: '/onlyrouteinside' - preLoaderRoute: typeof anotherGroupOnlyrouteinsideRouteImport - parentRoute: typeof rootRouteImport - } - '/posts_/$postId/edit': { - id: '/posts_/$postId/edit' - path: '/posts/$postId/edit' - fullPath: '/posts/$postId/edit' - preLoaderRoute: typeof PostsPostIdEditRouteImport - parentRoute: typeof rootRouteImport - } - '/_layout/_layout-2/layout-b': { - id: '/_layout/_layout-2/layout-b' - path: '/layout-b' - fullPath: '/layout-b' - preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport - parentRoute: typeof LayoutLayout2Route - } - '/_layout/_layout-2/layout-a': { - id: '/_layout/_layout-2/layout-a' - path: '/layout-a' - fullPath: '/layout-a' - preLoaderRoute: typeof LayoutLayout2LayoutARouteImport - parentRoute: typeof LayoutLayout2Route + '/(group)/_layout/insidelayout': { + id: '/(group)/_layout/insidelayout' + path: '/insidelayout' + fullPath: '/insidelayout' + preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport + parentRoute: typeof groupLayoutRoute } '/(group)/subfolder/inside': { id: '/(group)/subfolder/inside' @@ -521,12 +507,26 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof groupSubfolderInsideRouteImport parentRoute: typeof rootRouteImport } - '/(group)/_layout/insidelayout': { - id: '/(group)/_layout/insidelayout' - path: '/insidelayout' - fullPath: '/insidelayout' - preLoaderRoute: typeof groupLayoutInsidelayoutRouteImport - parentRoute: typeof groupLayoutRoute + '/_layout/_layout-2/layout-a': { + id: '/_layout/_layout-2/layout-a' + path: '/layout-a' + fullPath: '/layout-a' + preLoaderRoute: typeof LayoutLayout2LayoutARouteImport + parentRoute: typeof LayoutLayout2Route + } + '/_layout/_layout-2/layout-b': { + id: '/_layout/_layout-2/layout-b' + path: '/layout-b' + fullPath: '/layout-b' + preLoaderRoute: typeof LayoutLayout2LayoutBRouteImport + parentRoute: typeof LayoutLayout2Route + } + '/posts_/$postId/edit': { + id: '/posts_/$postId/edit' + path: '/posts/$postId/edit' + fullPath: '/posts/$postId/edit' + preLoaderRoute: typeof PostsPostIdEditRouteImport + parentRoute: typeof rootRouteImport } } } diff --git a/examples/vue/basic/package.json b/examples/vue/basic/package.json index 49b88fa665..af74afff3a 100644 --- a/examples/vue/basic/package.json +++ b/examples/vue/basic/package.json @@ -9,16 +9,17 @@ "start": "vite" }, "dependencies": { - "@tanstack/vue-router": "^1.170.17", - "@tanstack/vue-router-devtools": "^1.167.0", + "@tanstack/vue-router": "^1.170.42", + "@tanstack/vue-router-devtools": "^1.167.3", "redaxios": "^0.5.1", "vue": "^3.5.13", "tailwindcss": "4.1.18" }, "devDependencies": { - "typescript": "^6.0.2", + "@typescript/native": "npm:typescript@^7.0.2", + "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", - "vue-tsc": "^3.1.5", + "vue-tsc": "^3.3.8", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "@tailwindcss/vite": "^4.2.2" diff --git a/examples/vue/basic/src/main.tsx b/examples/vue/basic/src/main.tsx index dc12871db0..09878913a8 100644 --- a/examples/vue/basic/src/main.tsx +++ b/examples/vue/basic/src/main.tsx @@ -1,4 +1,4 @@ -import { createApp } from 'vue' +import { createApp, defineComponent } from 'vue' import { ErrorComponent, Link, @@ -102,6 +102,20 @@ function PostsIndexComponent() { return
Select a post.
} +const PostComponent = defineComponent({ + setup() { + const post = postRoute.useLoaderData() + + return () => ( +
+

{post.value.title}

+
+
{post.value.body}
+
+ ) + }, +}) + const postRoute = createRoute({ getParentRoute: () => postsLayoutRoute, path: '$postId', @@ -118,18 +132,6 @@ function PostErrorComponent({ error }: ErrorComponentProps) { return } -function PostComponent() { - const post = postRoute.useLoaderData() - - return ( -
-

{post.value.title}

-
-
{post.value.body}
-
- ) -} - const pathlessLayoutRoute = createRoute({ getParentRoute: () => rootRoute, id: '_pathlessLayout', diff --git a/examples/vue/basic/src/posts.lazy.tsx b/examples/vue/basic/src/posts.lazy.tsx index 1fd64723e5..8602de045f 100644 --- a/examples/vue/basic/src/posts.lazy.tsx +++ b/examples/vue/basic/src/posts.lazy.tsx @@ -1,36 +1,39 @@ import { Link, Outlet, createLazyRoute } from '@tanstack/vue-router' +import { defineComponent } from 'vue' + +const PostsLayoutComponent = defineComponent({ + setup() { + const posts = Route.useLoaderData() + + return () => ( +
+
    + {[ + ...posts.value, + { id: 'i-do-not-exist', title: 'Non-existent Post' }, + ].map((post) => { + return ( +
  • + +
    {post.title.substring(0, 20)}
    + +
  • + ) + })} +
+ +
+ ) + }, +}) export const Route = createLazyRoute('/posts')({ component: PostsLayoutComponent, }) - -function PostsLayoutComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {[ - ...posts.value, - { id: 'i-do-not-exist', title: 'Non-existent Post' }, - ].map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
- -
- ) -} diff --git a/labeler-config.yml b/labeler-config.yml index c1ad49328e..9da92bf7ff 100644 --- a/labeler-config.yml +++ b/labeler-config.yml @@ -10,9 +10,6 @@ 'package: history': - changed-files: - any-glob-to-any-file: 'packages/history/**/*' -'package: nitro-v2-vite-plugin': - - changed-files: - - any-glob-to-any-file: 'packages/nitro-v2-vite-plugin/**/*' 'package: react-router': - changed-files: - any-glob-to-any-file: 'packages/react-router/**/*' diff --git a/media/header_router.png b/media/header_router.png deleted file mode 100644 index 5f2d58134d..0000000000 Binary files a/media/header_router.png and /dev/null differ diff --git a/media/header_start.png b/media/header_start.png deleted file mode 100644 index 8622986ee1..0000000000 Binary files a/media/header_start.png and /dev/null differ diff --git a/nx.json b/nx.json index 08e7563642..b7df8b2c09 100644 --- a/nx.json +++ b/nx.json @@ -1,6 +1,7 @@ { "$schema": "./node_modules/nx/schemas/nx-schema.json", "defaultBase": "main", + "bust": "nx24-exclusive-e2e-16-medium-baseline-2026-10-25-05", "nxCloudId": "6442f7de8226a6291646a813", "useInferencePlugins": false, "parallel": 5, @@ -9,10 +10,26 @@ }, "namedInputs": { "sharedGlobals": [ + "{workspaceRoot}/.npmrc", + "{workspaceRoot}/nx.json", + "{workspaceRoot}/.github/workflows/pr.yml", + "{workspaceRoot}/.nx/ci-config.yaml", + "{workspaceRoot}/.nx/workflows/ultracache-config.yaml", "{workspaceRoot}/.nvmrc", "{workspaceRoot}/package.json", "{workspaceRoot}/tsconfig.json" ], + "dependentTaskOutputs": [ + { + "dependentTasksOutputFiles": "**/*", + "transitive": true + } + ], + "streamingSsrTests": [ + "{workspaceRoot}/e2e/streaming-ssr-assertions.ts", + "{workspaceRoot}/e2e/streaming-ssr-fixtures/**/*", + "{workspaceRoot}/e2e/streaming-ssr-specs/**/*" + ], "default": [ "sharedGlobals", "{projectRoot}/**/*", @@ -22,64 +39,119 @@ "default", "!{projectRoot}/tests/**/*", "!{projectRoot}/eslint.config.js" - ] + ], + "buildProduction": ["sharedGlobals", "{projectRoot}/**/*"] }, "targetDefaults": { "test:docs": { "cache": true, - "inputs": ["{workspaceRoot}/docs/**/*"] + "inputs": ["sharedGlobals", "{workspaceRoot}/docs/**/*"] }, "test:eslint": { "cache": true, - "dependsOn": ["^build"], - "inputs": ["default", "^production", "{workspaceRoot}/eslint.config.js"] + "dependsOn": ["^build", "build"], + "inputs": [ + "default", + "^production", + "{workspaceRoot}/eslint.config.js", + "dependentTaskOutputs" + ] }, "test:unit": { "cache": true, "dependsOn": ["^build"], - "inputs": ["default", "^production"], + "inputs": [ + "default", + "^production", + "{workspaceRoot}/eslint.config.js", + "dependentTaskOutputs" + ], "outputs": ["{projectRoot}/coverage"] }, "test:e2e": { "cache": true, "dependsOn": ["^build", "test:e2e--*"], - "inputs": ["default", "^production"] + "inputs": ["buildProduction", "^production", "dependentTaskOutputs"], + "outputs": ["{projectRoot}/dist", "{projectRoot}/test-results"], + "parallelism": false }, "test:e2e:nitro": { "cache": true, "dependsOn": ["^build"], - "inputs": ["default", "^production"] + "inputs": ["default", "^production"], + "parallelism": false }, "test:e2e:basepath": { "cache": true, "dependsOn": ["^build"], - "inputs": ["default", "^production"] + "inputs": ["default", "^production"], + "parallelism": false }, "test:e2e:preview": { "cache": true, "dependsOn": ["^build"], - "inputs": ["default", "^production"] + "inputs": ["default", "^production"], + "parallelism": false }, "test:types": { "cache": true, - "dependsOn": ["^build"], - "inputs": ["default", "^production"] + "dependsOn": ["^build", "build"], + "inputs": [ + "default", + "^production", + "{workspaceRoot}/eslint.config.js", + "dependentTaskOutputs" + ] + }, + "test:types:client": { + "cache": true, + "inputs": [ + "default", + "^production", + "{workspaceRoot}/benchmarks/client-nav/*.{ts,json}", + "{workspaceRoot}/benchmarks/client-nav/scenarios/*.ts", + "{workspaceRoot}/benchmarks/client-nav/scenarios/*/*.ts", + "{workspaceRoot}/benchmarks/memory/*.ts", + "{workspaceRoot}/benchmarks/memory/client/*.{ts,json}", + "{workspaceRoot}/benchmarks/memory/client/scenarios/*/*.ts", + "{workspaceRoot}/benchmarks/cpu-simulation.ts", + "dependentTaskOutputs" + ] }, "test:types:ssr": { "cache": true, - "dependsOn": ["^build"], - "inputs": ["default", "^production"] + "dependsOn": ["^build", "build"], + "inputs": [ + "default", + "^production", + "{workspaceRoot}/benchmarks/ssr/bench-utils.ts", + "{workspaceRoot}/benchmarks/cpu-simulation.ts", + "{workspaceRoot}/benchmarks/ssr/scenarios/*/*.ts", + "{workspaceRoot}/benchmarks/memory/*.ts", + "{workspaceRoot}/benchmarks/memory/server/*.ts", + "{workspaceRoot}/benchmarks/memory/server/scenarios/*/*.ts", + "dependentTaskOutputs" + ] }, "build": { "cache": true, "dependsOn": ["^build"], - "inputs": ["production", "^production"], - "outputs": ["{projectRoot}/build", "{projectRoot}/dist"] + "inputs": ["buildProduction", "^buildProduction", "dependentTaskOutputs"], + "outputs": [ + "{projectRoot}/.netlify", + "{projectRoot}/.wrangler", + "{projectRoot}/.output", + "{projectRoot}/build", + "{projectRoot}/dist" + ] }, "test:build": { "cache": true, "dependsOn": ["build"], - "inputs": ["production"] + "inputs": ["buildProduction", "dependentTaskOutputs"] + }, + "test:e2e*": { + "parallelism": false } }, "plugins": [ diff --git a/package.json b/package.json index cdc2bf2bc8..3ef11b1969 100644 --- a/package.json +++ b/package.json @@ -5,24 +5,25 @@ "type": "git", "url": "git+https://github.com/TanStack/router.git" }, - "packageManager": "pnpm@11.9.0", + "packageManager": "pnpm@12.18.0", "engines": { - "pnpm": ">=11.9.0" + "pnpm": ">=12.18.0" }, "type": "module", "scripts": { "cleanNodeModules": "pnpm -r exec rm -rf node_modules", "clean": "pnpm --filter \"./packages/**\" run clean", "test": "pnpm run test:ci", - "test:pr": "nx affected --targets=test:eslint,test:unit,test:e2e,test:types,test:build,build", - "test:ci": "nx run-many --targets=test:eslint,test:unit,test:e2e,test:types,test:build,build", + "test:pr": "nx affected --targets=test:eslint,test:unit,test:integration,test:e2e,test:types,test:build,build", + "test:ci": "nx run-many --targets=test:eslint,test:unit,test:integration,test:e2e,test:types,test:build,build", "test:eslint": "nx affected --target=test:eslint --exclude=examples/**,e2e/**", "test:unit": "nx affected --target=test:unit --exclude=examples/**,e2e/**", "test:unit:dev": "pnpm run test:unit && nx watch --all -- pnpm run test:unit", "test:build": "nx affected --target=test:build --exclude=examples/**", "test:types": "nx affected --target=test:types --exclude=examples/**", "test:e2e": "nx run-many --target=test:e2e", - "benchmark:bundle-size": "nx run @benchmarks/bundle-size:build", + "benchmark:bundle-size": "node scripts/benchmarks/bundle-size/build.mjs", + "benchmark:bundle-size:run": "node scripts/benchmarks/bundle-size/run.mjs", "benchmark:bundle-size:query": "node scripts/benchmarks/bundle-size/query.mjs", "benchmark:bundle-size:diff": "node scripts/benchmarks/bundle-size/diff.mjs", "benchmark:bundle-size:history": "node scripts/benchmarks/bundle-size/history.mjs", @@ -44,7 +45,8 @@ "format": "prettier --experimental-cli --ignore-unknown '**/*' --write", "changeset": "changeset", "changeset:publish": "changeset publish", - "changeset:version": "changeset version && node scripts/update-example-deps.mjs && pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile && pnpm format", + "changeset:version": "changeset version && pnpm run update:example-deps && pnpm install --lockfile-only --ignore-scripts --no-frozen-lockfile && pnpm format", + "update:example-deps": "node scripts/update-example-deps.mjs", "gpt-generate": "node gpt/generate.js", "set-ts-version": "node scripts/set-ts-version.js", "labeler-generate": "node scripts/generate-labeler-config.ts", @@ -61,45 +63,25 @@ ] }, "devDependencies": { - "@arethetypeswrong/cli": "^0.18.4", "@changesets/changelog-github": "^0.7.0", "@changesets/cli": "^2.30.0", - "@eslint-react/eslint-plugin": "^1.26.2", - "@nx/devkit": "22.7.5", + "@nx/devkit": "24.0.0", "@playwright/test": "catalog:", - "@swc-node/core": "^1.14.1", "@swc-node/register": "^1.11.1", "@tanstack/eslint-config": "0.4.0", - "@tanstack/query-core": "catalog:", - "@tanstack/react-query": "catalog:", - "@tanstack/solid-query": "catalog:", - "@tanstack/vite-config": "0.5.2", - "@tanstack/vue-query": "catalog:", "@types/node": "catalog:", - "@types/react": "catalog:", - "@types/react-dom": "catalog:", - "@vitest/browser": "^4.1.4", - "@vitest/ui": "^4.1.4", "eslint": "catalog:", - "eslint-plugin-react-hooks": "^5.1.0", "eslint-plugin-unused-imports": "^4.1.4", - "jsdom": "^25.0.1", "markdown-link-extractor": "^4.0.3", - "nx": "22.7.5", + "nx": "24.0.0", "prettier": "^3.8.0", - "publint": "^0.3.16", - "react": "catalog:", - "react-dom": "catalog:", - "redaxios": "^0.5.1", - "rimraf": "^6.1.2", "tinyglobby": "^0.2.15", - "typescript": "^6.0.2", - "typescript55": "npm:typescript@5.5", + "typescript": "npm:@typescript/typescript6@^6.0.2", + "vite": "catalog:", + "@typescript/native": "npm:typescript@^7.0.2", "typescript56": "npm:typescript@5.6", "typescript57": "npm:typescript@5.7", "typescript58": "npm:typescript@5.8", - "typescript59": "npm:typescript@5.9", - "vite": "catalog:", - "vitest": "^4.1.4" + "typescript59": "npm:typescript@5.9" } } diff --git a/packages/AGENTS.md b/packages/AGENTS.md new file mode 100644 index 0000000000..0c63c3a15c --- /dev/null +++ b/packages/AGENTS.md @@ -0,0 +1,16 @@ +# Packages + +- Route generation/code splitting live in `router-generator`/`router-plugin`; Start build transforms live in `start-plugin-core`. + +## Router bindings + +- Navigation/render identity is more than href or route membership: same-href navigations can have different history keys, and suspended renders must acknowledge only their own match publication. Preserve those identity checks when optimizing stores or render notifications. +- In navigation params/search, an explicit `undefined` can clear an inherited value; an absent key can inherit it. Preserve that distinction when comparing or memoizing options; React's `useValueStable` uses `deepEqual` with `ignoreUndefined: false`. + +## Tests + +- Inspect test commands: several `test:unit` scripts immediately exit or only echo a message. For these packages, validate behavior in the shared core or consuming e2e app; a successful placeholder target provides no unit coverage. +- For `*-router-ssr-query` changes, run `router-ssr-query-core` unit tests and the affected framework's `e2e/-start/query-integration` tests. The framework wrapper unit targets currently exit without running tests. +- For single-command Vitest targets, append filters after `--`, e.g. `-- tests/link.test.tsx -t "preloading"`. +- `solid-router` and `router-generator` chain two Vitest commands in `test:unit`. Trailing file/name/update arguments reach only the final command. Run the full target for verification: Solid needs browser and server suites; the generator needs fixture generation followed by typechecking. +- For public type changes, add `*.test-d.*` inference regressions and run both unit and type targets. React/Solid Router's TypeScript compiler matrix checks `src`; Vitest runs their inference tests. For changes to inference cost, follow the [type-safety performance guidance](../docs/router/guide/type-safety.md#performance-recommendations); `test:perf` measures runtime, not compiler cost. diff --git a/packages/arktype-adapter/package.json b/packages/arktype-adapter/package.json index f7840ba4f8..ceca3fad73 100644 --- a/packages/arktype-adapter/package.json +++ b/packages/arktype-adapter/package.json @@ -27,12 +27,12 @@ "clean": "rimraf ./dist && rimraf ./coverage", "test:eslint": "eslint ./src", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc", + "test:types:ts60": "tsc6", + "test:types:ts70": "tsc", "test:unit": "vitest", "test:unit:dev": "pnpm run test:unit --watch --typecheck", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", @@ -66,11 +66,19 @@ "devDependencies": { "@tanstack/react-router": "workspace:*", "arktype": "^2.1.7", - "@testing-library/jest-dom": "^6.6.3", - "@testing-library/react": "^16.2.0", - "react": "^19.0.0", - "react-dom": "^19.0.0", - "vite": "*" + "@testing-library/jest-dom": "catalog:", + "@testing-library/react": "catalog:", + "react": "catalog:", + "react-dom": "catalog:", + "vite": "*", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "jsdom": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" }, "peerDependencies": { "arktype": ">=2.0.0-rc <3", diff --git a/packages/arktype-adapter/tests/index.test.tsx b/packages/arktype-adapter/tests/index.test.tsx index a99ecda9c4..ce6eb74756 100644 --- a/packages/arktype-adapter/tests/index.test.tsx +++ b/packages/arktype-adapter/tests/index.test.tsx @@ -9,7 +9,6 @@ import { cleanup, fireEvent, render, screen } from '@testing-library/react' import { afterEach, expect, test, vi } from 'vitest' import { type } from 'arktype' import { arkTypeValidator } from '../src' -import '@testing-library/jest-dom/vitest' afterEach(() => { vi.resetAllMocks() diff --git a/packages/arktype-adapter/tests/jest-dom.setup.ts b/packages/arktype-adapter/tests/jest-dom.setup.ts new file mode 100644 index 0000000000..8f7cbf15be --- /dev/null +++ b/packages/arktype-adapter/tests/jest-dom.setup.ts @@ -0,0 +1,18 @@ +import * as jestDomMatchers from '@testing-library/jest-dom/matchers' +import { expect } from 'vitest' +import type { TestingLibraryMatchers } from '@testing-library/jest-dom/matchers' + +// Workaround for Vitest 5: remove once testing-library/jest-dom#742 is merged +// and released, and go back to `import '@testing-library/jest-dom/vitest'`. +// That entry imports `vitest` from its own install location, which can resolve +// a different Vitest copy than the one running these tests, and its types +// augment Vitest 4's `Assertion` instead of Vitest 5's `Matchers`. +// Keep `jest-dom` in this file name: vite-plugin-solid only skips injecting +// `@testing-library/jest-dom/vitest` when a setup file path contains it. +expect.extend(jestDomMatchers) + +declare module 'vitest' { + // Type parameter names must match Vitest's declaration for the interfaces to merge. + // eslint-disable-next-line @typescript-eslint/naming-convention + interface Matchers extends TestingLibraryMatchers {} +} diff --git a/packages/arktype-adapter/vite.config.ts b/packages/arktype-adapter/vite.config.ts index 8c8c0c519f..8d553e0a59 100644 --- a/packages/arktype-adapter/vite.config.ts +++ b/packages/arktype-adapter/vite.config.ts @@ -9,6 +9,7 @@ const config = defineConfig({ watch: false, environment: 'jsdom', typecheck: { enabled: true }, + setupFiles: ['./tests/jest-dom.setup.ts'], }, }) diff --git a/packages/eslint-plugin-router/package.json b/packages/eslint-plugin-router/package.json index b99ee55e13..9be54c220e 100644 --- a/packages/eslint-plugin-router/package.json +++ b/packages/eslint-plugin-router/package.json @@ -18,12 +18,12 @@ "clean": "rimraf ./dist ./coverage", "test:eslint": "eslint ./src", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc", + "test:types:ts60": "tsc6", + "test:types:ts70": "tsc", "test:unit": "vitest", "test:unit:dev": "pnpm run test:unit --watch --typecheck", "test:build": "publint --strict && attw --pack .", @@ -56,11 +56,26 @@ }, "devDependencies": { "@typescript-eslint/rule-tester": "^8.23.0", - "combinate": "^1.1.11", + "combinate": "catalog:", "eslint": "^9.22.0", - "vite": "*" + "vite": "*", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0" + }, + "nx": { + "targets": { + "build": { + "inputs": [ + "...", + "{workspaceRoot}/eslint.config.js" + ] + } + } } } diff --git a/packages/eslint-plugin-start/package.json b/packages/eslint-plugin-start/package.json index c4867c58d0..803264ed10 100644 --- a/packages/eslint-plugin-start/package.json +++ b/packages/eslint-plugin-start/package.json @@ -18,29 +18,29 @@ "clean": "rimraf ./dist ./coverage", "test:eslint": "eslint ./src", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc", + "test:types:ts60": "tsc6", + "test:types:ts70": "tsc", "test:unit": "vitest", "test:unit:dev": "pnpm run test:unit --watch --typecheck", "test:build": "publint --strict && attw --pack .", "build": "vite build && tsc --noEmit" }, "type": "module", - "types": "dist/esm/src/index.d.ts", + "types": "dist/esm/index.d.ts", "main": "dist/cjs/index.cjs", "module": "dist/esm/index.js", "exports": { ".": { "import": { - "types": "./dist/esm/src/index.d.ts", + "types": "./dist/esm/index.d.ts", "default": "./dist/esm/index.js" }, "require": { - "types": "./dist/cjs/src/index.d.cts", + "types": "./dist/cjs/index.d.cts", "default": "./dist/cjs/index.cjs" } }, @@ -58,10 +58,25 @@ "devDependencies": { "@typescript-eslint/rule-tester": "^8.44.1", "eslint": "^9.22.0", - "typescript": "^5.8.2" + "typescript": "^5.8.2", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" }, "peerDependencies": { - "eslint": "^8.57.0 || ^9.0.0", + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.7.0" + }, + "nx": { + "targets": { + "build": { + "inputs": [ + "...", + "{workspaceRoot}/eslint.config.js" + ] + } + } } } diff --git a/packages/history/AGENTS.md b/packages/history/AGENTS.md new file mode 100644 index 0000000000..509da6a4ec --- /dev/null +++ b/packages/history/AGENTS.md @@ -0,0 +1,3 @@ +# History + +Accepted browser push/replace operations update the in-memory location immediately and batch native writes into a microtask. Preserve coalescing: the latest href/state wins, but any queued push wins over replaces. Use `history.flush()` when native browser state must be current; verify subsequent updates still flush afterward in `tests/createBrowserHistory.test.ts`. diff --git a/packages/history/CHANGELOG.md b/packages/history/CHANGELOG.md index dbd02474bf..ca3341088c 100644 --- a/packages/history/CHANGELOG.md +++ b/packages/history/CHANGELOG.md @@ -1,5 +1,63 @@ # @tanstack/history +## 1.162.5 + +### Patch Changes + +- [#8605](https://github.com/TanStack/router/pull/8605) [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2) - Drop a duplicated current-location flag and a redundant `createHref` wrapper. + +- [#8605](https://github.com/TanStack/router/pull/8605) [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2) - Avoid temporary arrays when reading hash-history locations. + +- [#8605](https://github.com/TanStack/router/pull/8605) [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2) - Keep a leading query or fragment out of the parsed pathname, so hash-history URLs like `/#?x=1` no longer repeat the query in the router location. + +- [#8602](https://github.com/TanStack/router/pull/8602) [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb) - Fixed Link destinations that resolve to a route mask are now reused across navigations instead of being rebuilt every time. A mounted Link now follows changes to its `href` and `reloadDocument` props, and React Links no longer each subscribe to a hydration flag. + +- [#8605](https://github.com/TanStack/router/pull/8605) [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2) - Use `slice` instead of `substring` where the bounds are always ordered and non-negative. + +## 1.162.4 + +### Patch Changes + +- [#8359](https://github.com/TanStack/router/pull/8359) [`8fff7fa`](https://github.com/TanStack/router/commit/8fff7fa1f2e6f061916b0bf5e0ec486b2e732f94) - Normalize memory history hrefs consistently with browser and server history, including protocol-relative paths and control characters. + +- [#8352](https://github.com/TanStack/router/pull/8352) [`f021f6d`](https://github.com/TanStack/router/commit/f021f6d1c6dce6c9b54d70766f1d636d8fd9e184) - Avoid temporary arrays when replacing forward memory-history entries. + +- [#8349](https://github.com/TanStack/router/pull/8349) [`ae68535`](https://github.com/TanStack/router/commit/ae68535929043607d4ee9438f8ae401f3a064862) - Avoid generating unused history keys for locations with existing state. + +- [#8354](https://github.com/TanStack/router/pull/8354) [`9872d2a`](https://github.com/TanStack/router/commit/9872d2ac39fc05f4ef6566c0b421f71ceb115244) - Use lightweight request history for SSR and make server navigation a no-op. Use redirect() to issue HTTP redirects. Server hrefs use the same normalization as browser history to handle protocol-relative URLs and control characters. + +## 1.162.3 + +### Patch Changes + +- [#8308](https://github.com/TanStack/router/pull/8308) [`9c1871c`](https://github.com/TanStack/router/commit/9c1871ccc88bc1157186b8b460941a304ec740b8) - Validate navigation and redirect destinations, keep ambiguous relative URLs on the current origin, and constrain prerender requests and output paths. Prevent redirect headers from appearing in serialized server function response bodies. + + Preserve native form HTTP redirects, route error handling and masks for document redirects, and per-navigation destinations for shared loader redirects. Avoid redundant origin parsing and reduce link styling and server-rendering work. Configured origins must already be normalized. + + Keep blocked-link inactive props consistent during React hydration, honor explicit redirect Location headers before checking route options, and refresh Vue link state when destinations become internal. Reuse the protocol-relative URL check while parsing redirect schemes once. + + Reduce React link bundle size by sharing pathname comparisons, state-prop selection, and element creation. + + Share normalized pathname comparisons in Solid and Vue links to reduce bundle size. + +- [#8287](https://github.com/TanStack/router/pull/8287) [`0654c0a`](https://github.com/TanStack/router/commit/0654c0a1a427db24d9af13c1d6ad1217a588c0c9) - Use full-document navigation when an output rewrite produces a cross-origin destination, including the public URL of a route mask. + + Respect registered history blockers during document navigation, passing history locations and the requested push or replace action. + +## 1.162.2 + +### Patch Changes + +- [#8264](https://github.com/TanStack/router/pull/8264) [`9035abc`](https://github.com/TanStack/router/commit/9035abc41163d83409ef582f7743a3c7be57dd93) - Respect `ignoreBlocker` during `go()` navigation, including document unload warnings. Preserve beforeunload warnings during back and forward navigation unless `ignoreBlocker` is requested, and clear the bypass after same-document traversal so later document navigation still warns about unsaved changes. + + Restore the original browser history entry when forward or multi-entry navigation is blocked. + +## 1.162.1 + +### Patch Changes + +- [#7985](https://github.com/TanStack/router/pull/7985) [`9cac62a`](https://github.com/TanStack/router/commit/9cac62a5c7f99ef070991ea6f1fa7e42c746d46b) - perf: compact private bundle boundaries- [#7975](https://github.com/TanStack/router/issues/7975) + ## 1.162.0 ### Minor Changes diff --git a/packages/history/package.json b/packages/history/package.json index 790acabc3c..d09c710d2f 100644 --- a/packages/history/package.json +++ b/packages/history/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/history", - "version": "1.162.0", + "version": "1.162.5", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -22,12 +22,12 @@ "clean": "rimraf ./dist && rimraf ./coverage", "test:eslint": "eslint ./src", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc", + "test:types:ts60": "tsc6", + "test:types:ts70": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "test:unit": "vitest", "test:unit:dev": "pnpm run test:unit --watch", @@ -59,6 +59,12 @@ "node": ">=20.19" }, "devDependencies": { - "vite": "*" + "vite": "*", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "jsdom": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" } } diff --git a/packages/history/src/index.ts b/packages/history/src/index.ts index 0f3be8242e..d2f80581b9 100644 --- a/packages/history/src/index.ts +++ b/packages/history/src/index.ts @@ -36,7 +36,9 @@ export interface RouterHistory { flush: () => void destroy: () => void notify: (action: SubscriberHistoryAction) => void + _getBlockers: () => Array _ignoreSubscribers?: boolean + _ignoreNextBeforeUnload?: (href: string) => void } export interface HistoryLocation extends ParsedPath { @@ -96,12 +98,40 @@ const stateIndexKey = '__TSR_index' const popStateEvent = 'popstate' const beforeUnloadEvent = 'beforeunload' +/** + * Turn protocol-relative inputs such as "//evil.example" into paths + * such as "/evil.example", keeping navigation on the current origin. + * + * For HTTP(S) URLs, WHATWG parsing ignores leading C0 controls and spaces, + * removes tabs/newlines, and treats backslashes as slashes, so inputs like + * "/\evil.example" also need normalization. This only allocates when those + * rules would make the input protocol-relative. + */ +// eslint-disable-next-line no-control-regex +const protocolRelativePrefix = /^[\x00-\x20]*(?:[\\/][\t\n\r]*){2,}/ + +export function normalizeProtocolRelative(url: string): string { + const match = protocolRelativePrefix.exec(url) + return match ? '/' + url.slice(match[0].length) : url +} + +function normalizeHref(href: string): string { + // eslint-disable-next-line no-control-regex + if (/[\x00-\x1f\x7f]/.test(href)) { + // eslint-disable-next-line no-control-regex + href = href.replace(/[\x00-\x1f\x7f]/g, (character) => + '\t\n\r'.includes(character) ? '' : encodeURIComponent(character), + ) + } + return normalizeProtocolRelative(href) +} + export function createHistory(opts: { getLocation: () => HistoryLocation getLength: () => number pushState: (path: string, state: any) => void replaceState: (path: string, state: any) => void - go: (n: number) => void + go: (n: number, ignoreBlocker: boolean) => void back: (ignoreBlocker: boolean) => void forward: (ignoreBlocker: boolean) => void createHref: (path: string) => string @@ -126,27 +156,21 @@ export function createHistory(opts: { else location = opts.getLocation() } - const tryNavigation = async ({ - task, - navigateOpts, - ...actionInfo - }: TryNavigateArgs) => { - const ignoreBlocker = navigateOpts?.ignoreBlocker ?? false - if (ignoreBlocker) { - task() - return - } - - const blockers = opts.getBlockers?.() ?? [] - const isPushOrReplace = - actionInfo.type === 'PUSH' || actionInfo.type === 'REPLACE' - if (typeof document !== 'undefined' && blockers.length && isPushOrReplace) { + const tryNavigation = async (args: TryNavigateArgs) => { + const blockers = args.navigateOpts?.ignoreBlocker + ? undefined + : opts.getBlockers?.() + if ( + typeof document !== 'undefined' && + blockers?.length && + (args.type === 'PUSH' || args.type === 'REPLACE') + ) { for (const blocker of blockers) { - const nextLocation = parseHref(actionInfo.path, actionInfo.state) + const nextLocation = parseHref(args.path, args.state) const isBlocked = await blocker.blockerFn({ currentLocation: location, nextLocation, - action: actionInfo.type, + action: args.type, }) if (isBlocked) { opts.onBlocked?.() @@ -155,7 +179,7 @@ export function createHistory(opts: { } } - task() + args.task() } return { @@ -204,7 +228,7 @@ export function createHistory(opts: { go: (index, navigateOpts) => { tryNavigation({ task: () => { - opts.go(index) + opts.go(index, navigateOpts?.ignoreBlocker ?? false) handleIndexChange({ type: 'GO', index }) }, navigateOpts, @@ -246,13 +270,11 @@ export function createHistory(opts: { flush: () => opts.flush?.(), destroy: () => opts.destroy?.(), notify, + _getBlockers: () => opts.getBlockers?.() ?? [], } } function assignKeyAndIndex(index: number, state: HistoryState | undefined) { - if (!state) { - state = {} - } const key = createRandomKey() return { ...state, @@ -295,7 +317,8 @@ export function createBrowserHistory(opts?: { const _setBlockers = (newBlockers: Array) => (blockers = newBlockers) - const createHref = opts?.createHref ?? ((path) => path) + const createHref = (path: string) => + normalizeHref(opts?.createHref ? opts.createHref(path) : path) const parseLocation = opts?.parseLocation ?? (() => @@ -322,6 +345,9 @@ export function createBrowserHistory(opts?: { let nextPopIsGo = false let ignoreNextPop = false + // TODO: An ignored traversal past a history boundary emits neither popstate + // nor beforeunload, leaving these bypasses active for a later navigation. + // The History API provides no completion signal for such no-op traversals. let skipBlockerNextPop = false let ignoreNextBeforeUnload = false @@ -329,18 +355,14 @@ export function createBrowserHistory(opts?: { let next: | undefined - | { - // This is the latest location that we were attempting to push/replace - href: string - // This is the latest state that we were attempting to push/replace - state: any - // This is the latest type that we were attempting to push/replace - isPush: boolean - } - - // We need to track the current scheduled update to prevent - // multiple updates from being scheduled at the same time. - let scheduled: undefined | boolean + | [ + // The latest location that we were attempting to push/replace + href: string, + // The latest state that we were attempting to push/replace + state: any, + // Whether any queued update needs to push rather than replace + isPush: boolean, + ] // This function flushes the next update to the browser history const flush = () => { @@ -352,46 +374,47 @@ export function createBrowserHistory(opts?: { history._ignoreSubscribers = true // Update the browser history - ;(next.isPush ? win.history.pushState : win.history.replaceState)( - next.state, + ;(next[2 /* is push */] ? win.history.pushState : win.history.replaceState)( + next[1 /* state */], '', - next.href, + next[0 /* href */], ) // Stop ignoring subscriber updates history._ignoreSubscribers = false - // Reset the nextIsPush flag and clear the scheduled update + // Clear the queued action after it reaches browser history. next = undefined - scheduled = false rollbackLocation = undefined } // This function queues up a call to update the browser history const queueHistoryAction = ( - type: 'push' | 'replace', + isPush: boolean, destHref: string, state: any, ) => { - const href = createHref(destHref) + // A formatter changes the URL space and must receive the original input. + // Otherwise parseHref below already produces the browser destination. + const href = opts?.createHref ? createHref(destHref) : undefined + const hasPendingAction = !!next - if (!scheduled) { + if (!hasPendingAction) { rollbackLocation = currentLocation } - // Update the location in memory + // Keep the optimistic location in the router's logical URL space. currentLocation = parseHref(destHref, state) // Keep track of the next location we need to flush to the URL - next = { - href, + next = [ + href ?? currentLocation.href, state, - isPush: next?.isPush || type === 'push', - } + next?.[2 /* is push */] || isPush, + ] - if (!scheduled) { + if (!hasPendingAction) { // Schedule an update to the browser history - scheduled = true queueMicrotask(() => flush()) } } @@ -403,6 +426,10 @@ export function createBrowserHistory(opts?: { } const onPushPopEvent = async () => { + // Same-document traversals do not fire beforeunload, so consume their + // exemption here instead of carrying it into a later document navigation. + ignoreNextBeforeUnload = false + if (ignoreNextPop) { ignoreNextPop = false return @@ -439,7 +466,7 @@ export function createBrowserHistory(opts?: { }) if (isBlocked) { ignoreNextPop = true - win.history.go(1) + win.history.go(-delta) history.notify(notify) return } @@ -489,23 +516,31 @@ export function createBrowserHistory(opts?: { const history = createHistory({ getLocation, getLength: () => win.history.length, - pushState: (href, state) => queueHistoryAction('push', href, state), - replaceState: (href, state) => queueHistoryAction('replace', href, state), + pushState: (href, state) => queueHistoryAction(true, href, state), + replaceState: (href, state) => queueHistoryAction(false, href, state), back: (ignoreBlocker) => { - if (ignoreBlocker) skipBlockerNextPop = true - ignoreNextBeforeUnload = true + if (ignoreBlocker) { + skipBlockerNextPop = true + ignoreNextBeforeUnload = true + } return win.history.back() }, forward: (ignoreBlocker) => { - if (ignoreBlocker) skipBlockerNextPop = true - ignoreNextBeforeUnload = true + if (ignoreBlocker) { + skipBlockerNextPop = true + ignoreNextBeforeUnload = true + } win.history.forward() }, - go: (n) => { + go: (n, ignoreBlocker) => { nextPopIsGo = true + if (ignoreBlocker) { + skipBlockerNextPop = true + ignoreNextBeforeUnload = true + } win.history.go(n) }, - createHref: (href) => createHref(href), + createHref, flush, destroy: () => { win.history.pushState = originalPushState @@ -527,6 +562,21 @@ export function createBrowserHistory(opts?: { notifyOnIndexChange: false, }) + history._ignoreNextBeforeUnload = (href) => { + ignoreNextBeforeUnload = false + try { + href = new URL(href, win.document.baseURI).href + // External handlers and same-document fragments may emit neither + // beforeunload nor popstate, leaving an exemption for a later departure. + ignoreNextBeforeUnload = + /^https?:/.test(href) && + (!href.includes('#') || + href.split('#')[0] !== win.location.href.split('#')[0]) + } catch { + // Invalid URLs cannot unload the document. + } + } + win.addEventListener(beforeUnloadEvent, onBeforeUnload, { capture: true }) win.addEventListener(popStateEvent, onPushPopEvent) @@ -557,14 +607,17 @@ export function createHashHistory(opts?: { window?: any }): RouterHistory { return createBrowserHistory({ window: win, parseLocation: () => { - const hashSplit = win.location.hash.split('#').slice(1) - const pathPart = hashSplit[0] ?? '/' - const searchPart = win.location.search - const hashEntries = hashSplit.slice(1) - const hashPart = - hashEntries.length === 0 ? '' : `#${hashEntries.join('#')}` - const hashHref = `${pathPart}${searchPart}${hashPart}` - return parseHref(hashHref, win.history.state) + // `#/path?query#fragment`: the router's own fragment starts at the + // second '#'. A non-empty `location.hash` always starts with '#'. + const hash = win.location.hash + let hashIndex = hash.indexOf('#', 1) + if (hashIndex < 0) { + hashIndex = hash.length + } + return parseHref( + `${hash ? hash.slice(1, hashIndex) : '/'}${win.location.search}${hash.slice(hashIndex)}`, + win.history.state, + ) }, createHref: (href) => `${win.location.pathname}${win.location.search}#${href}`, @@ -604,13 +657,13 @@ export function createMemoryHistory( getLength: () => entries.length, pushState: (path, state) => { // Removes all subsequent entries after the current index to start a new branch + index = index < entries.length - 1 ? index + 1 : entries.length + states[index] = state + entries[index] = path if (index < entries.length - 1) { - entries.splice(index + 1) - states.splice(index + 1) + entries.length = index + 1 + states.length = index + 1 } - states.push(state) - entries.push(path) - index = Math.max(entries.length - 1, 0) }, replaceState: (path, state) => { states[index] = state @@ -625,54 +678,89 @@ export function createMemoryHistory( go: (n) => { index = Math.min(Math.max(index + n, 0), entries.length - 1) }, - createHref: (path) => path, + createHref: normalizeHref, getBlockers: _getBlockers, setBlockers: _setBlockers, }) } -/** - * Sanitize a path to prevent open redirect vulnerabilities. - * Removes control characters and collapses leading double slashes. - */ -function sanitizePath(path: string): string { - // Remove ASCII control characters (0x00-0x1F) and DEL (0x7F) - // These include CR (\r = 0x0D), LF (\n = 0x0A), and other potentially dangerous characters - // eslint-disable-next-line no-control-regex - let sanitized = path.replace(/[\x00-\x1f\x7f]/g, '') +const noop = () => {} - // Prevent open redirect via protocol-relative URLs (e.g. "//evil.com") - // Collapse leading double slashes to a single slash - if (sanitized.startsWith('//')) { - sanitized = '/' + sanitized.replace(/^\/+/, '') +class ServerHistory implements RouterHistory { + declare private _subscribers?: RouterHistory['subscribers'] + + constructor(public location: HistoryLocation) {} + + get length() { + return 1 } - return sanitized + // Preserve the history interface without allocating a Set for each request. + get subscribers() { + return (this._subscribers ??= new Set()) + } + + subscribe() { + return noop + } + + push() {} + replace() {} + go() {} + back() {} + forward() {} + + canGoBack() { + return false + } + + createHref(href: string) { + return normalizeHref(href) + } + + block() { + return noop + } + + flush() {} + destroy() {} + notify() {} + + _getBlockers(): Array { + return [] + } +} + +/** A fixed request location; server navigation is a no-op. */ +export function createServerHistory(href: string): RouterHistory { + return new ServerHistory(parseHref(href, undefined)) } export function parseHref( href: string, state: ParsedHistoryState | undefined, ): HistoryLocation { - const sanitizedHref = sanitizePath(href) + const sanitizedHref = normalizeHref(href) const hashIndex = sanitizedHref.indexOf('#') const searchIndex = sanitizedHref.indexOf('?') - - const addedKey = createRandomKey() + if (!state) { + const key = createRandomKey() + state = { [stateIndexKey]: 0, key, __TSR_key: key } + } return { href: sanitizedHref, - pathname: sanitizedHref.substring( + pathname: sanitizedHref.slice( 0, - hashIndex > 0 - ? searchIndex > 0 + hashIndex > -1 + ? searchIndex > -1 ? Math.min(hashIndex, searchIndex) : hashIndex - : searchIndex > 0 + : searchIndex > -1 ? searchIndex : sanitizedHref.length, ), - hash: hashIndex > -1 ? sanitizedHref.substring(hashIndex) : '', + hash: hashIndex > -1 ? sanitizedHref.slice(hashIndex) : '', search: searchIndex > -1 ? sanitizedHref.slice( @@ -680,11 +768,11 @@ export function parseHref( hashIndex === -1 ? undefined : hashIndex, ) : '', - state: state || { [stateIndexKey]: 0, key: addedKey, __TSR_key: addedKey }, + state, } } // Thanks co-pilot! function createRandomKey() { - return (Math.random() + 1).toString(36).substring(7) + return (Math.random() + 1).toString(36).slice(7) } diff --git a/packages/history/tests/createBrowserHistory.test.ts b/packages/history/tests/createBrowserHistory.test.ts new file mode 100644 index 0000000000..5b24744fb5 --- /dev/null +++ b/packages/history/tests/createBrowserHistory.test.ts @@ -0,0 +1,307 @@ +import { describe, expect, test, vi } from 'vitest' +import { createBrowserHistory } from '../src' + +function createBrowserHistoryHarness(createHref?: (path: string) => string) { + const listeners = new Map any>() + const location = { + pathname: '/', + search: '', + hash: '', + } + const pushState = vi.fn() + const replaceState = vi.fn() + const nativeHistory = { + state: { __TSR_index: 0, __TSR_key: 'initial' }, + length: 1, + pushState, + replaceState, + back: vi.fn(), + forward: vi.fn(), + go: vi.fn(), + } + const window = { + location, + history: nativeHistory, + addEventListener: vi.fn((type: string, listener: (event: any) => any) => { + listeners.set(type, listener) + }), + removeEventListener: vi.fn((type: string) => { + listeners.delete(type) + }), + dispatchEvent: (event: { type: string }) => + listeners.get(event.type)?.(event), + } + const history = createBrowserHistory({ window, createHref }) + + return { + history, + pushState, + replaceState, + window, + } +} + +describe('createBrowserHistory', () => { + test('passes the original destination to a custom formatter', () => { + const { history, pushState } = createBrowserHistoryHarness( + (href) => '/mapped?value=' + encodeURIComponent(href), + ) + history.push('/a\tb') + history.flush() + expect(pushState).toHaveBeenCalledWith( + expect.anything(), + '', + '/mapped?value=%2Fa%09b', + ) + expect(history.location.href).toBe('/ab') + history.destroy() + }) + + test.each(['/a\x00b?q=a\x01b#/\\section\x7f', '/a\tb?q=a\nb#/\\section\r'])( + 'preserves the browser interpretation of %j', + (href) => { + const originalHref = window.location.href + const expected = new URL(href, originalHref) + const history = createBrowserHistory() + try { + expect(new URL(history.createHref(href), originalHref).href).toBe( + expected.href, + ) + history.push(href) + history.flush() + expect(window.location.href).toBe(expected.href) + expect(new URL(history.location.href, originalHref).href).toBe( + expected.href, + ) + } finally { + history.destroy() + window.history.replaceState(null, '', originalHref) + } + }, + ) + + test('coalesces consecutive replaces into the latest replace', async () => { + const { history, pushState, replaceState } = createBrowserHistoryHarness() + + history.replace('/first', { value: 1 }) + history.replace('/second', { value: 2 }) + await Promise.resolve() + + expect(pushState).not.toHaveBeenCalled() + expect(replaceState).toHaveBeenCalledTimes(1) + expect(replaceState).toHaveBeenCalledWith( + expect.objectContaining({ value: 2 }), + '', + '/second', + ) + history.destroy() + }) + + test('promotes a queued replace to a push', async () => { + const { history, pushState, replaceState } = createBrowserHistoryHarness() + + history.replace('/first', { value: 1 }) + history.push('/second', { value: 2 }) + await Promise.resolve() + + expect(replaceState).not.toHaveBeenCalled() + expect(pushState).toHaveBeenCalledTimes(1) + expect(pushState).toHaveBeenCalledWith( + expect.objectContaining({ value: 2 }), + '', + '/second', + ) + history.destroy() + }) + + test('keeps a queued push when followed by a replace', async () => { + const { history, pushState, replaceState } = createBrowserHistoryHarness() + + history.push('/first', { value: 1 }) + history.replace('/second', { value: 2 }) + await Promise.resolve() + + expect(replaceState).not.toHaveBeenCalled() + expect(pushState).toHaveBeenCalledTimes(1) + expect(pushState).toHaveBeenCalledWith( + expect.objectContaining({ value: 2 }), + '', + '/second', + ) + history.destroy() + }) + + test('flushes a later action after an explicit flush', async () => { + const { history, pushState, replaceState } = createBrowserHistoryHarness() + + history.replace('/first', { value: 1 }) + history.flush() + await Promise.resolve() + history.replace('/second', { value: 2 }) + await Promise.resolve() + + expect(pushState).not.toHaveBeenCalled() + expect(replaceState).toHaveBeenCalledTimes(2) + expect(replaceState).toHaveBeenLastCalledWith( + expect.objectContaining({ value: 2 }), + '', + '/second', + ) + history.destroy() + }) + + test.each([ + '//evil.com/path', + '///evil.com/path', + '/\\evil.com/path', + '/\\\\evil.com/path', + '/\\/evil.com/path', + '\\/evil.com/path', + '\\\\evil.com/path', + ' /\\evil.com/path', + '\x01//evil.com/path', + '/\t/evil.com/path', + ])('sanitizes %j before calling the native History API', async (href) => { + const { history, pushState } = createBrowserHistoryHarness() + + history.push(href) + await Promise.resolve() + + expect(pushState).toHaveBeenCalledOnce() + const pushedHref = pushState.mock.calls[0]![2] + const serializedUrl = new URL(pushedHref, 'https://victim.example') + expect(serializedUrl.origin).toBe('https://victim.example') + expect(serializedUrl.pathname).toBe( + href === '\x01//evil.com/path' ? '/%01//evil.com/path' : '/evil.com/path', + ) + expect( + new URL(history.location.href, 'https://victim.example').origin, + ).toBe('https://victim.example') + history.destroy() + }) + + test('does not exempt a normal traversal from beforeunload blockers', () => { + const { history, window } = createBrowserHistoryHarness() + history.block({ blockerFn: vi.fn(), enableBeforeUnload: true }) + + history.back() + const event = { + type: 'beforeunload', + preventDefault: vi.fn(), + returnValue: undefined, + } + window.dispatchEvent(event) + + expect(event.preventDefault).toHaveBeenCalledOnce() + expect(event.returnValue).toBe('') + history.destroy() + }) + + test('exempts an ignored document traversal from beforeunload blockers', () => { + const { history, window } = createBrowserHistoryHarness() + history.block({ blockerFn: vi.fn(), enableBeforeUnload: true }) + + history.back({ ignoreBlocker: true }) + const event = { + type: 'beforeunload', + preventDefault: vi.fn(), + returnValue: undefined, + } + window.dispatchEvent(event) + + expect(event.preventDefault).not.toHaveBeenCalled() + expect(event.returnValue).toBeUndefined() + history.destroy() + }) + + test('passes the logical requested destination to blockers', async () => { + const { history } = createBrowserHistoryHarness( + () => '/mapped/../browser-destination', + ) + const blockerFn = vi.fn(() => true) + history.block({ blockerFn, enableBeforeUnload: false }) + + history.push('/logical/../destination?query=value#hash') + await Promise.resolve() + + expect(blockerFn).toHaveBeenCalledWith( + expect.objectContaining({ + action: 'PUSH', + nextLocation: expect.objectContaining({ + href: '/logical/../destination?query=value#hash', + pathname: '/logical/../destination', + search: '?query=value', + hash: '#hash', + }), + }), + ) + history.destroy() + }) + + test('normalizes the final result of a custom createHref', async () => { + const { history, pushState, replaceState } = createBrowserHistoryHarness( + () => ' \t/\\evil.example/path', + ) + + expect(history.createHref('/safe')).toBe('/evil.example/path') + + history.push('/safe') + await Promise.resolve() + history.replace('/safe') + await Promise.resolve() + + expect(pushState).toHaveBeenCalledWith( + expect.anything(), + '', + '/evil.example/path', + ) + expect(replaceState).toHaveBeenCalledWith( + expect.anything(), + '', + '/evil.example/path', + ) + expect(history.location.href).toBe('/safe') + history.destroy() + }) + + test('keeps the optimistic location in the logical URL space', async () => { + const { history, pushState } = createBrowserHistoryHarness( + () => '/mapped/../browser-destination', + ) + + history.push('/logical/../destination?query=value#hash') + await Promise.resolve() + + expect(history.location).toMatchObject({ + href: '/logical/../destination?query=value#hash', + pathname: '/logical/../destination', + search: '?query=value', + hash: '#hash', + }) + expect(pushState).toHaveBeenCalledWith( + expect.anything(), + '', + '/mapped/../browser-destination', + ) + history.destroy() + }) + + test('does not retain a beforeunload exemption after a same-document traversal', async () => { + const { history, window } = createBrowserHistoryHarness() + history.block({ blockerFn: vi.fn(), enableBeforeUnload: true }) + + history.back({ ignoreBlocker: true }) + await window.dispatchEvent({ type: 'popstate' }) + + const event = { + type: 'beforeunload', + preventDefault: vi.fn(), + returnValue: undefined, + } + window.dispatchEvent(event) + + expect(event.preventDefault).toHaveBeenCalledOnce() + expect(event.returnValue).toBe('') + history.destroy() + }) +}) diff --git a/packages/history/tests/createHashHistory.test.ts b/packages/history/tests/createHashHistory.test.ts index 4d68238249..e54b1a1ae1 100644 --- a/packages/history/tests/createHashHistory.test.ts +++ b/packages/history/tests/createHashHistory.test.ts @@ -1,8 +1,162 @@ -import { describe, expect, test } from 'vitest' +import { describe, expect, test, vi } from 'vitest' import { createHashHistory } from '../src' describe('createHashHistory', () => { + test.each(['\x00/route', '/route\x01', '/route?q=a\x1fb#c\x7fd'])( + 'keeps logical control data stable after reading the browser URL again: %j', + (href) => { + const originalHref = window.location.href + window.history.replaceState(null, '', '/shell') + const history = createHashHistory() + let reloaded: ReturnType | undefined + try { + history.push(href) + history.flush() + const location = history.location + history.destroy() + reloaded = createHashHistory() + expect(reloaded.location).toEqual(location) + } finally { + history.destroy() + reloaded?.destroy() + window.history.replaceState(null, '', originalHref) + } + }, + ) + + test('reads a hash route that starts with a query without leaking it into the pathname', () => { + const window = { + location: { pathname: '/', search: '', hash: '#?x=1' }, + history: { + state: { __TSR_index: 0, __TSR_key: 'initial' }, + length: 1, + pushState: vi.fn(), + replaceState: vi.fn(), + back: vi.fn(), + forward: vi.fn(), + go: vi.fn(), + }, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + } + const history = createHashHistory({ window }) + + expect(history.location).toMatchObject({ + href: '?x=1', + pathname: '', + search: '?x=1', + hash: '', + }) + history.destroy() + }) + + test('normalizes the final browser href without changing the logical hash location', async () => { + const pushState = vi.fn() + const window = { + location: { + pathname: '//nested/path', + search: '', + hash: '', + }, + history: { + state: { __TSR_index: 0, __TSR_key: 'initial' }, + length: 1, + pushState, + replaceState: vi.fn(), + back: vi.fn(), + forward: vi.fn(), + go: vi.fn(), + }, + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + } + const history = createHashHistory({ window }) + + history.push('/logical') + await Promise.resolve() + + expect(pushState).toHaveBeenCalledWith( + expect.anything(), + '', + '/nested/path#/logical', + ) + expect(history.location.href).toBe('/logical') + history.destroy() + }) + + test.each([ + [ + '/?shell=1#/hello#section#tail', + { + href: '/hello?shell=1#section#tail', + pathname: '/hello', + search: '?shell=1', + hash: '#section#tail', + }, + ], + [ + '/?shell=1#/hello?route=2#section', + { + href: '/hello?route=2?shell=1#section', + pathname: '/hello', + search: '?route=2?shell=1', + hash: '#section', + }, + ], + [ + '/#/hello##tail#', + { + href: '/hello##tail#', + pathname: '/hello', + search: '', + hash: '##tail#', + }, + ], + [ + '/#/hello%23nested?value=%23#anchor%23tail', + { + href: '/hello%23nested?value=%23#anchor%23tail', + pathname: '/hello%23nested', + search: '?value=%23', + hash: '#anchor%23tail', + }, + ], + [ + '/?shell=1#//evil.example/path#fragment', + { + href: '/evil.example/path?shell=1#fragment', + pathname: '/evil.example/path', + search: '?shell=1', + hash: '#fragment', + }, + ], + [ + '/?shell=1#', + { + href: '/?shell=1', + pathname: '/', + search: '?shell=1', + hash: '', + }, + ], + ])('preserves the logical URL when reading %s', (href, expected) => { + const originalHref = window.location.href + const originalState = window.history.state + window.history.replaceState(null, '', href) + const history = createHashHistory() + + try { + expect(history.location).toMatchObject(expected) + window.history.replaceState(window.history.state, '', '/shell') + window.history.pushState(window.history.state, '', href) + expect(history.location).toMatchObject(expected) + } finally { + history.destroy() + window.history.replaceState(originalState, '', originalHref) + } + }) + describe('parseLocation', () => { describe.each([ ['/', { pathname: '/', search: '' }, 'neither search params nor hash'], diff --git a/packages/history/tests/createMemoryHistory.test.ts b/packages/history/tests/createMemoryHistory.test.ts index 1a27c04919..c0f565115e 100644 --- a/packages/history/tests/createMemoryHistory.test.ts +++ b/packages/history/tests/createMemoryHistory.test.ts @@ -2,6 +2,53 @@ import { describe, expect, test, vi } from 'vitest' import { createMemoryHistory } from '../src' describe('createMemoryHistory', () => { + test.each([ + ['//example.com/path', '/example.com/path'], + ['/\\example.com/path', '/example.com/path'], + ['\\/example.com/path', '/example.com/path'], + ['\\\\example.com/path', '/example.com/path'], + [' \t/\r\\example.com/path', '/example.com/path'], + ['/\t/example.com/path', '/example.com/path'], + ['/a\tb?q=a\nb#section\r', '/ab?q=ab#section'], + ['/a\u0000b?q=a\u0001b#section\u007f', '/a%00b?q=a%01b#section%7F'], + ['/', '/'], + ['/posts/123?sort=new#comments', '/posts/123?sort=new#comments'], + ['/caf%C3%A9?q=%2F#//section', '/caf%C3%A9?q=%2F#//section'], + ['/a//b?q=//value#\\/section', '/a//b?q=//value#\\/section'], + ['/%2Fexample.com/path', '/%2Fexample.com/path'], + ])('creates href %j consistent with navigation', (href, expected) => { + const history = createMemoryHistory() + const location = history.location + const createdHref = history.createHref(href) + + expect(createdHref).toBe(expected) + expect(history.location).toBe(location) + expect(new URL(createdHref, 'https://app.example').origin).toBe( + 'https://app.example', + ) + + history.push(href) + expect(history.location.href).toBe(createdHref) + }) + + test('exposes the current blocker registry after registration and removal', () => { + const history = createMemoryHistory() + const first = { blockerFn: vi.fn(() => true) } + const second = { blockerFn: vi.fn(() => false) } + + expect(history._getBlockers()).toEqual([]) + + const removeFirst = history.block(first) + const removeSecond = history.block(second) + expect(history._getBlockers()).toEqual([first, second]) + + removeFirst() + expect(history._getBlockers()).toEqual([second]) + + removeSecond() + expect(history._getBlockers()).toEqual([]) + }) + test('back', () => { const initialEntry = '/initial' const history = createMemoryHistory({ initialEntries: [initialEntry] }) @@ -52,6 +99,38 @@ describe('createMemoryHistory', () => { expect(history.location.pathname).toBe('/b') }) + test('discards forward entries and their state when pushing a new branch', () => { + const initialEntries = ['/'] + const history = createMemoryHistory({ initialEntries }) + history.push('/kept', { marker: 'kept' }) + const keptState = history.location.state + history.push('/discarded-first', { marker: 'discarded-first' }) + history.push('/discarded-last', { marker: 'discarded-last' }) + history.go(-2) + history.push('/new', { marker: 'new' }) + + expect(initialEntries).toEqual(['/', '/kept', '/new']) + expect(history.length).toBe(3) + expect(history.location.pathname).toBe('/new') + expect(history.location.state).toMatchObject({ + __TSR_index: 2, + marker: 'new', + }) + const newState = history.location.state + + history.forward() + expect(history.location.pathname).toBe('/new') + expect(history.location.state).toBe(newState) + + history.back() + expect(history.location.pathname).toBe('/kept') + expect(history.location.state).toBe(keptState) + + history.forward() + expect(history.location.pathname).toBe('/new') + expect(history.location.state).toBe(newState) + }) + test('length', () => { const history = createMemoryHistory() expect(history.length).toBe(1) diff --git a/packages/history/tests/createServerHistory.test.ts b/packages/history/tests/createServerHistory.test.ts new file mode 100644 index 0000000000..c036cea185 --- /dev/null +++ b/packages/history/tests/createServerHistory.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, test, vi } from 'vitest' +import { + createBrowserHistory, + createMemoryHistory, + createServerHistory, +} from '../src' + +describe('server history', () => { + test.each([ + '/', + '/posts/123?sort=new#comments', + '/caf%C3%A9?q=%2F#//section', + '//example.com/path', + '/\\example.com/path', + '/path\nname?value=\u0000', + ])('parses and sanitizes %j like memory history', (href) => { + const history = createServerHistory(href) + const memory = createMemoryHistory({ initialEntries: [href] }) + expect(history.location).toEqual({ + ...memory.location, + state: { + key: expect.any(String), + __TSR_key: expect.any(String), + __TSR_index: 0, + }, + }) + expect(history.location.state.key).toBe(history.location.state.__TSR_key) + }) + + test.each([ + '//evil.example/path', + '/\\evil.example/path', + '\\/evil.example/path', + '\\\\evil.example/path', + ' \t/\r\\evil.example/path', + '/\t/evil.example/path', + '/a\tb?q=a\nb#section\r', + '/a\u0000b?q=a\u0001b#section\u007f', + '/', + '/posts/123?sort=new#comments', + '/caf%C3%A9?q=%2F#//section', + '/a//b?q=//value#\\/section', + '/%2Fevil.example/path', + ])('normalizes href %j like browser history', (href) => { + const history = createServerHistory('/request') + const browser = createBrowserHistory() + try { + expect(history.createHref(href)).toBe(browser.createHref(href)) + expect(history.location.href).toBe('/request') + } finally { + browser.destroy() + } + }) + + test('ignores navigation, subscriptions, and blockers', () => { + const history = createServerHistory('/request?q=1') + const location = history.location + const subscriber = vi.fn() + const blockerFn = vi.fn(() => true) + const unsubscribe = history.subscribe(subscriber) + const unblock = history.block({ blockerFn }) + + history.push('/pushed', { value: 1 }) + history.replace('/replaced', { value: 2 }) + history.go(-1) + history.back() + history.forward() + history.notify({ type: 'PUSH' }) + history.flush() + history.destroy() + unsubscribe() + unblock() + + expect(history.location).toBe(location) + expect(history.length).toBe(1) + expect(history.canGoBack()).toBe(false) + expect(history.subscribers.size).toBe(0) + expect(history._getBlockers()).toEqual([]) + expect(subscriber).not.toHaveBeenCalled() + expect(blockerFn).not.toHaveBeenCalled() + }) + + test('isolates state and exposed collections between requests', () => { + const first = createServerHistory('/first') + const second = createServerHistory('/second') + first.location.state.__TSR_index = 10 + first.subscribers.add(vi.fn()) + first._getBlockers().push({ blockerFn: () => true }) + + expect(second.location.pathname).toBe('/second') + expect(second.location.state.__TSR_index).toBe(0) + expect(second.subscribers.size).toBe(0) + expect(second._getBlockers()).toEqual([]) + }) +}) diff --git a/packages/history/tests/parseHref.test.ts b/packages/history/tests/parseHref.test.ts index e1b8db9c1a..aa6882e6fc 100644 --- a/packages/history/tests/parseHref.test.ts +++ b/packages/history/tests/parseHref.test.ts @@ -1,7 +1,19 @@ import { describe, expect, test } from 'vitest' import { parseHref } from '../src' +const baseUrl = new URL('https://victim.example/base') + describe('parseHref', () => { + test.each(['\x00', '\x01', '\x1f', '\x7f', '\t', '\n', '\r'])( + 'preserves browser path, query, and fragment interpretation for %j', + (character) => { + const href = `/a${character}b?q=a${character}b#a${character}b` + expect(new URL(parseHref(href, undefined).href, baseUrl).href).toBe( + new URL(href, baseUrl).href, + ) + }, + ) + test('works', () => { const parsed = parseHref('/foo?bar=baz#qux', {} as any) expect(parsed.pathname).toEqual('/foo') @@ -9,6 +21,42 @@ describe('parseHref', () => { expect(parsed.hash).toEqual('#qux') }) + test.each([ + ['?x=1', { pathname: '', search: '?x=1', hash: '' }], + ['#top', { pathname: '', search: '', hash: '#top' }], + ['?x=1#top', { pathname: '', search: '?x=1', hash: '#top' }], + ['#top?x=1', { pathname: '', search: '', hash: '#top?x=1' }], + ])( + 'keeps a leading query or fragment out of the pathname: %j', + (href, expected) => { + expect(parseHref(href, undefined)).toMatchObject({ href, ...expected }) + }, + ) + + test.each([ + { __TSR_index: 2 }, + { __TSR_index: 2, key: 'legacy-key', __TSR_key: 'current-key' }, + ])('preserves supplied state %j', (state) => { + Object.freeze(state) + expect(parseHref('/foo', state).state).toBe(state) + }) + + test('creates independent initial states with matching history keys', () => { + const first = parseHref('/foo', undefined) + const second = parseHref('/bar', undefined) + + for (const location of [first, second]) { + expect(location.state).toEqual({ + __TSR_index: 0, + key: expect.any(String), + __TSR_key: location.state.key, + }) + } + + first.state.__TSR_index = 1 + expect(second.state.__TSR_index).toBe(0) + }) + describe('open redirect prevention', () => { test('strips CR characters to prevent open redirect', () => { // If \r (CR) is in the href, it should be stripped @@ -45,6 +93,86 @@ describe('parseHref', () => { expect(url.pathname).toBe('/evil.com/') }) + test.each([ + '//evil.com/path', + '///evil.com/path', + '/\\evil.com/path', + '/\\\\evil.com/path', + '/\\/evil.com/path', + '\\/evil.com/path', + '\\\\evil.com/path', + ' /\\evil.com/path', + '\x01//evil.com/path', + '/\t/evil.com/path', + ])('keeps protocol-relative input %j on the current origin', (href) => { + const parsed = parseHref(href, undefined) + const url = new URL(parsed.href, 'https://victim.example') + + expect(url.origin).toBe('https://victim.example') + }) + + test.each([ + 'h\x00ttps://evil.example', + 'java\x00script:alert(1)', + '/\x00/evil.example', + '\x7f//evil.example', + '/%5c/evil.example', + '/%2f/evil.example', + '?next=//evil.example', + '#//evil.example', + '//evil.example', + '', + ' ', + '\x00', + '\x00\t\n', + ])('does not make same-origin input %j cross-origin', (href) => { + expect(new URL(href, baseUrl).origin).toBe(baseUrl.origin) + + const parsed = parseHref(href, undefined) + + expect(new URL(parsed.href, baseUrl).origin).toBe(baseUrl.origin) + }) + + test('matches WHATWG parsing of protocol-relative prefixes', () => { + const alphabet = [ + '/', + '\\', + '\t', + '\n', + '\r', + '\x00', + '\x0b', + ' ', + '\x7f', + ] + + for (let length = 0; length <= 4; length++) { + const count = alphabet.length ** length + for (let value = 0; value < count; value++) { + let input = '' + let cursor = value + for (let index = 0; index < length; index++) { + input += alphabet[cursor % alphabet.length] + cursor = Math.floor(cursor / alphabet.length) + } + input += 'evil.example/path' + + try { + new URL(input, baseUrl) + } catch { + continue + } + + const parsed = parseHref(input, undefined) + + expect( + new URL(parsed.href, baseUrl).origin, + JSON.stringify(input), + ).toBe(baseUrl.origin) + } + } + }) + test('normal paths remain unchanged', () => { const parsed = parseHref('/users/profile?id=1#section', undefined) expect(parsed.href).toBe('/users/profile?id=1#section') diff --git a/packages/nitro-v2-vite-plugin/CHANGELOG.md b/packages/nitro-v2-vite-plugin/CHANGELOG.md deleted file mode 100644 index 934532d11b..0000000000 --- a/packages/nitro-v2-vite-plugin/CHANGELOG.md +++ /dev/null @@ -1,19 +0,0 @@ -# @tanstack/nitro-v2-vite-plugin - -## 1.155.0 - -### Minor Changes - -- Clean minor bump, fresh start ([#7395](https://github.com/TanStack/router/pull/7395)) - -## 1.154.9 - -### Patch Changes - -- build: update to vite-config 5.x (rolldown) ([#6926](https://github.com/TanStack/router/pull/6926)) - -## 1.154.8 - -### Patch Changes - -- fix: build with @tanstack/vite-config 0.4.3 ([#6923](https://github.com/TanStack/router/pull/6923)) diff --git a/packages/nitro-v2-vite-plugin/README.md b/packages/nitro-v2-vite-plugin/README.md deleted file mode 100644 index 5882e61120..0000000000 --- a/packages/nitro-v2-vite-plugin/README.md +++ /dev/null @@ -1 +0,0 @@ -# Experimental Nitro v2 Vite Plugin diff --git a/packages/nitro-v2-vite-plugin/eslint.config.js b/packages/nitro-v2-vite-plugin/eslint.config.js deleted file mode 100644 index 8ce6ad05fc..0000000000 --- a/packages/nitro-v2-vite-plugin/eslint.config.js +++ /dev/null @@ -1,5 +0,0 @@ -// @ts-check - -import rootConfig from '../../eslint.config.js' - -export default [...rootConfig] diff --git a/packages/nitro-v2-vite-plugin/package.json b/packages/nitro-v2-vite-plugin/package.json deleted file mode 100644 index b3021ea3c6..0000000000 --- a/packages/nitro-v2-vite-plugin/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "name": "@tanstack/nitro-v2-vite-plugin", - "version": "1.155.0", - "description": "Modern and scalable routing for React applications", - "author": "Tanner Linsley", - "license": "MIT", - "repository": { - "type": "git", - "url": "git+https://github.com/TanStack/router.git", - "directory": "packages/nitro-v2-vite-plugin" - }, - "homepage": "https://tanstack.com/router", - "funding": { - "type": "github", - "url": "https://github.com/sponsors/tannerlinsley" - }, - "keywords": [ - "react", - "location", - "router", - "routing", - "async", - "async router", - "typescript" - ], - "scripts": { - "clean": "rimraf ./dist && rimraf ./coverage", - "test": "pnpm test:eslint && pnpm test:types && pnpm test:build && pnpm test:unit", - "test:unit": "echo 'No unit tests are needed here since we do them in @tanstack/router-plugin!'", - "test:eslint": "eslint ./src", - "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", - "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", - "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", - "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", - "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc", - "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", - "build": "vite build" - }, - "type": "module", - "types": "dist/esm/index.d.ts", - "main": "dist/cjs/index.cjs", - "module": "dist/esm/index.js", - "exports": { - ".": { - "import": { - "types": "./dist/esm/index.d.ts", - "default": "./dist/esm/index.js" - } - }, - "./package.json": "./package.json" - }, - "sideEffects": false, - "files": [ - "dist", - "src" - ], - "engines": { - "node": ">=22.12" - }, - "dependencies": { - "nitropack": "^2.13.1", - "pathe": "^2.0.3" - }, - "peerDependencies": { - "vite": ">=7.0.0" - } -} diff --git a/packages/nitro-v2-vite-plugin/src/index.ts b/packages/nitro-v2-vite-plugin/src/index.ts deleted file mode 100644 index d8ae5009de..0000000000 --- a/packages/nitro-v2-vite-plugin/src/index.ts +++ /dev/null @@ -1,197 +0,0 @@ -import { build, copyPublicAssets, createNitro, prepare } from 'nitropack' -import { dirname, resolve } from 'pathe' - -import type { PluginOption, ResolvedConfig, Rollup } from 'vite' -import type { NitroConfig } from 'nitropack' - -let ssrBundle: Rollup.OutputBundle -let ssrEntryFile: string - -function isFullUrl(str: string): boolean { - try { - new URL(str) - return true - } catch { - return false - } -} - -export function nitroV2Plugin(nitroConfig?: NitroConfig): Array { - let resolvedConfig: ResolvedConfig - return [ - { - name: 'tanstack-nitro-v2-vite-plugin', - - generateBundle: { - handler(_options, bundle) { - if (this.environment.name !== 'ssr') { - return - } - - // find entry point of ssr bundle - let entryFile: string | undefined - for (const [_name, file] of Object.entries(bundle)) { - if (file.type === 'chunk') { - if (file.isEntry) { - if (entryFile !== undefined) { - this.error( - `Multiple entry points found for service "${this.environment.name}". Only one entry point is allowed.`, - ) - } - entryFile = file.fileName - } - } - } - if (entryFile === undefined) { - this.error( - `No entry point found for service "${this.environment.name}".`, - ) - } - ssrEntryFile = entryFile! - ssrBundle = bundle - }, - }, - - configResolved(config) { - resolvedConfig = config - }, - config(_, env) { - if (env.command !== 'build') { - return - } - - return { - environments: { - ssr: { - consumer: 'server', - build: { - ssr: true, - // we don't write to the file system as the below 'capture-output' plugin will - // capture the output and write it to the virtual file system - write: false, - copyPublicDir: false, - commonjsOptions: { - include: [/node_modules/], - }, - }, - }, - }, - builder: { - sharedPlugins: true, - async buildApp(builder) { - const client = builder.environments.client - const server = builder.environments.ssr - - if (!client) { - throw new Error('Client environment not found') - } - - if (!server) { - throw new Error('SSR environment not found') - } - - await builder.build(client) - await builder.build(server) - - const virtualEntry = '#tanstack/start/entry' - const baseURL = !isFullUrl(resolvedConfig.base) - ? resolvedConfig.base - : undefined - const config: NitroConfig = { - baseURL, - publicAssets: [ - { - dir: client.config.build.outDir, - maxAge: 31536000, // 1 year - baseURL: '/', - }, - ], - ...nitroConfig, - esbuild: { - options: { - target: server.config.build.target || undefined, - ...nitroConfig?.esbuild?.options, - }, - }, - renderer: virtualEntry, - rollupConfig: { - ...nitroConfig?.rollupConfig, - plugins: [virtualBundlePlugin(ssrBundle) as any], - }, - virtual: { - ...nitroConfig?.virtual, - [virtualEntry]: `import { fromWebHandler } from 'h3' - import handler from '${ssrEntryFile}' - export default fromWebHandler(handler.fetch)`, - }, - } - - const nitro = await createNitro(config) - - await prepare(nitro) - await copyPublicAssets(nitro) - await build(nitro) - - await nitro.close() - }, - }, - } - }, - }, - ] -} - -function virtualBundlePlugin(bundle: Rollup.OutputBundle): Rollup.Plugin { - type VirtualModule = { code: string; map: string | null } - let _modules: Map | null = null - - // lazy initialize _modules since at the time of plugin creation, the bundles are not available yet - const getModules = () => { - if (_modules) { - return _modules - } - _modules = new Map() - // group chunks and source maps - for (const [fileName, content] of Object.entries(bundle)) { - if (content.type === 'chunk') { - const virtualModule: VirtualModule = { - code: content.code, - map: null, - } - const maybeMap = bundle[`${fileName}.map`] - if (maybeMap && maybeMap.type === 'asset') { - virtualModule.map = maybeMap.source as string - } - _modules.set(fileName, virtualModule) - _modules.set(resolve(fileName), virtualModule) - } - } - return _modules - } - - return { - name: 'virtual-bundle', - resolveId(id, importer) { - const modules = getModules() - if (modules.has(id)) { - return resolve(id) - } - - if (importer) { - const resolved = resolve(dirname(importer), id) - if (modules.has(resolved)) { - return resolved - } - } - return null - }, - load(id) { - const modules = getModules() - const m = modules.get(id) - if (!m) { - return null - } - return m - }, - } -} diff --git a/packages/nitro-v2-vite-plugin/tsconfig.build.json b/packages/nitro-v2-vite-plugin/tsconfig.build.json deleted file mode 100644 index 92be18587f..0000000000 --- a/packages/nitro-v2-vite-plugin/tsconfig.build.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "rootDir": "./src" - }, - "include": ["src"] -} diff --git a/packages/nitro-v2-vite-plugin/tsconfig.json b/packages/nitro-v2-vite-plugin/tsconfig.json deleted file mode 100644 index bd398a8728..0000000000 --- a/packages/nitro-v2-vite-plugin/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig.json", - "include": ["src", "vite.config.ts", "tests"], - "exclude": ["tests/test-files/**", "tests/snapshots/**"], - "compilerOptions": { - "jsx": "react-jsx" - } -} diff --git a/packages/nitro-v2-vite-plugin/vite.config.ts b/packages/nitro-v2-vite-plugin/vite.config.ts deleted file mode 100644 index 7401092b13..0000000000 --- a/packages/nitro-v2-vite-plugin/vite.config.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { defineConfig, mergeConfig } from 'vitest/config' -import { tanstackViteConfig } from '@tanstack/vite-config' - -const config = defineConfig({}) - -export default mergeConfig( - config, - tanstackViteConfig({ - tsconfigPath: './tsconfig.build.json', - entry: './src/index.ts', - srcDir: './src', - exclude: ['./src/tests/'], - }), -) diff --git a/packages/react-router-devtools/CHANGELOG.md b/packages/react-router-devtools/CHANGELOG.md index 40e065c673..f74de5f187 100644 --- a/packages/react-router-devtools/CHANGELOG.md +++ b/packages/react-router-devtools/CHANGELOG.md @@ -1,5 +1,30 @@ # @tanstack/react-router-devtools +## 1.167.3 + +### Patch Changes + +- Updated dependencies [[`bbf9b75`](https://github.com/TanStack/router/commit/bbf9b75808d8eee497a6dd1663f0cf08426512e0)]: + - @tanstack/router-devtools-core@1.168.3 + +## 1.167.2 + +### Patch Changes + +- Updated dependencies [[`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`b747fb8`](https://github.com/TanStack/router/commit/b747fb8891b3347b1ffdfe0fa81e7d15049cb776), [`6cfb1e8`](https://github.com/TanStack/router/commit/6cfb1e8b564be282584765352250bf61747895ed), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`6387d58`](https://github.com/TanStack/router/commit/6387d581eabc6e6a3acc87a0bc924e5a38d9c8b2), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`9b2adaf`](https://github.com/TanStack/router/commit/9b2adaf8c3fca905f156c42f6a4fe17a787afcc8), [`873c830`](https://github.com/TanStack/router/commit/873c830ccb2610a864ee697250e10fcc99772ffa), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`f151ab0`](https://github.com/TanStack/router/commit/f151ab018eede64ae849b77e68f3cdf31cb95cc5), [`bc57fa3`](https://github.com/TanStack/router/commit/bc57fa3f12450cf34c731450947c7c8f1ea05e58), [`6387d58`](https://github.com/TanStack/router/commit/6387d581eabc6e6a3acc87a0bc924e5a38d9c8b2), [`9872d2a`](https://github.com/TanStack/router/commit/9872d2ac39fc05f4ef6566c0b421f71ceb115244), [`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`9448caa`](https://github.com/TanStack/router/commit/9448caa03a89076b9770631c356c0cc502802c09), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef)]: + - @tanstack/router-core@1.171.30 + - @tanstack/react-router@1.170.36 + - @tanstack/router-devtools-core@1.168.2 + +## 1.167.1 + +### Patch Changes + +- Updated dependencies [[`45c4ad8`](https://github.com/TanStack/router/commit/45c4ad8d629e291fab70c37900525449e415ffcd)]: + - @tanstack/router-core@1.171.16 + - @tanstack/react-router@1.170.19 + - @tanstack/router-devtools-core@1.168.1 + ## 1.167.0 ### Minor Changes diff --git a/packages/react-router-devtools/README.md b/packages/react-router-devtools/README.md index 7be76f46c2..0079d7c065 100644 --- a/packages/react-router-devtools/README.md +++ b/packages/react-router-devtools/README.md @@ -1,5 +1,22 @@ +
+ + + + TanStack React Router + +
# TanStack React Router Devtools See https://tanstack.com/router/latest/docs/framework/react/devtools diff --git a/packages/react-router-devtools/package.json b/packages/react-router-devtools/package.json index 3cb40e24b0..969371a6a6 100644 --- a/packages/react-router-devtools/package.json +++ b/packages/react-router-devtools/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-router-devtools", - "version": "1.167.0", + "version": "1.167.3", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -27,12 +27,12 @@ "clean": "rimraf ./dist && rimraf ./coverage", "test:eslint": "eslint ./src", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc", + "test:types:ts60": "tsc6", + "test:types:ts70": "tsc", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", "build": "vite build" }, @@ -65,11 +65,21 @@ "@tanstack/router-devtools-core": "workspace:*" }, "devDependencies": { - "@vitejs/plugin-react": "^4.3.4", - "react": ">=19", - "react-dom": ">=19", + "@vitejs/plugin-react": "catalog:", + "react": "catalog:", + "react-dom": "catalog:", "vite": "*", - "@types/node": ">=20" + "@types/node": ">=20", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "jsdom": "catalog:", + "@eslint-react/eslint-plugin": "catalog:", + "eslint-plugin-react-hooks": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" }, "peerDependencies": { "@tanstack/react-router": "workspace:^", diff --git a/packages/react-router-ssr-query/CHANGELOG.md b/packages/react-router-ssr-query/CHANGELOG.md index 8e4f3df45d..d0fc73ff50 100644 --- a/packages/react-router-ssr-query/CHANGELOG.md +++ b/packages/react-router-ssr-query/CHANGELOG.md @@ -1,5 +1,39 @@ # @tanstack/react-router-ssr-query +## 1.167.3 + +### Patch Changes + +- [#8204](https://github.com/TanStack/router/pull/8204) [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26) - Stream large deferred SSR hydration payloads through a backpressure-aware router transport, fail known setup errors before response creation, and close cancelled or expired transforms safely. + + Start now cancels discarded middleware and HEAD response bodies, including plain streams and derived branches. + + Server-function raw streams share one ordered response. Arbitrary or sequential consumption can require potentially unbounded buffering of unread data on the client. Cancelling one raw stream discards it locally, while aborting the whole call cancels the response and server work. Consume streams concurrently, cancel unused streams promptly, or use separate calls when independent backpressure is required. A raw stream that exceeds its unread-byte limit now fails alone; sibling streams and the JSON result keep flowing. + + The JSON wire shape of a `RawStream` server-function argument changed. Clients and servers must run matching versions for requests that pass a `RawStream`. + + The frame-protocol constants (`FRAME_TYPE_*`, `MAX_FRAME_PAYLOAD_SIZE`, `MAX_FRAMED_STREAMS`) moved from the `@tanstack/start-client-core` root to the `@tanstack/start-client-core/client-rpc` subpath. + + Router requests whose `Accept` header allows neither `text/html` nor `*/*` now receive `406 Not Acceptable` instead of `500`. + + Framework adapters share the body `` composition (`getSsrBodyScriptParts`, `composeSsrBodyScripts`) and the eager HTML response wrapper (`renderSsrHtmlResponse`) from `@tanstack/router-core`. + + Solid SSR now emits one document type and renders late lazy errors through route boundaries. A Solid `` without a `fallback` no longer holds the streamed shell; it renders inside the nearest `` boundary like React and Vue, and now renders falsy resolved values. + + Static server functions decode cached `RawStream` values with the client deserializer plugins. + + SSR Query integrations now keep request cleanup and stream ownership aligned with the router lifecycle. + +- Updated dependencies [[`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26)]: + - @tanstack/router-ssr-query-core@1.169.3 + +## 1.167.2 + +### Patch Changes + +- Updated dependencies [[`79e3533`](https://github.com/TanStack/router/commit/79e35335b4bb1c3b5e2275a8df5181aa05036628)]: + - @tanstack/router-ssr-query-core@1.169.2 + ## 1.167.1 ### Patch Changes diff --git a/packages/react-router-ssr-query/README.md b/packages/react-router-ssr-query/README.md index 0a19fd3b81..c3a60d1008 100644 --- a/packages/react-router-ssr-query/README.md +++ b/packages/react-router-ssr-query/README.md @@ -2,7 +2,21 @@ # TanStack React Router -![TanStack Router Header](https://raw.githubusercontent.com/TanStack/router/main/media/header_router.png) + + + + TanStack React Router + 🤖 Type-safe router w/ built-in caching & URL state management for React! diff --git a/packages/react-router-ssr-query/package.json b/packages/react-router-ssr-query/package.json index 82d9917747..7333146047 100644 --- a/packages/react-router-ssr-query/package.json +++ b/packages/react-router-ssr-query/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-router-ssr-query", - "version": "1.167.1", + "version": "1.167.3", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -27,12 +27,12 @@ "clean": "rimraf ./dist && rimraf ./coverage", "test:eslint": "eslint ./src", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js", "test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js", "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js", "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js", "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js", - "test:types:ts60": "tsc", + "test:types:ts60": "tsc6", + "test:types:ts70": "tsc", "test:unit": "exit 0; vitest", "test:unit:dev": "pnpm run test:unit --watch", "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .", @@ -67,18 +67,28 @@ "@tanstack/router-ssr-query-core": "workspace:*" }, "devDependencies": { - "@vitejs/plugin-react": "^4.3.4", - "react": ">=19", - "react-dom": ">=19", + "@vitejs/plugin-react": "catalog:", + "react": "catalog:", + "react-dom": "catalog:", "@tanstack/react-router": "workspace:*", - "@tanstack/react-query": ">=5.90.0", - "vite": "*" + "@tanstack/react-query": ">=5.102.0", + "vite": "*", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "jsdom": "catalog:", + "@eslint-react/eslint-plugin": "catalog:", + "eslint-plugin-react-hooks": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0", - "@tanstack/query-core": ">=5.90.0", - "@tanstack/react-router": ">=1.127.0", - "@tanstack/react-query": ">=5.90.0" + "@tanstack/query-core": ">=5.102.0", + "@tanstack/react-router": ">=1.170.33", + "@tanstack/react-query": ">=5.102.0" } } diff --git a/packages/react-router/CHANGELOG.md b/packages/react-router/CHANGELOG.md index 46909b1699..7e1e2f1a62 100644 --- a/packages/react-router/CHANGELOG.md +++ b/packages/react-router/CHANGELOG.md @@ -1,5 +1,357 @@ # @tanstack/react-router +## 1.170.46 + +### Patch Changes + +- [#8670](https://github.com/TanStack/router/pull/8670) [`32a3360`](https://github.com/TanStack/router/commit/32a3360cba0e0f884b3215813a48c63467f5a53c) - Reference agent skills in other packages by their `intent load` identifier (`@tanstack/#`) instead of relative file links that break once packages are installed. + +- [#8671](https://github.com/TanStack/router/pull/8671) [`689a7c5`](https://github.com/TanStack/router/commit/689a7c5419de68bce0aaaef72b9a36f115ea1398) - Publish the `@tanstack/react-router` agent skills (`react-router`, `compositions/router-query`, `lifecycle/migrate-from-react-router`), which were missing from the package's `files` list. + +- Updated dependencies [[`32a3360`](https://github.com/TanStack/router/commit/32a3360cba0e0f884b3215813a48c63467f5a53c)]: + - @tanstack/router-core@1.171.39 + +## 1.170.45 + +### Patch Changes + +- Updated dependencies [[`18154b1`](https://github.com/TanStack/router/commit/18154b1c45454a70aa77e9d6d27c8a6e0733d031)]: + - @tanstack/router-core@1.171.38 + +## 1.170.44 + +### Patch Changes + +- Updated dependencies [[`d6ba115`](https://github.com/TanStack/router/commit/d6ba115d5751c75e20943f0062577cf17b446d82)]: + - @tanstack/router-core@1.171.37 + +## 1.170.43 + +### Patch Changes + +- Updated dependencies [[`94d6d8e`](https://github.com/TanStack/router/commit/94d6d8e49694e225cb07e2a6777633d08aeeb3c5)]: + - @tanstack/router-core@1.171.36 + +## 1.170.42 + +### Patch Changes + +- [#8594](https://github.com/TanStack/router/pull/8594) [`2413cc0`](https://github.com/TanStack/router/commit/2413cc009826fba4f97b166a35a8a50a4a8fe4bb) - reduce component nesting per route match + +- [#8602](https://github.com/TanStack/router/pull/8602) [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb) - Links of a route that the pending navigation leaves skip deriving the destination location, and clicks and preloads follow the href a Link displays. `buildLocation` now builds `mask` and `routeMasks` locations from the same `_fromLocation` as the destination. + +- [#8602](https://github.com/TanStack/router/pull/8602) [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb) - Fixed Link destinations that resolve to a route mask are now reused across navigations instead of being rebuilt every time. A mounted Link now follows changes to its `href` and `reloadDocument` props, and React Links no longer each subscribe to a hydration flag. + +- [#8579](https://github.com/TanStack/router/pull/8579) [`d35aab4`](https://github.com/TanStack/router/commit/d35aab425b07b46e222a507c0f0239644669757b) - Cancel pending link preload timers when starting navigation to avoid redundant preloading while the destination is loading. + +- Updated dependencies [[`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb), [`efc2042`](https://github.com/TanStack/router/commit/efc2042c2d02a9780c3e7efe81f123d066a869eb), [`dfe3dea`](https://github.com/TanStack/router/commit/dfe3dea88a28400db1677111e2b15ae7914782c2), [`663282b`](https://github.com/TanStack/router/commit/663282b0ebbc494aee3595ed95867ee29d01938e)]: + - @tanstack/history@1.162.5 + - @tanstack/router-core@1.171.35 + +## 1.170.41 + +### Patch Changes + +- [#8529](https://github.com/TanStack/router/pull/8529) [`60b8ad1`](https://github.com/TanStack/router/commit/60b8ad1ad00812bf966a8eeee6be238c37ddad74) - Compose only enabled route boundaries instead of rendering inactive wrapper components. + +- [#8568](https://github.com/TanStack/router/pull/8568) [`614bc27`](https://github.com/TanStack/router/commit/614bc27034c8ec98747bf305ed41d4a619640949) - Update TanStack Store to 0.11.2 to prevent unrelated atom reads inside subscription observers from triggering extra notifications. + +- [#8530](https://github.com/TanStack/router/pull/8530) [`ff66a03`](https://github.com/TanStack/router/commit/ff66a03df4816f44a48a4a37189fc4021b1c8480) - Consolidate the root match context provider while preserving match context in the root shell. + +- [#8522](https://github.com/TanStack/router/pull/8522) [`863c8a7`](https://github.com/TanStack/router/commit/863c8a736b96746c56278a16c50554356f5523d1) - Reuse Link href classification and active/inactive results across location updates while preserving live history href formatting. + +- Updated dependencies [[`d521abd`](https://github.com/TanStack/router/commit/d521abd71c69f1ff010bb3def4d417cb5fa058cb)]: + - @tanstack/router-core@1.171.34 + +## 1.170.40 + +### Patch Changes + +- [#8436](https://github.com/TanStack/router/pull/8436) [`f5ffd38`](https://github.com/TanStack/router/commit/f5ffd3884ba26778a2a8ce53b379a5bded231676) - Skip unused Link preload cleanup when preloading is disabled and ignore queued viewport notifications after their effect has been cleaned up. + +- Updated dependencies [[`488d046`](https://github.com/TanStack/router/commit/488d046a907d330429e2c807ef95326dad87480f), [`0c1b5e3`](https://github.com/TanStack/router/commit/0c1b5e38de71b7e81bbf1fd81c73ee0cd68ffe47), [`3cdd1af`](https://github.com/TanStack/router/commit/3cdd1af04b3e2d6f777797ee7bddf285318dd9d2)]: + - @tanstack/router-core@1.171.33 + +## 1.170.39 + +### Patch Changes + +- [#8435](https://github.com/TanStack/router/pull/8435) [`73bfc15`](https://github.com/TanStack/router/commit/73bfc153eef460e9b670556215a5adb2b5cbf542) - Avoid hydration-triggered rerenders for links that do not compare URL hashes while preserving hash-sensitive active state and ClientOnly behavior. + +## 1.170.38 + +### Patch Changes + +- Updated dependencies [[`cecae54`](https://github.com/TanStack/router/commit/cecae5440b8edaea77c5448fe3d74bbd20fe10a4), [`0103578`](https://github.com/TanStack/router/commit/01035782e53af9b929c784b94ddd64b95efb89c7), [`ce10dcd`](https://github.com/TanStack/router/commit/ce10dcd4d9d3d23738744e453205aad5c6dbd716), [`84936cc`](https://github.com/TanStack/router/commit/84936cc04530bba11059c57b293a794922bbc5aa), [`bbd2336`](https://github.com/TanStack/router/commit/bbd2336b8446de3f7dd85070895e7cf43980183e)]: + - @tanstack/router-core@1.171.32 + +## 1.170.37 + +### Patch Changes + +- [#8418](https://github.com/TanStack/router/pull/8418) [`e561fa1`](https://github.com/TanStack/router/commit/e561fa1d7118e3d29267cc3b6ce1130d6581f387) - `deepEqual` now takes its flags as positional arguments — `deepEqual(a, b, partial?, explicitUndefined?)` — instead of an options object. The router's hot callers (Link option stabilization and active-state checks, `matchRoute`) no longer allocate an options object per comparison, and the comparator reads two booleans instead of a polymorphic object. `explicitUndefined` replaces `ignoreUndefined: false`. `deepEqual` is an internal helper; it stays exported for compatibility of two-argument calls. + +- [#8419](https://github.com/TanStack/router/pull/8419) [`a1c8d1a`](https://github.com/TanStack/router/commit/a1c8d1aa759c227eae9601a030321ac4c53c24bd) - `resolvePath` (internal helper) now takes positional arguments — `resolvePath(base, to, trailingSlash?, cache?)` — so `buildLocation` and `matchRoute` no longer allocate an options object per path resolution. + +- [#8204](https://github.com/TanStack/router/pull/8204) [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26) - Stream large deferred SSR hydration payloads through a backpressure-aware router transport, fail known setup errors before response creation, and close cancelled or expired transforms safely. + + Start now cancels discarded middleware and HEAD response bodies, including plain streams and derived branches. + + Server-function raw streams share one ordered response. Arbitrary or sequential consumption can require potentially unbounded buffering of unread data on the client. Cancelling one raw stream discards it locally, while aborting the whole call cancels the response and server work. Consume streams concurrently, cancel unused streams promptly, or use separate calls when independent backpressure is required. A raw stream that exceeds its unread-byte limit now fails alone; sibling streams and the JSON result keep flowing. + + The JSON wire shape of a `RawStream` server-function argument changed. Clients and servers must run matching versions for requests that pass a `RawStream`. + + The frame-protocol constants (`FRAME_TYPE_*`, `MAX_FRAME_PAYLOAD_SIZE`, `MAX_FRAMED_STREAMS`) moved from the `@tanstack/start-client-core` root to the `@tanstack/start-client-core/client-rpc` subpath. + + Router requests whose `Accept` header allows neither `text/html` nor `*/*` now receive `406 Not Acceptable` instead of `500`. + + Framework adapters share the body `` composition (`getSsrBodyScriptParts`, `composeSsrBodyScripts`) and the eager HTML response wrapper (`renderSsrHtmlResponse`) from `@tanstack/router-core`. + + Solid SSR now emits one document type and renders late lazy errors through route boundaries. A Solid `` without a `fallback` no longer holds the streamed shell; it renders inside the nearest `` boundary like React and Vue, and now renders falsy resolved values. + + Static server functions decode cached `RawStream` values with the client deserializer plugins. + + SSR Query integrations now keep request cleanup and stream ownership aligned with the router lifecycle. + +- [#8420](https://github.com/TanStack/router/pull/8420) [`8e164d2`](https://github.com/TanStack/router/commit/8e164d28f9e9eb1a7301109230d7ece9817492a8) - `useLinkProps` no longer calls through an internal wrapper. The host element `Link` renders on is an `@internal` overload parameter that is stripped from the published declarations, so the public `useLinkProps(options, forwardedRef?)` signature is unchanged. + +- Updated dependencies [[`bc80866`](https://github.com/TanStack/router/commit/bc80866f6d6eb3e6f152ee3682eb783c96403e83), [`e561fa1`](https://github.com/TanStack/router/commit/e561fa1d7118e3d29267cc3b6ce1130d6581f387), [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26), [`a1c8d1a`](https://github.com/TanStack/router/commit/a1c8d1aa759c227eae9601a030321ac4c53c24bd), [`cbbfbe3`](https://github.com/TanStack/router/commit/cbbfbe37ab1dbe328c343cb437c5660769cc9f26), [`a0b2ad9`](https://github.com/TanStack/router/commit/a0b2ad99aee64af08d16b0e4ff26b3ba42a99f0a), [`1ca361b`](https://github.com/TanStack/router/commit/1ca361ba52a627d2f76ab33323bd83d1d0aa65a3)]: + - @tanstack/router-core@1.171.31 + +## 1.170.36 + +### Patch Changes + +- [#8390](https://github.com/TanStack/router/pull/8390) [`b747fb8`](https://github.com/TanStack/router/commit/b747fb8891b3347b1ffdfe0fa81e7d15049cb776) - Keep the Link location cache out of server bundles: `buildLocation` only creates, reads and writes it when `isServer` is false. Render React Links on the server without the extra prop copies and the forwarded-ref hook. Link SSR rendering is 20-40% faster in the Link benchmarks and the React Start SSR request loop about 7% faster. + + React `activeProps` and `inactiveProps` now follow one precedence rule on every link, including links whose destination is blocked for using a disallowed scheme: state props override element props, `ref` and event handlers, while `href`, `disabled` and `target` stay controlled by the router. Previously a blocked link ignored a `ref` or handler from its inactive props. + + React `Link` and `useLinkProps` split router options from element props with one key set on the client and the server. Element props pass through as given: external links forward them verbatim, falsy values included, and `useLinkProps` now returns `children` for router-controlled links as it already did for external ones. + +- [#8324](https://github.com/TanStack/router/pull/8324) [`6387d58`](https://github.com/TanStack/router/commit/6387d581eabc6e6a3acc87a0bc924e5a38d9c8b2) - Reuse hydration snapshot getters to avoid unnecessary store-instance effect updates when Links and other hydration-aware components rerender. + +- [#8318](https://github.com/TanStack/router/pull/8318) [`9b2adaf`](https://github.com/TanStack/router/commit/9b2adaf8c3fca905f156c42f6a4fe17a787afcc8) - Allow active and inactive Link props to override base element props in React and Solid while preserving class/style merging. Keep React's `href`, `target`, and `disabled` values controlled by routing options. Preserve Vue object and nested-array class bindings, including reactive updates and server rendering, without mutating cached bindings during VNode normalization. + +- [#8327](https://github.com/TanStack/router/pull/8327) [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef) - Make `pathParamsAllowedCharacters` initialization-only. Configure it when creating the router; changing allowed characters requires a new router instance. Remove decoder-update bookkeeping and decoder-change checks from route-owned path caches. + +- [#8370](https://github.com/TanStack/router/pull/8370) [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5) - Stop exporting the internal `isPlainObject` and `isPlainArray` helpers. + +- [#8324](https://github.com/TanStack/router/pull/8324) [`6387d58`](https://github.com/TanStack/router/commit/6387d581eabc6e6a3acc87a0bc924e5a38d9c8b2) - Avoid a redundant prop copy when rendering native Links while preserving custom-component props and the public hook result. + +- [#8252](https://github.com/TanStack/router/pull/8252) [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734) - Reduce the bundle cost of shared Link pathname interpolation while preserving its rendering performance. Reuse one interpolation pass for pathname and optional metadata, keep the bounded cache on the router, and simplify React Link active-state and prop merging. + +- [#8370](https://github.com/TanStack/router/pull/8370) [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5) - Reuse built locations for Links whose destination does not depend on the current location. `buildLocation` keeps the result per options object when the build never read the current location, and the React `Link` passes one stable options object per instance, so navigations resolve unchanged Links with a lookup instead of a full build. The per-route pathname interpolation cache this replaces is removed. Link `params`, `search` and `activeOptions` are compared by value on render, so inline object literals with unchanged contents keep reusing the Link's location. Pass a new object to change a destination; like any other React prop, an object mutated in place is not re-read. + +- Updated dependencies [[`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`b747fb8`](https://github.com/TanStack/router/commit/b747fb8891b3347b1ffdfe0fa81e7d15049cb776), [`6cfb1e8`](https://github.com/TanStack/router/commit/6cfb1e8b564be282584765352250bf61747895ed), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`8fff7fa`](https://github.com/TanStack/router/commit/8fff7fa1f2e6f061916b0bf5e0ec486b2e732f94), [`f021f6d`](https://github.com/TanStack/router/commit/f021f6d1c6dce6c9b54d70766f1d636d8fd9e184), [`ae68535`](https://github.com/TanStack/router/commit/ae68535929043607d4ee9438f8ae401f3a064862), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`873c830`](https://github.com/TanStack/router/commit/873c830ccb2610a864ee697250e10fcc99772ffa), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`f151ab0`](https://github.com/TanStack/router/commit/f151ab018eede64ae849b77e68f3cdf31cb95cc5), [`bc57fa3`](https://github.com/TanStack/router/commit/bc57fa3f12450cf34c731450947c7c8f1ea05e58), [`9872d2a`](https://github.com/TanStack/router/commit/9872d2ac39fc05f4ef6566c0b421f71ceb115244), [`d76a332`](https://github.com/TanStack/router/commit/d76a33284bc0668f7af4c972a6d32bd0f42b22a6), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`7e349c3`](https://github.com/TanStack/router/commit/7e349c3071ef7a346698d320fc0989998ad55734), [`9448caa`](https://github.com/TanStack/router/commit/9448caa03a89076b9770631c356c0cc502802c09), [`e9396c9`](https://github.com/TanStack/router/commit/e9396c928945d1dd6fd3f3bd8052143794f688b5), [`700a714`](https://github.com/TanStack/router/commit/700a714c5fb64199b4edfaa3273d230c9894e274), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef), [`634da91`](https://github.com/TanStack/router/commit/634da9176e16fa8aa49af459bbb054fcae7d85ef)]: + - @tanstack/router-core@1.171.30 + - @tanstack/history@1.162.4 + +## 1.170.35 + +### Patch Changes + +- [#7824](https://github.com/TanStack/router/pull/7824) [`8c43c71`](https://github.com/TanStack/router/commit/8c43c712523fc63dc3a814f3a19617e270ce8ed1) - Upgrade TanStack Store to 0.11 and migrate router subscriptions to useSelector, preserving selector comparisons and Vue subscription cleanup. + +## 1.170.34 + +### Patch Changes + +- [#8279](https://github.com/TanStack/router/pull/8279) [`aee42c6`](https://github.com/TanStack/router/commit/aee42c6b641d8e919bfed9e0f04bb1b72092f3a6) - Avoid allocating event-handler arrays and wrapper functions for links without user-supplied event handlers. + +- [#8308](https://github.com/TanStack/router/pull/8308) [`9c1871c`](https://github.com/TanStack/router/commit/9c1871ccc88bc1157186b8b460941a304ec740b8) - Validate navigation and redirect destinations, keep ambiguous relative URLs on the current origin, and constrain prerender requests and output paths. Prevent redirect headers from appearing in serialized server function response bodies. + + Preserve native form HTTP redirects, route error handling and masks for document redirects, and per-navigation destinations for shared loader redirects. Avoid redundant origin parsing and reduce link styling and server-rendering work. Configured origins must already be normalized. + + Keep blocked-link inactive props consistent during React hydration, honor explicit redirect Location headers before checking route options, and refresh Vue link state when destinations become internal. Reuse the protocol-relative URL check while parsing redirect schemes once. + + Reduce React link bundle size by sharing pathname comparisons, state-prop selection, and element creation. + + Share normalized pathname comparisons in Solid and Vue links to reduce bundle size. + +- [#8311](https://github.com/TanStack/router/pull/8311) [`9aec5a7`](https://github.com/TanStack/router/commit/9aec5a7012c47e83ec23bb4763494b72a5e68bfc) - React Links resolve state props without temporary class-name arrays or unnecessary style copies. + +- Updated dependencies [[`f9836f1`](https://github.com/TanStack/router/commit/f9836f16f0e25b0a8495f5e01e3f303b1cbc8725), [`9c1871c`](https://github.com/TanStack/router/commit/9c1871ccc88bc1157186b8b460941a304ec740b8), [`9871c06`](https://github.com/TanStack/router/commit/9871c0625806001d6bf373524821a00303438a91), [`0654c0a`](https://github.com/TanStack/router/commit/0654c0a1a427db24d9af13c1d6ad1217a588c0c9)]: + - @tanstack/router-core@1.171.29 + - @tanstack/history@1.162.3 + +## 1.170.33 + +### Patch Changes + +- [#8165](https://github.com/TanStack/router/pull/8165) [`2f20c00`](https://github.com/TanStack/router/commit/2f20c00224c5ba63467551914e0c37012588c4c2) - Exclude structural descendants below error and not-found boundaries from route lifecycle callbacks. Preserve lifecycle membership through invalidation, hydration, background reloads, and superseded navigation publication. + +- [#8209](https://github.com/TanStack/router/pull/8209) [`28a5e45`](https://github.com/TanStack/router/commit/28a5e4504e4ea5cb1480667a4bea2588a53e110f) - Preserve falsy thrown values in React and Vue error boundaries. Type React and Vue boundary error components and `onCatch` callbacks as `unknown`. Solid boundary errors remain typed as `Error`; SSR now wraps non-`Error` loader errors to match Solid’s native boundary behavior, preserving the original value in `cause`. Router state and loader `onError` values are unchanged. + + When upgrading React or Vue, narrow boundary errors (for example, with `error instanceof Error`) before reading `message` or `stack`. `ErrorComponentProps` remains available for values narrowed to a specific error type. Route `onError` types are unchanged. + +- [#8161](https://github.com/TanStack/router/pull/8161) [`f0b5eda`](https://github.com/TanStack/router/commit/f0b5eda544606686a8a8d675a686ca1366428b96) - Retain successful not-found matches as terminal shared boundaries during client navigation, preserving route context while the destination loads. + +- [#8251](https://github.com/TanStack/router/pull/8251) [`0497cae`](https://github.com/TanStack/router/commit/0497caeef3ff7e1c1c6080eca38bca24e7ec320b) - Use URL.canParse for absolute URL checks in links, navigation, redirects, and build configuration. Preserve a URL constructor fallback for older browsers. + +- [#8169](https://github.com/TanStack/router/pull/8169) [`0caf6b9`](https://github.com/TanStack/router/commit/0caf6b9a2b7e14b0b146c74cc27cb05c19d700a5) - Fix route-scoped `useMatch`, `useSearch`, and `useParams` APIs to forward the `shouldThrow` option and preserve optional return types when `shouldThrow: false`. + +- [#8257](https://github.com/TanStack/router/pull/8257) [`cf166d1`](https://github.com/TanStack/router/commit/cf166d160e6397007a979bfc7065b45ff69ea543) - Fix repeated `innerHTML` writes for unchanged styles and data scripts during React re-renders. This prevents unnecessary CSS parsing and Trusted Types errors during client navigation. + +- Updated dependencies [[`edf0e16`](https://github.com/TanStack/router/commit/edf0e16ebfe82ec6e8f68f403a1fda8de9e28889), [`2f20c00`](https://github.com/TanStack/router/commit/2f20c00224c5ba63467551914e0c37012588c4c2), [`28a5e45`](https://github.com/TanStack/router/commit/28a5e4504e4ea5cb1480667a4bea2588a53e110f), [`08eff50`](https://github.com/TanStack/router/commit/08eff50c447a154a3373909009e9e4375cea17ce), [`216c0c4`](https://github.com/TanStack/router/commit/216c0c48036fd1a33163b70dcabfed2b893808b0), [`2f91503`](https://github.com/TanStack/router/commit/2f9150309bc472f4a75cbe98adcdb50c76b12c7a), [`f0b5eda`](https://github.com/TanStack/router/commit/f0b5eda544606686a8a8d675a686ca1366428b96), [`50eafca`](https://github.com/TanStack/router/commit/50eafcaebbbedb6fde3b2816de7a0ace8cde4832), [`0497cae`](https://github.com/TanStack/router/commit/0497caeef3ff7e1c1c6080eca38bca24e7ec320b), [`ee28348`](https://github.com/TanStack/router/commit/ee283480dfa51150a2e0b096a6eff94a89ff8b3f), [`9035abc`](https://github.com/TanStack/router/commit/9035abc41163d83409ef582f7743a3c7be57dd93), [`c18e690`](https://github.com/TanStack/router/commit/c18e69081475a7c98f9d40bd0fe6da78ccb84598)]: + - @tanstack/router-core@1.171.28 + - @tanstack/history@1.162.2 + +## 1.170.32 + +### Patch Changes + +- [#8130](https://github.com/TanStack/router/pull/8130) [`cb281d7`](https://github.com/TanStack/router/commit/cb281d70c1f5fe780f9d07bc500ea3a284a4e04b) - preserve context during reloads + +- Updated dependencies [[`fa65287`](https://github.com/TanStack/router/commit/fa652872812c9433ba8b9d9a285e51b535e7367c), [`cb281d7`](https://github.com/TanStack/router/commit/cb281d70c1f5fe780f9d07bc500ea3a284a4e04b)]: + - @tanstack/router-core@1.171.27 + +## 1.170.31 + +### Patch Changes + +- Updated dependencies [[`3e016ac`](https://github.com/TanStack/router/commit/3e016ac84ffec8119f0c25cfdd1fb17e5292bd34)]: + - @tanstack/router-core@1.171.26 + +## 1.170.30 + +### Patch Changes + +- [#8084](https://github.com/TanStack/router/pull/8084) [`5d3785d`](https://github.com/TanStack/router/commit/5d3785dcc366b66b1c261b5d01e66af778ff1175) - preserve pending UI across retained routes + +- [#8068](https://github.com/TanStack/router/pull/8068) [`f75cada`](https://github.com/TanStack/router/commit/f75cada01707e51fb9650dd301bc04f8b2265a2a) - direct export of CatchBoundary class component, remove function wrapper + +- Updated dependencies [[`5d3785d`](https://github.com/TanStack/router/commit/5d3785dcc366b66b1c261b5d01e66af778ff1175), [`63d2cc9`](https://github.com/TanStack/router/commit/63d2cc9155ff5374112f7d067d0b278bafeb8486)]: + - @tanstack/router-core@1.171.25 + +## 1.170.29 + +### Patch Changes + +- [#8073](https://github.com/TanStack/router/pull/8073) [`0fdf9ff`](https://github.com/TanStack/router/commit/0fdf9ff16fc532de9fc131d18df167ebd8038720) - inline isCtrlKey inside Link component for byte shaving + +- Updated dependencies [[`4c89b15`](https://github.com/TanStack/router/commit/4c89b15dd2b46491ee5e57985559bae8e31d62c2), [`cf6ab17`](https://github.com/TanStack/router/commit/cf6ab178b39e7628bf784759f384e0f4230e6d9e), [`bdaf73a`](https://github.com/TanStack/router/commit/bdaf73a4063ee2b02e3c9cc105ad10ce82a5a0ff)]: + - @tanstack/router-core@1.171.24 + +## 1.170.28 + +### Patch Changes + +- [#8055](https://github.com/TanStack/router/pull/8055) [`0c25a7b`](https://github.com/TanStack/router/commit/0c25a7b43b5331ee6ebf94d50e9793002783adab) - Avoid wrapping root components that may render the HTML document in a Suspense boundary during SSR and hydration. + +- [#8054](https://github.com/TanStack/router/pull/8054) [`31882c7`](https://github.com/TanStack/router/commit/31882c7fa87debef236228831655cb112c20ce90) - Reuse resolved lazy route components when revisiting code-split routes, preventing unnecessary pending UI. + +- Updated dependencies [[`31882c7`](https://github.com/TanStack/router/commit/31882c7fa87debef236228831655cb112c20ce90)]: + - @tanstack/router-core@1.171.23 + +## 1.170.27 + +### Patch Changes + +- [#8047](https://github.com/TanStack/router/pull/8047) [`b0817f5`](https://github.com/TanStack/router/commit/b0817f50cc639ae50b6c30cd11c5adbf7eed028c) - useMatchRoute w/ React Compiler + +## 1.170.26 + +### Patch Changes + +- [#8045](https://github.com/TanStack/router/pull/8045) [`f500760`](https://github.com/TanStack/router/commit/f5007607d62e932b8df19de866cdc6bddcff8db3) - Warn when an Outlet is rendered inside a pending, error, or not-found component. + +- [#8043](https://github.com/TanStack/router/pull/8043) [`1aafca9`](https://github.com/TanStack/router/commit/1aafca9b45d24f8f0dba78e716fc9582346c6ca1) - remove the undocumented Link `isTransitioning` state and `data-transitioning` attribute + +- [#8044](https://github.com/TanStack/router/pull/8044) [`aa10b65`](https://github.com/TanStack/router/commit/aa10b6589eeda215f5a60ea0af95a3101d8c414e) - Apply `preloadDelay` to viewport link preloading and cancel pending preloads when links leave the viewport. + +- Updated dependencies [[`7e93431`](https://github.com/TanStack/router/commit/7e93431ae9ff58c91c3c5ca10ffcb8414c1d0b13)]: + - @tanstack/router-core@1.171.22 + +## 1.170.25 + +### Patch Changes + +- Updated dependencies [[`51138a8`](https://github.com/TanStack/router/commit/51138a824cea053738f125c4c95073bd6286ff05)]: + - @tanstack/router-core@1.171.21 + +## 1.170.24 + +### Patch Changes + +- Updated dependencies [[`44a8c3e`](https://github.com/TanStack/router/commit/44a8c3e1d2af305064b2363d97fc7847c6f1a246), [`5253e70`](https://github.com/TanStack/router/commit/5253e70db2083d68a788fb7c9a043bb0c5518f2a)]: + - @tanstack/router-core@1.171.20 + +## 1.170.23 + +### Patch Changes + +- [#7952](https://github.com/TanStack/router/pull/7952) [`95dec51`](https://github.com/TanStack/router/commit/95dec51018d01483949c6f1fe3094b019ccf3b4f) - bail out of `Link` re-renders when the resolved href and active state are unchanged + +## 1.170.22 + +### Patch Changes + +- [#7992](https://github.com/TanStack/router/pull/7992) [`ea3a665`](https://github.com/TanStack/router/commit/ea3a665d81cbb5074c2d77ec953255ab534e7db9) - retain mounted UI during revalidation + +- Updated dependencies [[`ea3a665`](https://github.com/TanStack/router/commit/ea3a665d81cbb5074c2d77ec953255ab534e7db9)]: + - @tanstack/router-core@1.171.19 + +## 1.170.21 + +### Patch Changes + +- [#7961](https://github.com/TanStack/router/pull/7961) [`697ebb6`](https://github.com/TanStack/router/commit/697ebb6ddbd433d052b6b4707938a5c595865d58) - Prevent a blank frame before zero-delay initial pending UI by using a + component-scoped React transition for match publication. Pending timing, + boundary selection, and rendered matches continue to come from the router + core. + +- [#7970](https://github.com/TanStack/router/pull/7970) [`2435885`](https://github.com/TanStack/router/commit/2435885fa8b5e31c8c4b74d93920919f27316ebf) - createFileRoute does not rely on FileRoute class + +- [#7971](https://github.com/TanStack/router/pull/7971) [`86bf510`](https://github.com/TanStack/router/commit/86bf510c2923afb76804223bd04afc2a809b33e7) - clean intersection observer options in link component + +- [#7967](https://github.com/TanStack/router/pull/7967) [`6aefb33`](https://github.com/TanStack/router/commit/6aefb3392595a07a93f89301d7b5e3558ff9190c) - Preserve path params in their raw string form while matching routes so structured values returned by `params.parse` produce stable match IDs and do not reuse stale loader data. + + `RouterCore.getMatchedRoutes()` now returns `[matchedRoutes, rawParams, foundRoute]` instead of an object. + +- Updated dependencies [[`84db4a8`](https://github.com/TanStack/router/commit/84db4a842311df3f7e58073f6f12aaf371aeb5c7), [`9cac62a`](https://github.com/TanStack/router/commit/9cac62a5c7f99ef070991ea6f1fa7e42c746d46b), [`6aefb33`](https://github.com/TanStack/router/commit/6aefb3392595a07a93f89301d7b5e3558ff9190c)]: + - @tanstack/router-core@1.171.18 + - @tanstack/history@1.162.1 + +## 1.170.20 + +### Patch Changes + +- Updated dependencies [[`b2908c6`](https://github.com/TanStack/router/commit/b2908c642ac09aa08e6d965d2a820d7186e42fd5)]: + - @tanstack/router-core@1.171.17 + +## 1.170.19 + +### Patch Changes + +- [#7805](https://github.com/TanStack/router/pull/7805) [`45c4ad8`](https://github.com/TanStack/router/commit/45c4ad8d629e291fab70c37900525449e415ffcd) - Rewrite match loading around a lane-based scheduler that tracks each navigation, preload, and background reload as an ordered unit of work. This fixes pending/redirect/retry state leaking between overlapping navigations, restores correct SSR status codes for redirects, errors, and not-found responses, and closes hydration gaps where the client re-ran work the server had already completed. + - Invalidation now retires matching active preloads so older speculative loader results cannot become fresh cache data after invalidation. + - Route `headers()` now only runs on the server, matching the documented behavior — it is no longer invoked during client-side asset projection. + - The documented default `gcTime` and `preloadGcTime` now match the existing runtime default of 5 minutes (`300_000`). + + **Removed / changed exported internals** + - `RouterState` no longer includes `loadedAt`, `isTransitioning`, `statusCode`, or `redirect`. Use `match.updatedAt` in place of `loadedAt`; subscribe to `router.state.status` / `router.state.isLoading` in place of `isTransitioning`; server response status and redirect handling are now internal to the server loader and are no longer exposed on `router.state`. + - `RouteMatch.fetchCount` has been removed, with no replacement — it was purely informational. + - `RouteMatch.status` no longer includes `'redirected'` (it remains `'pending' | 'success' | 'error' | 'notFound'`) — redirected matches are dropped from the match list instead of being rendered. + - `RouteMatch.globalNotFound` has been renamed and privatized to the internal `_notFound` field. Use `match.status === 'notFound'` instead. + - The exported React, Solid, and Vue `Match` components now accept `routeId` instead of `matchId`. + - The exported `RouterStores` adapter contract now uses route-keyed presentation stores: `matchesId` is replaced by `ids`, `matchStores` by `byRoute`, and `getRouteMatchStore()` by `getMatchStore()`. The separate `loadedAt`, `isLoading`, `isTransitioning`, `statusCode`, and `redirect` stores have been removed, along with the pending/cache stores and their setters. `StoreConfig.init` has also been removed. Read application-facing state from `router.state`; preload and cache coordination are now internal. + - Removed `RouterCore` members `getMatch()`, `updateMatch()`, `cancelMatch()`, and `cancelMatches()` — read matches from `router.state.matches` (e.g. `router.state.matches.find((m) => m.id === id)`); there is no replacement for mutating or cancelling an individual in-flight match from outside the router. + - Removed `RouterCore.hasNotFoundMatch()` — use `router.state.matches.some((m) => m.status === 'notFound')`. + - Removed `RouterCore.looseRoutesById` — use `routesById`. + - Removed `RouterCore.isPrerendering()`, `RouterCore.isViewTransitionTypesSupported`, and `RouterCore.viewTransitionPromise`, with no replacement. + - Removed `RouterCore.getParsedLocationHref()` and `RouterCore.clearExpiredCache()`, with no replacement — expired cache entries are now reconciled automatically as part of match commit. + - Removed `RouterCore.latestLoadPromise` and `RouterCore.beforeLoad()`, with no replacement. + - `RouterCore.commitLocationPromise` and `RouterCore.pendingBuiltLocation` have been replaced by the internal `_commitPromise` and `_pendingLocation` fields. + - Removed the exported `GetMatchFn` and `UpdateMatchFn` types, along with the methods they typed. + - Removed the standalone `getMatchedRoutes()` export from `@tanstack/router-core` — use the `router.getMatchedRoutes()` instance method instead. + - `RouterCore.loadRouteChunk()` no longer accepts an array of component types as its second argument. One-argument usage is unchanged; the optional second argument is now `'errorComponent'`, `'notFoundComponent'`, or `false` for internal boundary loading. + - Removed `Redirect.redirectHandled`, which was internal redirect bookkeeping. + - `MatchRoutesOpts.preload` and `MatchRoutesOpts.dest` have been removed. + - `StartTransitionFn` is now `(fn, expected) => Promise` (previously `(fn) => void`). This only affects custom framework adapters that implement `startTransition`. + +- Updated dependencies [[`45c4ad8`](https://github.com/TanStack/router/commit/45c4ad8d629e291fab70c37900525449e415ffcd)]: + - @tanstack/router-core@1.171.16 + ## 1.170.18 ### Patch Changes diff --git a/packages/react-router/README.md b/packages/react-router/README.md index 0a19fd3b81..c3a60d1008 100644 --- a/packages/react-router/README.md +++ b/packages/react-router/README.md @@ -2,7 +2,21 @@ # TanStack React Router -![TanStack Router Header](https://raw.githubusercontent.com/TanStack/router/main/media/header_router.png) + + + + TanStack React Router + 🤖 Type-safe router w/ built-in caching & URL state management for React! diff --git a/packages/react-router/package.json b/packages/react-router/package.json index d1b6ddf285..9a61d5af25 100644 --- a/packages/react-router/package.json +++ b/packages/react-router/package.json @@ -1,6 +1,6 @@ { "name": "@tanstack/react-router", - "version": "1.170.18", + "version": "1.170.46", "description": "Modern and scalable routing for React applications", "author": "Tanner Linsley", "license": "MIT", @@ -27,12 +27,12 @@ "clean": "rimraf ./dist && rimraf ./coverage", "test:eslint": "eslint", "test:types": "pnpm run \"/^test:types:ts[0-9]{2}$/\"", - "test:types:ts55": "node ../../node_modules/typescript55/lib/tsc.js -p tsconfig.legacy.json", "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": "tsc -p tsconfig.legacy.json", + "test:types:ts60": "tsc6 -p tsconfig.legacy.json", + "test:types:ts70": "tsc -p tsconfig.legacy.json", "test:unit": "vitest", "test:unit:dev": "pnpm run test:unit --watch --hideSkippedTests", "test:perf": "vitest bench", @@ -86,28 +86,40 @@ "sideEffects": false, "files": [ "dist", - "src" + "src", + "skills", + "!skills/_artifacts" ], "engines": { "node": ">=20.19" }, "dependencies": { "@tanstack/history": "workspace:*", - "@tanstack/react-store": "^0.9.3", + "@tanstack/react-store": "^0.11.2", "@tanstack/router-core": "workspace:*", - "isbot": "^5.1.22" + "isbot": "catalog:" }, "devDependencies": { - "@testing-library/jest-dom": "^6.6.3", - "@testing-library/react": "^16.2.0", + "@testing-library/jest-dom": "catalog:", + "@testing-library/react": "catalog:", "@tanstack/react-query": "catalog:", "@types/node": ">=20", - "@vitejs/plugin-react": "^4.3.4", - "combinate": "^1.1.11", - "react": "^19.0.0", - "react-dom": "^19.0.0", + "@vitejs/plugin-react": "catalog:", + "combinate": "catalog:", + "react": "catalog:", + "react-dom": "catalog:", "vite": "*", - "zod": "^4.4.3" + "zod": "catalog:", + "@tanstack/vite-config": "catalog:", + "vitest": "catalog:", + "jsdom": "catalog:", + "@eslint-react/eslint-plugin": "catalog:", + "eslint-plugin-react-hooks": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@arethetypeswrong/cli": "catalog:", + "publint": "catalog:", + "rimraf": "catalog:" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", diff --git a/packages/react-router/skills/compositions/router-query/SKILL.md b/packages/react-router/skills/compositions/router-query/SKILL.md index 89fba76b54..4fdd74fc30 100644 --- a/packages/react-router/skills/compositions/router-query/SKILL.md +++ b/packages/react-router/skills/compositions/router-query/SKILL.md @@ -1,14 +1,15 @@ --- -name: compositions/router-query +name: router-query description: >- Integrating TanStack Router with TanStack Query: queryClient - in router context, ensureQueryData/prefetchQuery in loaders, + in router context, static queries and fire-and-forget queries in loaders, useSuspenseQuery in components, defaultPreloadStaleTime: 0, setupRouterSsrQueryIntegration for SSR dehydration/hydration and streaming, per-request QueryClient isolation. -type: composition -library: tanstack-router -library_version: '1.166.2' +metadata: + type: composition + library: tanstack-router + library_version: '1.166.2' requires: - router-core - router-core/data-loading @@ -20,7 +21,7 @@ sources: # TanStack Router + TanStack Query Integration -This skill requires familiarity with both TanStack Router and TanStack Query. Read [router-core](../../../../router-core/skills/router-core/SKILL.md) and [react-router](../../react-router/SKILL.md) first. +This skill requires familiarity with both TanStack Router and TanStack Query. Read `@tanstack/router-core#router-core` and [react-router](../../react-router/SKILL.md) first. This skill covers coordinating TanStack Query as an external data cache with TanStack Router's loader system. The router acts as a **coordinator** — it triggers data fetching during navigation, while Query manages caching, background refetching, and data lifecycle. @@ -181,9 +182,9 @@ export function createAppRouter() { } ``` -## Core Pattern: `ensureQueryData` in Loader + `useSuspenseQuery` in Component +## Core Pattern: Static `query` in Loader + `useSuspenseQuery` in Component -This is the recommended pattern. The loader ensures data is in the cache before render (no loading flash). The component subscribes to the cache for updates. +This is the recommended pattern. The loader queries data before render (no loading flash), using `staleTime: 'static'` to reuse cached data without a stale refetch. The component subscribes to the cache for updates. ```tsx // src/routes/posts.tsx @@ -203,9 +204,12 @@ const postsQueryOptions = queryOptions({ export const Route = createFileRoute('/posts')({ loader: ({ context }) => { - // ensureQueryData returns cached data if available, fetches if not in cache - // To also refetch stale data, pass revalidateIfStale: true - return context.queryClient.ensureQueryData(postsQueryOptions) + // query returns cached data when available and fetches when it is missing + // Keep this query static so a stale refetch does not block navigation + return context.queryClient.query({ + ...postsQueryOptions, + staleTime: 'static', + }) }, component: PostsPage, }) @@ -245,7 +249,10 @@ const postQueryOptions = (postId: string) => export const Route = createFileRoute('/posts/$postId')({ loader: ({ context, params }) => { - return context.queryClient.ensureQueryData(postQueryOptions(params.postId)) + return context.queryClient.query({ + ...postQueryOptions(params.postId), + staleTime: 'static', + }) }, component: PostPage, }) @@ -258,20 +265,23 @@ function PostPage() { } ``` -## Streaming Pattern: `prefetchQuery` (Not Awaited) +## Streaming Pattern: Fire-and-Forget `query` (Not Awaited) -For non-critical data, start the fetch without blocking navigation: +For non-critical data, start a query without blocking navigation. Handle its rejection with `noop` so a background failure does not become an unhandled rejection: ```tsx -import { useQuery, useSuspenseQuery } from '@tanstack/react-query' +import { noop, useQuery, useSuspenseQuery } from '@tanstack/react-query' export const Route = createFileRoute('/dashboard')({ loader: ({ context }) => { // Await critical data - const user = context.queryClient.ensureQueryData(userQueryOptions) + const user = context.queryClient.query({ + ...userQueryOptions, + staleTime: 'static', + }) - // Start non-critical fetch without awaiting — streams during SSR - context.queryClient.prefetchQuery(analyticsQueryOptions) + // Start non-critical query without awaiting — streams during SSR + void context.queryClient.query({ ...analyticsQueryOptions }).catch(noop) return user }, @@ -303,7 +313,10 @@ import { useRouter } from '@tanstack/react-router' export const Route = createFileRoute('/posts')({ loader: ({ context }) => - context.queryClient.ensureQueryData(postsQueryOptions), + context.queryClient.query({ + ...postsQueryOptions, + staleTime: 'static', + }), errorComponent: PostsErrorComponent, component: PostsPage, }) @@ -312,7 +325,7 @@ function PostsErrorComponent({ error, reset, }: { - error: Error + error: unknown reset: () => void }) { const router = useRouter() @@ -324,7 +337,7 @@ function PostsErrorComponent({ return (
-

{error.message}

+

{error instanceof Error ? error.message : String(error)}

) @@ -372,24 +385,29 @@ export function createAppRouter() { } ``` -### 3. MEDIUM: Awaiting `prefetchQuery` in loader blocks rendering +### 3. MEDIUM: Awaiting a fire-and-forget query in a loader blocks rendering -`prefetchQuery` is designed to fire-and-forget. Awaiting it blocks the navigation transition until the data resolves, defeating the purpose of streaming. +A query used for streaming should start in the background and handle errors with `catch(noop)`. Awaiting it blocks the navigation transition until the data resolves, defeating the purpose of streaming. ```tsx +import { noop } from '@tanstack/react-query' + // WRONG — blocks navigation, no streaming benefit loader: async ({ context }) => { - await context.queryClient.prefetchQuery(analyticsQueryOptions) + await context.queryClient.query({ ...analyticsQueryOptions }).catch(noop) } -// CORRECT — fire and forget for streaming +// CORRECT — fire and forget for streaming, with handled rejection loader: ({ context }) => { - context.queryClient.prefetchQuery(analyticsQueryOptions) + void context.queryClient.query({ ...analyticsQueryOptions }).catch(noop) } -// If you need to block (critical data), use ensureQueryData instead: +// If you need to block (critical data), use a static query instead: loader: ({ context }) => { - return context.queryClient.ensureQueryData(criticalQueryOptions) + return context.queryClient.query({ + ...criticalQueryOptions, + staleTime: 'static', + }) } ``` @@ -414,10 +432,10 @@ const rootRoute = createRootRouteWithContext<{ queryClient: QueryClient }>()({ TanStack Router has its own SWR cache (`staleTime`, `gcTime`, `defaultPreloadStaleTime`). When using Query as an external cache: - Set `defaultPreloadStaleTime: 0` to prevent Router's cache from short-circuiting Query's freshness logic -- Router's `staleTime`/`gcTime` still apply to the loader return value. For pure Query patterns, return nothing from the loader (just `ensureQueryData` for the side effect) and read data exclusively from `useSuspenseQuery` -- `router.invalidate()` re-runs loaders (which call `ensureQueryData`), but Query decides whether to actually refetch based on its own `staleTime` +- Router's `staleTime`/`gcTime` still apply to the loader return value. For pure Query patterns, return nothing from the loader (just a static `query` for the side effect) and read data exclusively from `useSuspenseQuery` +- `router.invalidate()` re-runs loaders (which call `query` with `staleTime: 'static'`), so the cached Query data remains the freshness authority ## Cross-References -- [router-core/data-loading](../../../../router-core/skills/router-core/data-loading/SKILL.md) — built-in loader caching fundamentals -- [router-core/ssr](../../../../router-core/skills/router-core/ssr/SKILL.md) — SSR setup for dehydration/hydration +- `@tanstack/router-core#router-core/data-loading` — built-in loader caching fundamentals +- `@tanstack/router-core#router-core/ssr` — SSR setup for dehydration/hydration diff --git a/packages/react-router/skills/lifecycle/migrate-from-react-router/SKILL.md b/packages/react-router/skills/lifecycle/migrate-from-react-router/SKILL.md index c9f53358e6..fdc4f4c4e5 100644 --- a/packages/react-router/skills/lifecycle/migrate-from-react-router/SKILL.md +++ b/packages/react-router/skills/lifecycle/migrate-from-react-router/SKILL.md @@ -1,13 +1,14 @@ --- -name: lifecycle/migrate-from-react-router +name: migrate-from-react-router description: >- Step-by-step migration from React Router v7 to TanStack Router: route definition conversion, Link/useNavigate API differences, useSearchParams to validateSearch + useSearch, useParams with from, Outlet replacement, loader conversion, code splitting differences. -type: lifecycle -library: tanstack-router -library_version: '1.166.2' +metadata: + type: lifecycle + library: tanstack-router + library_version: '1.166.2' requires: - router-core - react-router diff --git a/packages/react-router/skills/react-router/SKILL.md b/packages/react-router/skills/react-router/SKILL.md index 074f23e091..f8df76df02 100644 --- a/packages/react-router/skills/react-router/SKILL.md +++ b/packages/react-router/skills/react-router/SKILL.md @@ -8,10 +8,11 @@ description: >- Outlet, CatchBoundary, ErrorComponent. React-specific patterns for hooks, providers, SSR hydration, and createLink with forwardRef. -type: framework -library: tanstack-router -library_version: '1.166.2' -framework: react +metadata: + type: framework + library: tanstack-router + library_version: '1.166.2' + framework: react requires: - router-core sources: @@ -22,9 +23,7 @@ sources: # React Router (`@tanstack/react-router`) -This skill builds on router-core. Read [router-core](../../../router-core/skills/router-core/SKILL.md) first for foundational concepts. - -This skill covers the React-specific bindings, components, hooks, and setup for TanStack Router. +This skill builds on router-core. Read `@tanstack/router-core#router-core` first for foundational concepts. > **CRITICAL**: TanStack Router types are FULLY INFERRED. Never cast, never annotate inferred values. > **CRITICAL**: TanStack Router is CLIENT-FIRST. Loaders run on the client by default, not on the server. @@ -347,7 +346,7 @@ import { CatchBoundary } from '@tanstack/react-router' ; 'widget'} onCatch={(error) => console.error(error)} - errorComponent={({ error }) =>
Error: {error.message}
} + errorComponent={({ error }) =>
{String(error)}
} >
@@ -496,4 +495,4 @@ function App() { ## Cross-References -- [router-core/SKILL.md](../../../router-core/skills/router-core/SKILL.md) — all sub-skills for domain-specific patterns (search params, data loading, navigation, auth, SSR, etc.) +- `@tanstack/router-core#router-core` — all sub-skills for domain-specific patterns (search params, data loading, navigation, auth, SSR, etc.) diff --git a/packages/react-router/src/Asset.tsx b/packages/react-router/src/Asset.tsx index 5e4f159f52..04cbac9064 100644 --- a/packages/react-router/src/Asset.tsx +++ b/packages/react-router/src/Asset.tsx @@ -42,6 +42,11 @@ export function Asset( }, ): React.ReactElement | null { const { attrs, children, nonce, preventScriptHoist } = asset + // React 19 compares this object by reference before assigning innerHTML. + const innerHTML = React.useMemo( + () => (children === undefined ? undefined : { __html: children }), + [children], + ) switch (asset.tag) { case 'title': @@ -78,11 +83,7 @@ export function Asset( } return ( -