diff --git a/.changeset/perf-frame-decoder-zero-copy.md b/.changeset/perf-frame-decoder-zero-copy.md deleted file mode 100644 index 182c81b66a..0000000000 --- a/.changeset/perf-frame-decoder-zero-copy.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@tanstack/start-client-core': patch ---- - -perf: zero-copy frame payload extraction in the client frame decoder. When a frame's bytes are fully contained in the first buffered chunk (the common case), return a subarray view instead of allocating a new buffer and copying. This is on the hot path for decoding streamed server-function responses and `RawStream` payloads. 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/.changeset/violet-poets-wait.md b/.changeset/violet-poets-wait.md deleted file mode 100644 index 9cb332593a..0000000000 --- a/.changeset/violet-poets-wait.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -'@tanstack/router-core': patch -'@tanstack/react-router': patch -'@tanstack/solid-router': patch -'@tanstack/vue-router': patch -'@tanstack/start-server-core': patch ---- - -Fix match loading consistency across client navigation, preloading, background reloads, server rendering, and hydration. - -- `beforeLoad` context is now propagated to descendant loaders and components during background reloads, preloaded navigation, route re-entry while background work is still in flight, and error or notFound states. -- Redirects no longer use a renderable `RouteMatch.status`; `RouteMatch.status` is now `'pending' | 'success' | 'error' | 'notFound'`. Abandoned, redirected, or failed matches are dropped from cache and their readiness promises are settled so stale suspense work cannot keep rendering suspended. -- Route assets from `head` and `scripts` are projected from the committed match lane after loader data is current, including preloaded navigations, background reloads, and SSR hydration. -- Pending UI and `pendingMinMs` now remain owned by match loading, so long-running `beforeLoad` or loader work does not prematurely clear pending fallbacks. -- SSR hydration now handles dehydrated and data-only matches in a dedicated hydration pass, restoring route context and assets without rerunning client loaders. -- Server loading now has a dedicated path for status codes, redirects, notFound and error responses. -- React, Solid, and Vue match rendering now consume the simplified match readiness model, including aborted loader errors, SSR/data-only pending fallbacks, and stale render snapshots. 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 70% rename from .github/workflows/client-nav-benchmarks.yml rename to .github/workflows/benchmarks.yml index eae3cd7448..bbc3a1fa24 100644 --- a/.github/workflows/client-nav-benchmarks.yml +++ b/.github/workflows/benchmarks.yml @@ -3,17 +3,33 @@ name: Benchmarks on: push: + # Broad on purpose: CodSpeed compares each PR against the run on its + # merge-base commit. Skipping main pushes that don't touch packages/** + # (pnpm config, CI, root tooling) leaves those commits without a baseline + # run, and CodSpeed silently falls back to an older, possibly outlier run — + # which then flags phantom regressions on every PR until the next eligible + # push. Only paths that cannot affect benchmark results are excluded. branches: - 'main' - paths: - - 'packages/**' - - 'benchmarks/**' + paths-ignore: + - 'docs/**' + - 'examples/**' + - 'e2e/**' 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 @@ -65,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/.github/workflows/release.yml b/.github/workflows/release.yml index fb5c69751c..115c3445e6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -55,6 +55,7 @@ jobs: commit: 'ci: changeset release' env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + NODE_OPTIONS: --max-old-space-size=8192 - name: Create GitHub Release if: steps.changesets.outputs.published == 'true' run: node scripts/create-github-release.mjs ${{ steps.dist-tag.outputs.prerelease == 'true' && '--prerelease' }} ${{ steps.dist-tag.outputs.latest == 'true' && '--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/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 44b58107e3..ec34ecc0c1 100644 --- a/benchmarks/client-nav/README.md +++ b/benchmarks/client-nav/README.md @@ -1,16 +1,87 @@ # Client Navigation Benchmarks -Cross-framework client-side navigation benchmarks for: +Cross-framework client-side CPU benchmarks for: - `@tanstack/react-router` - `@tanstack/solid-router` - `@tanstack/vue-router` +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 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 -- `react/` - React benchmark + Vitest config -- `solid/` - Solid benchmark + Vitest config -- `vue/` - Vue benchmark + Vitest config +- `react/`, `solid/`, `vue/` - baseline benchmark (mixed navigation loop) + Vitest config +- `vitest.react.config.ts`, `vitest.solid.config.ts`, `vitest.vue.config.ts` - per-framework aggregate configs that run the baseline first, then scenario projects +- `scenarios/harness.ts` - shared scenario runner (mount, link-click steps, `onRendered` synchronization) +- `scenarios//shared.ts` - framework-agnostic scenario definition (workload data, step sequence, assertions, bench options) +- `scenarios///` - isolated scenario apps + +Scenario app layout: + +```text +scenarios/// + vite.config.ts + speed.bench.ts + speed.flame.ts + setup.ts + project.json + tsconfig.json + src/ + main.tsx + routeTree.gen.ts + routes/ +``` + +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 +another scenario's numbers. The existing baseline apps and bench names stay +stable for CodSpeed continuity. + +## Scenario Responsibilities + +Each scenario isolates one client-side responsibility so benchmark changes can +be attributed to a specific feature area. + +| Scenario | Client-side responsibility | +| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `react/`, `solid/`, `vue/` baseline apps | Mixed navigation loop: path params, search params, route context, and `useParams`/`useSearch`/`useLoaderData` selector subscriptions. | +| `async-pipeline` | The router's async pipeline via counted 0ms timer hops: async loaders (transition-held navigation), async `beforeLoad` context, and parallel nested async loaders. Component-level `Await`/Suspense is excluded: React 19 throttles Suspense reveals by ~300ms wall-clock, which is inherently non-deterministic to benchmark. | +| `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. | +| `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). | +| `route-tree-scale` | Route matching and link-target resolution on a wide (~40 route) tree mixing static, dynamic, prefixed-param, splat, pathless-layout, and route-group paths, with `autoCodeSplitting` enabled so navigations also resolve lazy route chunks. | +| `search-params` | `validateSearch` execution, search middlewares (`retainSearchParams`/`stripSearchParams`), functional search updaters, structural sharing, and `useSearch` selector subscriptions. | + +## 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). ## Run @@ -20,7 +91,7 @@ Run all benchmarks through Nx so dependency builds are part of the graph: CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:perf --outputStyle=stream --skipRemoteCache ``` -Run framework-specific benchmarks: +Run framework-specific benchmarks (baseline + all scenarios): ```bash CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:perf:react --outputStyle=stream --skipRemoteCache @@ -28,16 +99,209 @@ CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:perf:solid --output CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:perf:vue --outputStyle=stream --skipRemoteCache ``` +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 --mode benchmark --config ./scenarios///vite.config.ts +``` + Run framework-specific flame benchmarks (10 second loop, profiled with `@platformatic/flame`, forced to `NODE_ENV=production`): ```bash +# baseline CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:flame:react --outputStyle=stream --skipRemoteCache CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:flame:solid --outputStyle=stream --skipRemoteCache CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:flame:vue --outputStyle=stream --skipRemoteCache +# scenarios +CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav--:test:flame --outputStyle=stream --skipRemoteCache ``` -Typecheck benchmark sources: +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/jsdom.ts b/benchmarks/client-nav/jsdom.ts index 05535e693d..855c2a2316 100644 --- a/benchmarks/client-nav/jsdom.ts +++ b/benchmarks/client-nav/jsdom.ts @@ -30,6 +30,11 @@ setGlobal('MutationObserver', window.MutationObserver) setGlobal('sessionStorage', window.sessionStorage) setGlobal('localStorage', window.localStorage) setGlobal('getComputedStyle', window.getComputedStyle.bind(window)) +setGlobal('addEventListener', window.addEventListener.bind(window)) +setGlobal('removeEventListener', window.removeEventListener.bind(window)) +setGlobal('dispatchEvent', window.dispatchEvent.bind(window)) +setGlobal('CustomEvent', window.CustomEvent) +setGlobal('Event', window.Event) setGlobal( 'requestAnimationFrame', @@ -45,5 +50,6 @@ setGlobal( ) window.scrollTo = () => {} +setGlobal('scrollTo', () => {}) export { window } 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 cb86e70654..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 ./react/vite.config.ts ./react/speed.bench.ts", - "test:perf:solid": "NODE_ENV=production vitest bench --config ./solid/vite.config.ts ./solid/speed.bench.ts", - "test:perf:vue": "NODE_ENV=production vitest bench --config ./vue/vite.config.ts ./vue/speed.bench.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,16 +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": { @@ -51,6 +57,25 @@ "@tanstack/react-router" ], "target": "build" + }, + { + "projects": [ + "@benchmarks/client-nav-async-pipeline-react", + "@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", + "@benchmarks/client-nav-nested-params-react", + "@benchmarks/client-nav-preload-react", + "@benchmarks/client-nav-rewrites-react", + "@benchmarks/client-nav-route-tree-scale-react", + "@benchmarks/client-nav-search-params-react" + ], + "target": "build:client" } ] }, @@ -62,6 +87,25 @@ "@tanstack/solid-router" ], "target": "build" + }, + { + "projects": [ + "@benchmarks/client-nav-async-pipeline-solid", + "@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", + "@benchmarks/client-nav-nested-params-solid", + "@benchmarks/client-nav-preload-solid", + "@benchmarks/client-nav-rewrites-solid", + "@benchmarks/client-nav-route-tree-scale-solid", + "@benchmarks/client-nav-search-params-solid" + ], + "target": "build:client" } ] }, @@ -73,6 +117,24 @@ "@tanstack/vue-router" ], "target": "build" + }, + { + "projects": [ + "@benchmarks/client-nav-async-pipeline-vue", + "@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", + "@benchmarks/client-nav-nested-params-vue", + "@benchmarks/client-nav-preload-vue", + "@benchmarks/client-nav-rewrites-vue", + "@benchmarks/client-nav-route-tree-scale-vue", + "@benchmarks/client-nav-search-params-vue" + ], + "target": "build:client" } ] }, @@ -121,9 +183,61 @@ ] }, "test:types": { - "cache": false, + "inputs": [ + "default", + "^production", + "{workspaceRoot}/eslint.config.js", + "{workspaceRoot}/benchmarks/cpu-simulation.ts", + "dependentTaskOutputs" + ], "dependsOn": [ - "^build" + "^build", + { + "projects": [ + "@benchmarks/client-nav-async-pipeline-react", + "@benchmarks/client-nav-async-pipeline-solid", + "@benchmarks/client-nav-async-pipeline-vue", + "@benchmarks/client-nav-control-flow-react", + "@benchmarks/client-nav-control-flow-solid", + "@benchmarks/client-nav-control-flow-vue", + "@benchmarks/client-nav-head-react", + "@benchmarks/client-nav-head-solid", + "@benchmarks/client-nav-head-vue", + "@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", + "@benchmarks/client-nav-loaders-vue", + "@benchmarks/client-nav-mount-react", + "@benchmarks/client-nav-mount-solid", + "@benchmarks/client-nav-mount-vue", + "@benchmarks/client-nav-nested-params-react", + "@benchmarks/client-nav-nested-params-solid", + "@benchmarks/client-nav-nested-params-vue", + "@benchmarks/client-nav-preload-react", + "@benchmarks/client-nav-preload-solid", + "@benchmarks/client-nav-preload-vue", + "@benchmarks/client-nav-rewrites-react", + "@benchmarks/client-nav-route-tree-scale-react", + "@benchmarks/client-nav-rewrites-solid", + "@benchmarks/client-nav-route-tree-scale-solid", + "@benchmarks/client-nav-rewrites-vue", + "@benchmarks/client-nav-route-tree-scale-vue", + "@benchmarks/client-nav-search-params-react", + "@benchmarks/client-nav-search-params-solid", + "@benchmarks/client-nav-search-params-vue" + ], + "target": "test:types:client" + } ] } } 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 ffa1d41be8..7df3f80e71 100644 --- a/benchmarks/client-nav/react/vite.config.ts +++ b/benchmarks/client-nav/react/vite.config.ts @@ -1,8 +1,15 @@ +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. +const rootDir = fileURLToPath(new URL('..', import.meta.url)) export default defineConfig({ + root: rootDir, define: { 'process.env.NODE_ENV': JSON.stringify('production'), }, @@ -22,9 +29,11 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav (react)', watch: false, environment: 'jsdom', - setupFiles: ['./vitest.setup.ts'], + setupFiles: [`${rootDir}vitest.setup.ts`], + benchmark: { include: ['react/speed.bench.ts'] }, }, }) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/project.json b/benchmarks/client-nav/scenarios/async-pipeline/react/project.json new file mode 100644 index 0000000000..44ab55ccfe --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-async-pipeline-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/async-pipeline/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/setup.ts b/benchmarks/client-nav/scenarios/async-pipeline/react/setup.ts new file mode 100644 index 0000000000..130583b190 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } 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, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts b/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts new file mode 100644 index 0000000000..65dab0781e --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/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-async-pipeline', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-async-pipeline 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/async-pipeline/react/speed.flame.ts b/benchmarks/client-nav/scenarios/async-pipeline/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/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/async-pipeline/react/src/main.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/main.tsx new file mode 100644 index 0000000000..cab86a1272 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/src/main.tsx @@ -0,0 +1,39 @@ +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, + defaultPendingMs: 0, + defaultPendingMinMs: 0, + }) +} + +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/async-pipeline/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..9c79bab826 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routeTree.gen.ts @@ -0,0 +1,140 @@ +/* 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 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 IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +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({ + id: '/$id', + path: '/$id', + getParentRoute: () => NestedRoute, +} as any) +const SlowIdRoute = SlowIdRouteImport.update({ + id: '/slow/$id', + path: '/slow/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/nested': typeof NestedRouteWithChildren + '/ctx/$id': typeof CtxIdRoute + '/nested/$id': typeof NestedIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/nested': typeof NestedRouteWithChildren + '/ctx/$id': typeof CtxIdRoute + '/nested/$id': typeof NestedIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/nested': typeof NestedRouteWithChildren + '/ctx/$id': typeof CtxIdRoute + '/nested/$id': typeof NestedIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' + id: '__root__' | '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + NestedRoute: typeof NestedRouteWithChildren + CtxIdRoute: typeof CtxIdRoute + SlowIdRoute: typeof SlowIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/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': { + id: '/nested/$id' + path: '/$id' + fullPath: '/nested/$id' + preLoaderRoute: typeof NestedIdRouteImport + parentRoute: typeof NestedRoute + } + '/slow/$id': { + id: '/slow/$id' + path: '/slow/$id' + fullPath: '/slow/$id' + preLoaderRoute: typeof SlowIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +interface NestedRouteChildren { + NestedIdRoute: typeof NestedIdRoute +} + +const NestedRouteChildren: NestedRouteChildren = { + NestedIdRoute: NestedIdRoute, +} + +const NestedRouteWithChildren = + NestedRoute._addFileChildren(NestedRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + NestedRoute: NestedRouteWithChildren, + CtxIdRoute: CtxIdRoute, + SlowIdRoute: SlowIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/__root.tsx new file mode 100644 index 0000000000..1cc8566678 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/__root.tsx @@ -0,0 +1,50 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +const ids = ['1', '2'] + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/ctx.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/ctx.$id.tsx new file mode 100644 index 0000000000..d644376b7b --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/ctx.$id.tsx @@ -0,0 +1,29 @@ +import { createFileRoute } from '@tanstack/react-router' +import { + ctxSeedValue, + ctxStateValue, + deferredHops, + hopDelay, +} from '../../../shared' + +export const Route = createFileRoute('/ctx/$id')({ + staleTime: 0, + gcTime: 0, + beforeLoad: async ({ params }) => { + await hopDelay(deferredHops) + return { ctxSeed: ctxSeedValue(params.id) } + }, + loader: ({ params, context }) => { + if (context.ctxSeed !== ctxSeedValue(params.id)) { + throw new Error('beforeLoad context missing in loader') + } + return { value: ctxStateValue(params.id) } + }, + component: CtxPage, +}) + +function CtxPage() { + const data = Route.useLoaderData() + + return
{data.value}
+} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/index.tsx new file mode 100644 index 0000000000..5b6d70e744 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/index.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return ( +
+
home
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/nested.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/nested.$id.tsx new file mode 100644 index 0000000000..bc002c303f --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/nested.$id.tsx @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/react-router' +import { deferredHops, hopDelay, nestedStateValue } from '../../../shared' + +export const Route = createFileRoute('/nested/$id')({ + staleTime: 0, + gcTime: 0, + loader: async ({ params }) => { + await hopDelay(deferredHops) + return { value: nestedStateValue(params.id) } + }, + component: NestedPage, +}) + +function NestedPage() { + const data = Route.useLoaderData() + + return
{data.value}
+} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/nested.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/nested.tsx new file mode 100644 index 0000000000..443f592373 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/nested.tsx @@ -0,0 +1,23 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { deferredHops, hopDelay, nestedLayoutValue } from '../../../shared' + +export const Route = createFileRoute('/nested')({ + staleTime: 0, + gcTime: 0, + loader: async () => { + await hopDelay(deferredHops) + return { value: nestedLayoutValue() } + }, + component: NestedLayout, +}) + +function NestedLayout() { + const data = Route.useLoaderData() + + return ( +
+
{data.value}
+ +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/slow.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/slow.$id.tsx new file mode 100644 index 0000000000..4839b0ca6d --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/src/routes/slow.$id.tsx @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/react-router' +import { deferredHops, hopDelay, slowStateValue } from '../../../shared' + +export const Route = createFileRoute('/slow/$id')({ + staleTime: 0, + gcTime: 0, + loader: async ({ params }) => { + await hopDelay(deferredHops) + return { value: slowStateValue(params.id) } + }, + component: SlowPage, +}) + +function SlowPage() { + const data = Route.useLoaderData() + + return
{data.value}
+} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/tsconfig.json b/benchmarks/client-nav/scenarios/async-pipeline/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/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/async-pipeline/react/vite.config.ts b/benchmarks/client-nav/scenarios/async-pipeline/react/vite.config.ts new file mode 100644 index 0000000000..e36a5244b1 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/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 async-pipeline (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/shared.ts b/benchmarks/client-nav/scenarios/async-pipeline/shared.ts new file mode 100644 index 0000000000..02123309b2 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/shared.ts @@ -0,0 +1,113 @@ +/** + * Shared definition of the `async-pipeline` scenario: the router's async + * load pipeline — fully async loaders (transition-held navigations), async + * `beforeLoad` context building, and parallel nested async loaders. All async + * work resolves through counted 0ms timer hops so the workload is + * deterministic. The three framework apps consume these builders so the + * workload is identical modulo the rendering layer. + * + * Note: component-level deferred consumption (`Await`/Suspense) is + * intentionally NOT covered. React throttles every Suspense reveal (with or + * without a fallback, including `pendingComponent`) by ~300ms of wall-clock + * time, which cannot be made deterministic; the async work is exercised + * through the router's own pipeline instead. + */ +import type { ScenarioStep } from '../harness' + +/** + * Resolves after exactly `hops` chained macrotask turns. Uses `setImmediate` + * rather than `setTimeout(0)`: both are counted, deterministic event-loop + * turns, but timers cost ~3-4 syscalls per hop (timerfd + epoll) and CodSpeed + * excludes syscall time from the measure — inconsistently past a threshold — + * which destabilized the hop-heavy benches. + */ +export function hopDelay(hops: number): Promise { + let promise = Promise.resolve() + for (let i = 0; i < hops; i++) { + promise = promise.then( + () => new Promise((resolve) => setImmediate(() => resolve())), + ) + } + return promise +} + +/** Number of 0ms hops every async loader/beforeLoad takes before resolving. */ +export const deferredHops = 2 + +function checksum(seed: number) { + let value = seed | 0 + for (let index = 0; index < 20; index++) { + value = (value * 1664525 + 1013904223 + index) >>> 0 + } + return value +} + +export function slowStateValue(id: string) { + return `state-${id}-${checksum(Number(id) * 71 + 3)}` +} + +export function ctxSeedValue(id: string) { + return checksum(Number(id) * 13 + 1) +} + +export function ctxStateValue(id: string) { + return `ctx-${id}-${checksum(ctxSeedValue(id) + 5)}` +} + +export function nestedLayoutValue() { + return `layout-${checksum(97)}` +} + +export function nestedStateValue(id: string) { + return `nested-${id}-${checksum(Number(id) * 41 + 11)}` +} + +function markerText(testId: string) { + return ( + document.querySelector(`[data-testid="${testId}"]`)?.textContent ?? + undefined + ) +} + +function step(testId: string, isSettled: () => boolean): ScenarioStep { + return { type: 'click', testId, isSettled } +} + +export const steps: ReadonlyArray = [ + step('go-slow-1', () => markerText('slow-state') === slowStateValue('1')), + step('go-ctx-1', () => markerText('ctx-state') === ctxStateValue('1')), + step( + 'go-nested-1', + () => + markerText('nested-layout') === nestedLayoutValue() && + markerText('nested-state') === nestedStateValue('1'), + ), + step('go-slow-2', () => markerText('slow-state') === slowStateValue('2')), + step('go-ctx-2', () => markerText('ctx-state') === ctxStateValue('2')), + step( + 'go-nested-2', + () => markerText('nested-state') === nestedStateValue('2'), + ), + step('go-home', () => markerText('home-state') === 'home'), +] + +export function assertStepResult(stepIndex: number) { + const current = steps[stepIndex]! + if (typeof current === 'string' || !('isSettled' in current)) { + return + } + if (!current.isSettled!()) { + throw new Error( + `Unexpected document state after async-pipeline step ${stepIndex}`, + ) + } +} + +// Two laps through the 7-step sequence per benchmark iteration. +export const ticksPerIteration = 14 + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/project.json b/benchmarks/client-nav/scenarios/async-pipeline/solid/project.json new file mode 100644 index 0000000000..2fce426b1e --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-async-pipeline-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/async-pipeline/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/setup.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/setup.ts new file mode 100644 index 0000000000..6a46971603 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } 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, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts new file mode 100644 index 0000000000..acef710469 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/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-async-pipeline', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-async-pipeline 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/async-pipeline/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/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/async-pipeline/solid/src/main.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/main.tsx new file mode 100644 index 0000000000..4c6d49f501 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/main.tsx @@ -0,0 +1,36 @@ +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, + defaultPendingMs: 0, + defaultPendingMinMs: 0, + }) +} + +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/async-pipeline/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..27b9498b11 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routeTree.gen.ts @@ -0,0 +1,140 @@ +/* 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 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 IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +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({ + id: '/$id', + path: '/$id', + getParentRoute: () => NestedRoute, +} as any) +const SlowIdRoute = SlowIdRouteImport.update({ + id: '/slow/$id', + path: '/slow/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/nested': typeof NestedRouteWithChildren + '/ctx/$id': typeof CtxIdRoute + '/nested/$id': typeof NestedIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/nested': typeof NestedRouteWithChildren + '/ctx/$id': typeof CtxIdRoute + '/nested/$id': typeof NestedIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/nested': typeof NestedRouteWithChildren + '/ctx/$id': typeof CtxIdRoute + '/nested/$id': typeof NestedIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' + id: '__root__' | '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + NestedRoute: typeof NestedRouteWithChildren + CtxIdRoute: typeof CtxIdRoute + SlowIdRoute: typeof SlowIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/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': { + id: '/nested/$id' + path: '/$id' + fullPath: '/nested/$id' + preLoaderRoute: typeof NestedIdRouteImport + parentRoute: typeof NestedRoute + } + '/slow/$id': { + id: '/slow/$id' + path: '/slow/$id' + fullPath: '/slow/$id' + preLoaderRoute: typeof SlowIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +interface NestedRouteChildren { + NestedIdRoute: typeof NestedIdRoute +} + +const NestedRouteChildren: NestedRouteChildren = { + NestedIdRoute: NestedIdRoute, +} + +const NestedRouteWithChildren = + NestedRoute._addFileChildren(NestedRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + NestedRoute: NestedRouteWithChildren, + CtxIdRoute: CtxIdRoute, + SlowIdRoute: SlowIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..7d3647fee8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/__root.tsx @@ -0,0 +1,46 @@ +import { For } from 'solid-js' +import { Link, Outlet, createRootRoute } from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +const ids = ['1', '2'] + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/ctx.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/ctx.$id.tsx new file mode 100644 index 0000000000..e757b57b9d --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/ctx.$id.tsx @@ -0,0 +1,29 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { + ctxSeedValue, + ctxStateValue, + deferredHops, + hopDelay, +} from '../../../shared' + +export const Route = createFileRoute('/ctx/$id')({ + staleTime: 0, + gcTime: 0, + beforeLoad: async ({ params }) => { + await hopDelay(deferredHops) + return { ctxSeed: ctxSeedValue(params.id) } + }, + loader: ({ params, context }) => { + if (context.ctxSeed !== ctxSeedValue(params.id)) { + throw new Error('beforeLoad context missing in loader') + } + return { value: ctxStateValue(params.id) } + }, + component: CtxPage, +}) + +function CtxPage() { + const data = Route.useLoaderData() + + return
{data().value}
+} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/index.tsx new file mode 100644 index 0000000000..12907d440d --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/index.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return ( +
+
home
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/nested.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/nested.$id.tsx new file mode 100644 index 0000000000..5518ccf498 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/nested.$id.tsx @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { deferredHops, hopDelay, nestedStateValue } from '../../../shared' + +export const Route = createFileRoute('/nested/$id')({ + staleTime: 0, + gcTime: 0, + loader: async ({ params }) => { + await hopDelay(deferredHops) + return { value: nestedStateValue(params.id) } + }, + component: NestedPage, +}) + +function NestedPage() { + const data = Route.useLoaderData() + + return
{data().value}
+} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/nested.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/nested.tsx new file mode 100644 index 0000000000..fdc939dc95 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/nested.tsx @@ -0,0 +1,23 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { deferredHops, hopDelay, nestedLayoutValue } from '../../../shared' + +export const Route = createFileRoute('/nested')({ + staleTime: 0, + gcTime: 0, + loader: async () => { + await hopDelay(deferredHops) + return { value: nestedLayoutValue() } + }, + component: NestedLayout, +}) + +function NestedLayout() { + const data = Route.useLoaderData() + + return ( +
+
{data().value}
+ +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/slow.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/slow.$id.tsx new file mode 100644 index 0000000000..4c229407e1 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routes/slow.$id.tsx @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { deferredHops, hopDelay, slowStateValue } from '../../../shared' + +export const Route = createFileRoute('/slow/$id')({ + staleTime: 0, + gcTime: 0, + loader: async ({ params }) => { + await hopDelay(deferredHops) + return { value: slowStateValue(params.id) } + }, + component: SlowPage, +}) + +function SlowPage() { + const data = Route.useLoaderData() + + return
{data().value}
+} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/tsconfig.json b/benchmarks/client-nav/scenarios/async-pipeline/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/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/async-pipeline/solid/vite.config.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/vite.config.ts new file mode 100644 index 0000000000..214da8042e --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/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 async-pipeline (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/project.json b/benchmarks/client-nav/scenarios/async-pipeline/vue/project.json new file mode 100644 index 0000000000..911bb61e38 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-async-pipeline-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/async-pipeline/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/setup.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/setup.ts new file mode 100644 index 0000000000..97b74b3892 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } 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, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts new file mode 100644 index 0000000000..f0fd3e58df --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/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-async-pipeline', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-async-pipeline 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/async-pipeline/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/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/async-pipeline/vue/src/main.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/main.tsx new file mode 100644 index 0000000000..e1bfa5965f --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/main.tsx @@ -0,0 +1,43 @@ +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, + defaultPendingMs: 0, + defaultPendingMinMs: 0, + }) +} + +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/async-pipeline/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..66b9efd7aa --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routeTree.gen.ts @@ -0,0 +1,140 @@ +/* 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 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 IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +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({ + id: '/$id', + path: '/$id', + getParentRoute: () => NestedRoute, +} as any) +const SlowIdRoute = SlowIdRouteImport.update({ + id: '/slow/$id', + path: '/slow/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/nested': typeof NestedRouteWithChildren + '/ctx/$id': typeof CtxIdRoute + '/nested/$id': typeof NestedIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/nested': typeof NestedRouteWithChildren + '/ctx/$id': typeof CtxIdRoute + '/nested/$id': typeof NestedIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/nested': typeof NestedRouteWithChildren + '/ctx/$id': typeof CtxIdRoute + '/nested/$id': typeof NestedIdRoute + '/slow/$id': typeof SlowIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' + id: '__root__' | '/' | '/nested' | '/ctx/$id' | '/nested/$id' | '/slow/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + NestedRoute: typeof NestedRouteWithChildren + CtxIdRoute: typeof CtxIdRoute + SlowIdRoute: typeof SlowIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/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': { + id: '/nested/$id' + path: '/$id' + fullPath: '/nested/$id' + preLoaderRoute: typeof NestedIdRouteImport + parentRoute: typeof NestedRoute + } + '/slow/$id': { + id: '/slow/$id' + path: '/slow/$id' + fullPath: '/slow/$id' + preLoaderRoute: typeof SlowIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +interface NestedRouteChildren { + NestedIdRoute: typeof NestedIdRoute +} + +const NestedRouteChildren: NestedRouteChildren = { + NestedIdRoute: NestedIdRoute, +} + +const NestedRouteWithChildren = + NestedRoute._addFileChildren(NestedRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + NestedRoute: NestedRouteWithChildren, + CtxIdRoute: CtxIdRoute, + SlowIdRoute: SlowIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..c477ab7e68 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/__root.tsx @@ -0,0 +1,53 @@ +import * as Vue from 'vue' +import { Link, Outlet, createRootRoute } from '@tanstack/vue-router' + +const ids = ['1', '2'] + +const RootComponent = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + ) + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/ctx.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/ctx.$id.tsx new file mode 100644 index 0000000000..d995f1ff6c --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/ctx.$id.tsx @@ -0,0 +1,32 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { + ctxSeedValue, + ctxStateValue, + deferredHops, + hopDelay, +} from '../../../shared' + +const CtxPage = Vue.defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () =>
{data.value.value}
+ }, +}) + +export const Route = createFileRoute('/ctx/$id')({ + staleTime: 0, + gcTime: 0, + beforeLoad: async ({ params }) => { + await hopDelay(deferredHops) + return { ctxSeed: ctxSeedValue(params.id) } + }, + loader: ({ params, context }) => { + if (context.ctxSeed !== ctxSeedValue(params.id)) { + throw new Error('beforeLoad context missing in loader') + } + return { value: ctxStateValue(params.id) } + }, + component: CtxPage, +}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/index.tsx new file mode 100644 index 0000000000..128e132190 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/index.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const HomePage = Vue.defineComponent({ + setup() { + return () => ( +
+
home
+
+ ) + }, +}) + +export const Route = createFileRoute('/')({ + component: HomePage, +}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/nested.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/nested.$id.tsx new file mode 100644 index 0000000000..bbeaaa7dd7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/nested.$id.tsx @@ -0,0 +1,21 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { deferredHops, hopDelay, nestedStateValue } from '../../../shared' + +const NestedPage = Vue.defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () =>
{data.value.value}
+ }, +}) + +export const Route = createFileRoute('/nested/$id')({ + staleTime: 0, + gcTime: 0, + loader: async ({ params }) => { + await hopDelay(deferredHops) + return { value: nestedStateValue(params.id) } + }, + component: NestedPage, +}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/nested.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/nested.tsx new file mode 100644 index 0000000000..763657dfc6 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/nested.tsx @@ -0,0 +1,26 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { deferredHops, hopDelay, nestedLayoutValue } from '../../../shared' + +const NestedLayout = Vue.defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () => ( +
+
{data.value.value}
+ +
+ ) + }, +}) + +export const Route = createFileRoute('/nested')({ + staleTime: 0, + gcTime: 0, + loader: async () => { + await hopDelay(deferredHops) + return { value: nestedLayoutValue() } + }, + component: NestedLayout, +}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/slow.$id.tsx b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/slow.$id.tsx new file mode 100644 index 0000000000..c9afccba97 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routes/slow.$id.tsx @@ -0,0 +1,21 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { deferredHops, hopDelay, slowStateValue } from '../../../shared' + +const SlowPage = Vue.defineComponent({ + setup() { + const data = Route.useLoaderData() + + return () =>
{data.value.value}
+ }, +}) + +export const Route = createFileRoute('/slow/$id')({ + staleTime: 0, + gcTime: 0, + loader: async ({ params }) => { + await hopDelay(deferredHops) + return { value: slowStateValue(params.id) } + }, + component: SlowPage, +}) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/tsconfig.json b/benchmarks/client-nav/scenarios/async-pipeline/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/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/async-pipeline/vue/vite.config.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/vite.config.ts new file mode 100644 index 0000000000..ce4fa7318a --- /dev/null +++ b/benchmarks/client-nav/scenarios/async-pipeline/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 async-pipeline (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/react/project.json b/benchmarks/client-nav/scenarios/control-flow/react/project.json new file mode 100644 index 0000000000..e3e580911f --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-control-flow-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/control-flow/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/setup.ts b/benchmarks/client-nav/scenarios/control-flow/react/setup.ts new file mode 100644 index 0000000000..130583b190 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } 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, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts b/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts new file mode 100644 index 0000000000..d6f2190be7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/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-control-flow', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-control-flow 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/control-flow/react/speed.flame.ts b/benchmarks/client-nav/scenarios/control-flow/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/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/control-flow/react/src/main.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/main.tsx new file mode 100644 index 0000000000..da9e63d293 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/src/main.tsx @@ -0,0 +1,39 @@ +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) + + // The scenario intentionally throws loader errors every lap; keep React 19's + // default per-caught-error console reporting out of the measured loop. + const reactRoot = createRoot(container, { onCaughtError: () => {} }) + reactRoot.render() + + return { + router, + unmount() { + reactRoot.unmount() + }, + } +} 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 new file mode 100644 index 0000000000..7b6db9b237 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/src/routeTree.gen.ts @@ -0,0 +1,156 @@ +/* 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 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 IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const BrokenRoute = BrokenRouteImport.update({ + id: '/broken', + path: '/broken', + getParentRoute: () => rootRouteImport, +} as any) +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({ + id: '/missing/$id', + path: '/missing/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/broken': typeof BrokenRoute + '/hop1': typeof Hop1Route + '/hop2': typeof Hop2Route + '/target': typeof TargetRoute + '/missing/$id': typeof MissingIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/broken': typeof BrokenRoute + '/hop1': typeof Hop1Route + '/hop2': typeof Hop2Route + '/target': typeof TargetRoute + '/missing/$id': typeof MissingIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/broken': typeof BrokenRoute + '/hop1': typeof Hop1Route + '/hop2': typeof Hop2Route + '/target': typeof TargetRoute + '/missing/$id': typeof MissingIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/broken' | '/hop1' | '/hop2' | '/target' | '/missing/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/broken' | '/hop1' | '/hop2' | '/target' | '/missing/$id' + id: + | '__root__' + | '/' + | '/broken' + | '/hop1' + | '/hop2' + | '/target' + | '/missing/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + BrokenRoute: typeof BrokenRoute + Hop1Route: typeof Hop1Route + Hop2Route: typeof Hop2Route + TargetRoute: typeof TargetRoute + MissingIdRoute: typeof MissingIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/broken': { + id: '/broken' + path: '/broken' + fullPath: '/broken' + preLoaderRoute: typeof BrokenRouteImport + parentRoute: typeof rootRouteImport + } + '/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': { + id: '/missing/$id' + path: '/missing/$id' + fullPath: '/missing/$id' + preLoaderRoute: typeof MissingIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + BrokenRoute: BrokenRoute, + Hop1Route: Hop1Route, + Hop2Route: Hop2Route, + TargetRoute: TargetRoute, + MissingIdRoute: MissingIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/__root.tsx new file mode 100644 index 0000000000..63d5feb901 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/__root.tsx @@ -0,0 +1,52 @@ +import { + Link, + Outlet, + createRootRoute, + useLocation, +} from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function LocationMarker() { + const pathname = useLocation({ select: (location) => location.pathname }) + return {pathname} +} + +function RootComponent() { + return ( + <> + + + + + ) +} 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 new file mode 100644 index 0000000000..b11bb845bc --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/broken.tsx @@ -0,0 +1,20 @@ +import { createFileRoute } from '@tanstack/react-router' +import { errorMessage } from '../../../shared' +import type { ErrorComponentProps } from '@tanstack/react-router' + +export const Route = createFileRoute('/broken')({ + staleTime: 0, + gcTime: 0, + loader: () => { + throw new Error(errorMessage) + }, + errorComponent: BrokenError, +}) + +function BrokenError(props: ErrorComponentProps) { + return ( +
+ {props.error instanceof Error ? props.error.message : String(props.error)} +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/hop1.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/hop1.tsx new file mode 100644 index 0000000000..aacba39384 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/hop1.tsx @@ -0,0 +1,9 @@ +import { createFileRoute, redirect } from '@tanstack/react-router' + +export const Route = createFileRoute('/hop1')({ + staleTime: 0, + gcTime: 0, + loader: () => { + throw redirect({ to: '/hop2' }) + }, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/hop2.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/hop2.tsx new file mode 100644 index 0000000000..db31abe9f3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/hop2.tsx @@ -0,0 +1,9 @@ +import { createFileRoute, redirect } from '@tanstack/react-router' + +export const Route = createFileRoute('/hop2')({ + staleTime: 0, + gcTime: 0, + loader: () => { + throw redirect({ to: '/target' }) + }, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/index.tsx new file mode 100644 index 0000000000..24e856ea15 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return
home
+} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/missing.$id.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/missing.$id.tsx new file mode 100644 index 0000000000..0c807bb2bc --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/missing.$id.tsx @@ -0,0 +1,23 @@ +import { createFileRoute, notFound } from '@tanstack/react-router' + +export const Route = createFileRoute('/missing/$id')({ + staleTime: 0, + gcTime: 0, + loader: ({ params }) => { + if (params.id === 'gone') { + throw notFound() + } + return { id: params.id } + }, + component: MissingPage, + notFoundComponent: MissingNotFound, +}) + +function MissingPage() { + const data = Route.useLoaderData() + return
{data.id}
+} + +function MissingNotFound() { + return
missing not found
+} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/src/routes/target.tsx b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/target.tsx new file mode 100644 index 0000000000..280f65835e --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/react/src/routes/target.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/target')({ + component: TargetPage, +}) + +function TargetPage() { + return
target
+} diff --git a/benchmarks/client-nav/scenarios/control-flow/react/tsconfig.json b/benchmarks/client-nav/scenarios/control-flow/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/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/control-flow/react/vite.config.ts b/benchmarks/client-nav/scenarios/control-flow/react/vite.config.ts new file mode 100644 index 0000000000..1eefca0fc3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/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 control-flow (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/shared.ts b/benchmarks/client-nav/scenarios/control-flow/shared.ts new file mode 100644 index 0000000000..c4f368bee1 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/shared.ts @@ -0,0 +1,91 @@ +/** + * Shared definition of the `control-flow` scenario: loader-thrown redirects + * (including a 2-hop chain), notFound() rendering, loader errors through the + * route error boundary, and recovery navigation resetting the boundary. + */ +import type { ScenarioStep } from '../harness' + +export const errorMessage = 'bench-error' + +export const steps: ReadonlyArray = [ + { + type: 'click', + testId: 'go-hop1', + // The click lands on /hop1 whose loader chains redirects to /target; wait + // until the post-redirect location is committed before finishing the step. + isSettled: () => + document.querySelector('[data-testid="loc"]')?.textContent === '/target', + }, + 'go-missing-ok', + 'go-missing-gone', + 'go-broken', + 'go-target', + 'go-missing-gone', + 'home', +] + +interface StepExpectation { + loc: string + present: ReadonlyArray + absent?: ReadonlyArray + errorText?: string +} + +const expectations: ReadonlyArray = [ + { loc: '/target', present: ['target-state'] }, + { loc: '/missing/exists', present: ['missing-state'] }, + { + loc: '/missing/gone', + present: ['not-found-state'], + absent: ['missing-state'], + }, + { loc: '/broken', present: ['error-state'], errorText: errorMessage }, + { loc: '/target', present: ['target-state'], absent: ['error-state'] }, + { loc: '/missing/gone', present: ['not-found-state'] }, + { loc: '/', present: ['home-state'] }, +] + +export function assertStepResult(stepIndex: number, container: HTMLElement) { + const expectation = expectations[stepIndex % expectations.length]! + + const loc = container.querySelector('[data-testid="loc"]') + if (loc?.textContent !== expectation.loc) { + throw new Error( + `Expected location "${expectation.loc}" after step ${stepIndex}, received "${loc?.textContent ?? ''}"`, + ) + } + + for (const testId of expectation.present) { + const element = container.querySelector(`[data-testid="${testId}"]`) + if (!element) { + throw new Error( + `Expected [data-testid="${testId}"] after step ${stepIndex}`, + ) + } + if ( + expectation.errorText && + !element.textContent?.includes(expectation.errorText) + ) { + throw new Error( + `Expected [data-testid="${testId}"] to include "${expectation.errorText}", received "${element.textContent}"`, + ) + } + } + + for (const testId of expectation.absent ?? []) { + if (container.querySelector(`[data-testid="${testId}"]`)) { + throw new Error( + `Expected [data-testid="${testId}"] to be absent after step ${stepIndex}`, + ) + } + } +} + +// Two laps through the 7-step sequence per benchmark iteration. +export const ticksPerIteration = 14 + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/project.json b/benchmarks/client-nav/scenarios/control-flow/solid/project.json new file mode 100644 index 0000000000..2b5154d385 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-control-flow-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/control-flow/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/setup.ts b/benchmarks/client-nav/scenarios/control-flow/solid/setup.ts new file mode 100644 index 0000000000..6a46971603 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } 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, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts new file mode 100644 index 0000000000..d803d2a313 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/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-control-flow', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-control-flow 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/control-flow/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/control-flow/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/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/control-flow/solid/src/main.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/main.tsx new file mode 100644 index 0000000000..fa9d239418 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/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/control-flow/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..cd84f99d5d --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts @@ -0,0 +1,156 @@ +/* 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 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 IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const BrokenRoute = BrokenRouteImport.update({ + id: '/broken', + path: '/broken', + getParentRoute: () => rootRouteImport, +} as any) +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({ + id: '/missing/$id', + path: '/missing/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/broken': typeof BrokenRoute + '/hop1': typeof Hop1Route + '/hop2': typeof Hop2Route + '/target': typeof TargetRoute + '/missing/$id': typeof MissingIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/broken': typeof BrokenRoute + '/hop1': typeof Hop1Route + '/hop2': typeof Hop2Route + '/target': typeof TargetRoute + '/missing/$id': typeof MissingIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/broken': typeof BrokenRoute + '/hop1': typeof Hop1Route + '/hop2': typeof Hop2Route + '/target': typeof TargetRoute + '/missing/$id': typeof MissingIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/broken' | '/hop1' | '/hop2' | '/target' | '/missing/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/broken' | '/hop1' | '/hop2' | '/target' | '/missing/$id' + id: + | '__root__' + | '/' + | '/broken' + | '/hop1' + | '/hop2' + | '/target' + | '/missing/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + BrokenRoute: typeof BrokenRoute + Hop1Route: typeof Hop1Route + Hop2Route: typeof Hop2Route + TargetRoute: typeof TargetRoute + MissingIdRoute: typeof MissingIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/broken': { + id: '/broken' + path: '/broken' + fullPath: '/broken' + preLoaderRoute: typeof BrokenRouteImport + parentRoute: typeof rootRouteImport + } + '/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': { + id: '/missing/$id' + path: '/missing/$id' + fullPath: '/missing/$id' + preLoaderRoute: typeof MissingIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + BrokenRoute: BrokenRoute, + Hop1Route: Hop1Route, + Hop2Route: Hop2Route, + TargetRoute: TargetRoute, + MissingIdRoute: MissingIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..1bce9e8a3e --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/__root.tsx @@ -0,0 +1,52 @@ +import { + Link, + Outlet, + createRootRoute, + useLocation, +} from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function LocationMarker() { + const pathname = useLocation({ select: (location) => location.pathname }) + return {pathname()} +} + +function RootComponent() { + return ( + <> + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/broken.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/broken.tsx new file mode 100644 index 0000000000..9931ef9c58 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/broken.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { errorMessage } from '../../../shared' +import type { ErrorComponentProps } from '@tanstack/solid-router' + +export const Route = createFileRoute('/broken')({ + staleTime: 0, + gcTime: 0, + loader: () => { + throw new Error(errorMessage) + }, + errorComponent: BrokenError, +}) + +function BrokenError(props: ErrorComponentProps) { + return
{props.error.message}
+} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/hop1.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/hop1.tsx new file mode 100644 index 0000000000..1aedb481ec --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/hop1.tsx @@ -0,0 +1,9 @@ +import { createFileRoute, redirect } from '@tanstack/solid-router' + +export const Route = createFileRoute('/hop1')({ + staleTime: 0, + gcTime: 0, + loader: () => { + throw redirect({ to: '/hop2' }) + }, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/hop2.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/hop2.tsx new file mode 100644 index 0000000000..91b601c516 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/hop2.tsx @@ -0,0 +1,9 @@ +import { createFileRoute, redirect } from '@tanstack/solid-router' + +export const Route = createFileRoute('/hop2')({ + staleTime: 0, + gcTime: 0, + loader: () => { + throw redirect({ to: '/target' }) + }, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/index.tsx new file mode 100644 index 0000000000..cc46764de5 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return
home
+} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/missing.$id.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/missing.$id.tsx new file mode 100644 index 0000000000..9c0493fb48 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/missing.$id.tsx @@ -0,0 +1,23 @@ +import { createFileRoute, notFound } from '@tanstack/solid-router' + +export const Route = createFileRoute('/missing/$id')({ + staleTime: 0, + gcTime: 0, + loader: ({ params }) => { + if (params.id === 'gone') { + throw notFound() + } + return { id: params.id } + }, + component: MissingPage, + notFoundComponent: MissingNotFound, +}) + +function MissingPage() { + const data = Route.useLoaderData() + return
{data().id}
+} + +function MissingNotFound() { + return
missing not found
+} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/target.tsx b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/target.tsx new file mode 100644 index 0000000000..87de4e59a7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/solid/src/routes/target.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/target')({ + component: TargetPage, +}) + +function TargetPage() { + return
target
+} diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/tsconfig.json b/benchmarks/client-nav/scenarios/control-flow/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/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/control-flow/solid/vite.config.ts b/benchmarks/client-nav/scenarios/control-flow/solid/vite.config.ts new file mode 100644 index 0000000000..f4fa916154 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/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 control-flow (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/project.json b/benchmarks/client-nav/scenarios/control-flow/vue/project.json new file mode 100644 index 0000000000..7370687988 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-control-flow-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/control-flow/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/setup.ts b/benchmarks/client-nav/scenarios/control-flow/vue/setup.ts new file mode 100644 index 0000000000..97b74b3892 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } 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, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts new file mode 100644 index 0000000000..8a019945c7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/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-control-flow', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-control-flow 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/control-flow/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/control-flow/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/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/control-flow/vue/src/main.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/main.tsx new file mode 100644 index 0000000000..cae9b54f1d --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/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/control-flow/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..6b53a6a203 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts @@ -0,0 +1,156 @@ +/* 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 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 IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const BrokenRoute = BrokenRouteImport.update({ + id: '/broken', + path: '/broken', + getParentRoute: () => rootRouteImport, +} as any) +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({ + id: '/missing/$id', + path: '/missing/$id', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/broken': typeof BrokenRoute + '/hop1': typeof Hop1Route + '/hop2': typeof Hop2Route + '/target': typeof TargetRoute + '/missing/$id': typeof MissingIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/broken': typeof BrokenRoute + '/hop1': typeof Hop1Route + '/hop2': typeof Hop2Route + '/target': typeof TargetRoute + '/missing/$id': typeof MissingIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/broken': typeof BrokenRoute + '/hop1': typeof Hop1Route + '/hop2': typeof Hop2Route + '/target': typeof TargetRoute + '/missing/$id': typeof MissingIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/broken' | '/hop1' | '/hop2' | '/target' | '/missing/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/broken' | '/hop1' | '/hop2' | '/target' | '/missing/$id' + id: + | '__root__' + | '/' + | '/broken' + | '/hop1' + | '/hop2' + | '/target' + | '/missing/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + BrokenRoute: typeof BrokenRoute + Hop1Route: typeof Hop1Route + Hop2Route: typeof Hop2Route + TargetRoute: typeof TargetRoute + MissingIdRoute: typeof MissingIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/broken': { + id: '/broken' + path: '/broken' + fullPath: '/broken' + preLoaderRoute: typeof BrokenRouteImport + parentRoute: typeof rootRouteImport + } + '/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': { + id: '/missing/$id' + path: '/missing/$id' + fullPath: '/missing/$id' + preLoaderRoute: typeof MissingIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + BrokenRoute: BrokenRoute, + Hop1Route: Hop1Route, + Hop2Route: Hop2Route, + TargetRoute: TargetRoute, + MissingIdRoute: MissingIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..9695c4b32d --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/__root.tsx @@ -0,0 +1,57 @@ +import * as Vue from 'vue' +import { + Link, + Outlet, + createRootRoute, + useLocation, +} from '@tanstack/vue-router' + +const LocationMarker = Vue.defineComponent({ + setup() { + const pathname = useLocation({ select: (location) => location.pathname }) + return () => {pathname.value} + }, +}) + +const RootComponent = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + + ) + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/broken.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/broken.tsx new file mode 100644 index 0000000000..c67fa2817e --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/broken.tsx @@ -0,0 +1,21 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { errorMessage } from '../../../shared' + +const BrokenError = Vue.defineComponent({ + props: { + error: { type: Error, required: true }, + }, + setup(props) { + return () =>
{props.error.message}
+ }, +}) + +export const Route = createFileRoute('/broken')({ + staleTime: 0, + gcTime: 0, + loader: () => { + throw new Error(errorMessage) + }, + errorComponent: BrokenError, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/hop1.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/hop1.tsx new file mode 100644 index 0000000000..ed00cefe3f --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/hop1.tsx @@ -0,0 +1,9 @@ +import { createFileRoute, redirect } from '@tanstack/vue-router' + +export const Route = createFileRoute('/hop1')({ + staleTime: 0, + gcTime: 0, + loader: () => { + throw redirect({ to: '/hop2' }) + }, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/hop2.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/hop2.tsx new file mode 100644 index 0000000000..f6d4b1c1e0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/hop2.tsx @@ -0,0 +1,9 @@ +import { createFileRoute, redirect } from '@tanstack/vue-router' + +export const Route = createFileRoute('/hop2')({ + staleTime: 0, + gcTime: 0, + loader: () => { + throw redirect({ to: '/target' }) + }, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/index.tsx new file mode 100644 index 0000000000..f3ffc58610 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/index.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const HomePage = Vue.defineComponent({ + setup() { + return () =>
home
+ }, +}) + +export const Route = createFileRoute('/')({ + component: HomePage, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/missing.$id.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/missing.$id.tsx new file mode 100644 index 0000000000..022ea656a6 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/missing.$id.tsx @@ -0,0 +1,28 @@ +import * as Vue from 'vue' +import { createFileRoute, notFound } from '@tanstack/vue-router' + +const MissingPage = Vue.defineComponent({ + setup() { + const data = Route.useLoaderData() + return () =>
{data.value.id}
+ }, +}) + +const MissingNotFound = Vue.defineComponent({ + setup() { + return () =>
missing not found
+ }, +}) + +export const Route = createFileRoute('/missing/$id')({ + staleTime: 0, + gcTime: 0, + loader: ({ params }) => { + if (params.id === 'gone') { + throw notFound() + } + return { id: params.id } + }, + component: MissingPage, + notFoundComponent: MissingNotFound, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/target.tsx b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/target.tsx new file mode 100644 index 0000000000..4e22d0993a --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/vue/src/routes/target.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const TargetPage = Vue.defineComponent({ + setup() { + return () =>
target
+ }, +}) + +export const Route = createFileRoute('/target')({ + component: TargetPage, +}) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/tsconfig.json b/benchmarks/client-nav/scenarios/control-flow/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/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/control-flow/vue/vite.config.ts b/benchmarks/client-nav/scenarios/control-flow/vue/vite.config.ts new file mode 100644 index 0000000000..3c2750d2a6 --- /dev/null +++ b/benchmarks/client-nav/scenarios/control-flow/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 control-flow (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/harness.ts b/benchmarks/client-nav/scenarios/harness.ts new file mode 100644 index 0000000000..cf3c39c7e6 --- /dev/null +++ b/benchmarks/client-nav/scenarios/harness.ts @@ -0,0 +1,534 @@ +import { + createBrowserHistory, + createMemoryHistory, + type RouterHistory, +} from '@tanstack/history' +import { JSDOM } from 'jsdom' +import { getRequiredLink, waitForRequiredLink } from '../setup-helpers' + +export interface ScenarioRouter { + load: () => Promise + subscribe: (eventType: 'onRendered', callback: () => void) => () => void + navigate: (options: any) => Promise + preloadRoute: (options: any) => Promise + invalidate: () => Promise + history: { + back: () => void + forward: () => void + go: (index: number) => void + } +} + +export interface MountedScenarioApp { + router: ScenarioRouter + unmount: () => void +} + +/** + * A single benchmark step. Plain strings are link-click steps (the common + * case). Steps that change the router location (`click`, `navigate`, `back`, + * `forward`, `go`) are awaited through the router's `onRendered` event; steps + * that do background work (`hover`, `preload`, `invalidate`) are awaited + * through a fixed number of 0ms timer hops so the loop stays deterministic. + */ +export type ScenarioStep = + | string + | { + type: 'click' + testId: string + /** + * Optional post-render settle predicate for steps that trigger work + * finishing after `onRendered` (e.g. deferred data resolving through a + * Suspense boundary). The step keeps taking 0ms timer hops until the + * predicate returns true (bounded, throws when exceeded). + */ + isSettled?: () => boolean + } + | { + /** + * Dispatches a single `mouseover` on the link, which triggers + * `preload: 'intent'` exactly once in every adapter: React synthesizes + * `mouseEnter` from `mouseover`, and Solid/Vue attach a native + * `mouseover` preload handler. (Solid/Vue also listen to `mouseenter` — + * dispatching both events would run the preload pipeline twice for them + * but only once for React.) Then settles via counted 0ms hops. + */ + type: 'hover' + testId: string + settleHops?: number + } + | { type: 'navigate'; getOptions: () => object } + | { type: 'preload'; getOptions: () => object; settleHops?: number } + | { type: 'invalidate'; settleHops?: number } + | { type: 'back' } + | { type: 'forward' } + | { type: 'go'; delta: number } + +/** + * One macrotask turn via `setImmediate` rather than `setTimeout(0)`: both + * yield deterministically to the event loop (timers, MessageChannel, React's + * Node scheduler), but a timer costs ~3-4 syscalls (timerfd + epoll) per hop + * while an immediate costs ~1. CodSpeed excludes syscall time from the + * measure — inconsistently past a threshold, which flagged the hop-heavy + * benches as "skipped" — so the loop must stay syscall-lean. + */ +const timerHop = () => + new Promise((resolve) => setImmediate(() => resolve())) + +async function settle(hops: number) { + for (let i = 0; i < hops; i++) { + await timerHop() + } +} + +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++) { + if (isSettled()) { + return + } + await timerHop() + } + throw new Error( + `Step "${label}" did not settle within ${MAX_SETTLE_HOPS} timer hops`, + ) +} + +/** + * Reroute zero-delay `window.setTimeout` calls onto `setImmediate` for the + * duration of the benchmark. jsdom delivers history traversals through two + * nested `window.setTimeout(0)` tasks; Node clamps those to 1ms of wall + * time, so with nothing else pending the event loop blocks in `epoll_wait` + * until each timer expires — and that blocked wall-time is recorded as + * highly variable syscall time (5-26ms across runs), enough for CodSpeed to + * skip-warn the history benches. Zero-delay timeouts carry no ordering + * semantics a check-phase immediate doesn't satisfy, and the suite's + * conventions already forbid real-delay timers in measured code; non-zero + * delays are passed through untouched. + */ +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 + + targetWindow.setTimeout = (( + handler: (...handlerArgs: Array) => void, + delay?: number, + ...args: Array + ) => { + if (!delay) { + const id = nextImmediateId-- + immediates.set( + id, + setImmediate(() => { + immediates.delete(id) + handler(...args) + }), + ) + return id + } + return originalSetTimeout(handler, delay, ...args) + }) as typeof targetWindow.setTimeout + + targetWindow.clearTimeout = ((id: number) => { + const immediate = immediates.get(id) + if (immediate) { + clearImmediate(immediate) + immediates.delete(id) + return + } + originalClearTimeout(id) + }) as typeof targetWindow.clearTimeout + + return () => { + 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, 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 + * consecutive location-changing steps may target the same location (a + * same-location click never triggers `onRendered`), and the sequence must + * leave the app back on the initial route so the warm-up lap ends in the + * starting state. + */ + steps: ReadonlyArray + /** Sanity check run once per step during the warm-up lap in `before()`. */ + assertAfterStep?: ( + stepIndex: number, + container: HTMLElement, + history: RouterHistory, + ) => void + /** + * 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) { + if (process.env.NODE_ENV !== 'production') { + console.warn( + `client-nav scenario benchmark is running without NODE_ENV=production; ${frameworkLabel} dev overhead will dominate results.`, + ) + } +} + +/** + * Shared scenario runner: mounts the prebuilt app, then advances a circular + * sequence of steps, synchronizing each step so its work is fully part of the + * measured tick and steps cannot overlap. + */ +export function createScenarioSetup(options: ScenarioSetupOptions) { + warnAboutDevMode(options.frameworkLabel) + + let container: HTMLDivElement | undefined = undefined + 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 + 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 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 = () => {} + unsub = router.subscribe('onRendered', () => { + resolveRendered() + }) + + const cachedLinks = new Map() + const rendered = () => + new Promise((resolveNext) => { + resolveRendered = resolveNext + }) + + const runStep = async (step: ScenarioStep) => { + if (typeof step === 'string') { + step = { type: 'click', testId: step } + } + + switch (step.type) { + case 'click': { + const renderedPromise = rendered() + getRequiredLink(container!, step.testId, cachedLinks).dispatchEvent( + new MouseEvent('click', { + bubbles: true, + cancelable: true, + button: 0, + }), + ) + await renderedPromise + if (step.isSettled) { + await settleUntil(step.isSettled, `click ${step.testId}`) + } + return + } + case 'hover': { + const link = getRequiredLink(container!, step.testId, cachedLinks) + link.dispatchEvent( + new MouseEvent('mouseover', { bubbles: true, cancelable: true }), + ) + await settle(step.settleHops ?? 4) + return + } + case 'navigate': { + const renderedPromise = rendered() + router.navigate(step.getOptions()) + await renderedPromise + return + } + case 'preload': { + await router.preloadRoute(step.getOptions()) + await settle(step.settleHops ?? 2) + return + } + case 'invalidate': { + await router.invalidate() + await settle(step.settleHops ?? 2) + return + } + case 'back': { + const renderedPromise = rendered() + router.history.back() + await renderedPromise + return + } + case 'forward': { + const renderedPromise = rendered() + router.history.forward() + await renderedPromise + return + } + case 'go': { + const renderedPromise = rendered() + router.history.go(step.delta) + await renderedPromise + return + } + } + } + + await router.load() + + const linkTestIds = new Set() + for (const step of options.steps) { + if (typeof step === 'string') { + linkTestIds.add(step) + } else if (step.type === 'click' || step.type === 'hover') { + linkTestIds.add(step.testId) + } + } + for (const testId of linkTestIds) { + await waitForRequiredLink(container, testId, cachedLinks) + } + + // One warm-up lap that also sanity-checks each step's observable output, + // 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, historyResource.history) + } + await finishBatch() + + next = () => { + const step = options.steps[stepIndex % options.steps.length]! + stepIndex += 1 + return runStep(step) + } + } + + function after() { + unmount?.() + container?.remove() + unsub() + cleanupScrollRestorationListeners() + restoreTimeouts() + historyResource?.dispose() + restoreTimeouts = () => {} + cleanupScrollRestorationListeners = () => {} + unmount = undefined + container = undefined + historyResource = undefined + } + + function tick() { + return next() + } + + return { + before, + tick, + finishBatch, + after, + } +} + +export interface MountLoopSetupOptions { + frameworkLabel: string + 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 +} + +/** + * Mount-loop runner for cold-start scenarios: every tick creates a fresh + * container, mounts the app (router creation included), waits for the initial + * render to commit, then unmounts and cleans up. + */ +export function createMountLoopSetup(options: MountLoopSetupOptions) { + warnAboutDevMode(options.frameworkLabel) + + async function tick() { + const container = document.createElement('div') + document.body.append(container) + const history = createMemoryHistory({ initialEntries: ['/'] }) + + const { router, unmount } = options.mount(container, history) + + try { + await router.load() + await settleUntil( + () => + container.querySelector(`[data-testid="${options.readyTestId}"]`) !== + null, + `mount ${options.readyTestId}`, + ) + options.assertReady?.(container) + } finally { + unmount() + history.destroy() + container.remove() + } + } + + return { + before: async () => {}, + tick, + finishBatch, + after: () => {}, + } +} diff --git a/benchmarks/client-nav/scenarios/head/react/project.json b/benchmarks/client-nav/scenarios/head/react/project.json new file mode 100644 index 0000000000..1becf30fb9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-head-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/head/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/head/react/setup.ts b/benchmarks/client-nav/scenarios/head/react/setup.ts new file mode 100644 index 0000000000..1a28b0ca94 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/react/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, stepTestIds } 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: stepTestIds, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/head/react/speed.bench.ts b/benchmarks/client-nav/scenarios/head/react/speed.bench.ts new file mode 100644 index 0000000000..d0d731a09f --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/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-head', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-head 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/head/react/speed.flame.ts b/benchmarks/client-nav/scenarios/head/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/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/head/react/src/main.tsx b/benchmarks/client-nav/scenarios/head/react/src/main.tsx new file mode 100644 index 0000000000..5febd6f795 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/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/head/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/head/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..88867d9190 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/react/src/routeTree.gen.ts @@ -0,0 +1,145 @@ +/* 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 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 IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const DocsRoute = DocsRouteImport.update({ + id: '/docs', + path: '/docs', + getParentRoute: () => rootRouteImport, +} as any) +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({ + id: '/$section', + path: '/$section', + getParentRoute: () => DocsRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/docs': typeof DocsRouteWithChildren + '/settings': typeof SettingsRoute + '/articles/$id': typeof ArticlesIdRoute + '/docs/$section': typeof DocsSectionRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/docs': typeof DocsRouteWithChildren + '/settings': typeof SettingsRoute + '/articles/$id': typeof ArticlesIdRoute + '/docs/$section': typeof DocsSectionRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/docs': typeof DocsRouteWithChildren + '/settings': typeof SettingsRoute + '/articles/$id': typeof ArticlesIdRoute + '/docs/$section': typeof DocsSectionRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/docs' | '/settings' | '/articles/$id' | '/docs/$section' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/docs' | '/settings' | '/articles/$id' | '/docs/$section' + id: + | '__root__' + | '/' + | '/docs' + | '/settings' + | '/articles/$id' + | '/docs/$section' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + DocsRoute: typeof DocsRouteWithChildren + SettingsRoute: typeof SettingsRoute + ArticlesIdRoute: typeof ArticlesIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/docs': { + id: '/docs' + path: '/docs' + fullPath: '/docs' + preLoaderRoute: typeof DocsRouteImport + parentRoute: typeof rootRouteImport + } + '/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': { + id: '/docs/$section' + path: '/$section' + fullPath: '/docs/$section' + preLoaderRoute: typeof DocsSectionRouteImport + parentRoute: typeof DocsRoute + } + } +} + +interface DocsRouteChildren { + DocsSectionRoute: typeof DocsSectionRoute +} + +const DocsRouteChildren: DocsRouteChildren = { + DocsSectionRoute: DocsSectionRoute, +} + +const DocsRouteWithChildren = DocsRoute._addFileChildren(DocsRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + DocsRoute: DocsRouteWithChildren, + SettingsRoute: SettingsRoute, + ArticlesIdRoute: ArticlesIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/head/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/head/react/src/routes/__root.tsx new file mode 100644 index 0000000000..3d61dad0e9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/react/src/routes/__root.tsx @@ -0,0 +1,59 @@ +import { + HeadContent, + Link, + Outlet, + createRootRoute, +} from '@tanstack/react-router' +import { articleIds, docsSections, rootHead } from '../../../shared' + +export const Route = createRootRoute({ + head: rootHead, + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/head/react/src/routes/articles.$id.tsx b/benchmarks/client-nav/scenarios/head/react/src/routes/articles.$id.tsx new file mode 100644 index 0000000000..6f5b78d60e --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/react/src/routes/articles.$id.tsx @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/react-router' +import { articleDescription, articleHead, articleTitle } from '../../../shared' + +export const Route = createFileRoute('/articles/$id')({ + head: ({ params }) => articleHead(params.id), + component: ArticlePage, +}) + +function ArticlePage() { + const params = Route.useParams() + + return ( +
+

{articleTitle(params.id)}

+

{articleDescription(params.id)}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/head/react/src/routes/docs.$section.tsx b/benchmarks/client-nav/scenarios/head/react/src/routes/docs.$section.tsx new file mode 100644 index 0000000000..6ed1935ada --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/react/src/routes/docs.$section.tsx @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/react-router' +import { docsDescription, docsSectionHead, docsTitle } from '../../../shared' + +export const Route = createFileRoute('/docs/$section')({ + head: ({ params }) => docsSectionHead(params.section), + component: DocsSectionPage, +}) + +function DocsSectionPage() { + const params = Route.useParams() + + return ( +
+

{docsTitle(params.section)}

+

{docsDescription(params.section)}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/head/react/src/routes/docs.tsx b/benchmarks/client-nav/scenarios/head/react/src/routes/docs.tsx new file mode 100644 index 0000000000..a2da216ddb --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/react/src/routes/docs.tsx @@ -0,0 +1,16 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { docsLayoutHead } from '../../../shared' + +export const Route = createFileRoute('/docs')({ + head: docsLayoutHead, + component: DocsLayout, +}) + +function DocsLayout() { + return ( +
+

Docs

+ +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/head/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/head/react/src/routes/index.tsx new file mode 100644 index 0000000000..6ac318452f --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/react/src/routes/index.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/react-router' +import { homeHead, homeTitle } from '../../../shared' + +export const Route = createFileRoute('/')({ + head: homeHead, + component: HomePage, +}) + +function HomePage() { + return ( +
+

{homeTitle}

+

Landing page

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/head/react/src/routes/settings.tsx b/benchmarks/client-nav/scenarios/head/react/src/routes/settings.tsx new file mode 100644 index 0000000000..cd73902bff --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/react/src/routes/settings.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/react-router' +import { settingsHead, settingsTitle } from '../../../shared' + +export const Route = createFileRoute('/settings')({ + head: settingsHead, + component: SettingsPage, +}) + +function SettingsPage() { + return ( +
+

{settingsTitle}

+

Account settings

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/head/react/tsconfig.json b/benchmarks/client-nav/scenarios/head/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/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/head/react/vite.config.ts b/benchmarks/client-nav/scenarios/head/react/vite.config.ts new file mode 100644 index 0000000000..7c8d6d4c15 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/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 head (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/head/shared.ts b/benchmarks/client-nav/scenarios/head/shared.ts new file mode 100644 index 0000000000..db185d602b --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/shared.ts @@ -0,0 +1,152 @@ +/** + * Shared definition of the `head` scenario: route head() payloads, the click + * sequence, and per-step sanity assertions. The three framework apps consume + * these builders so the workload is identical modulo the rendering layer. + */ + +const siteName = 'Head Bench' + +export const docsSections = ['api', 'guide', 'cli'] as const +export const articleIds = ['1', '2', '3'] as const + +export const homeTitle = `Home | ${siteName}` +export const settingsTitle = `Settings | ${siteName}` + +export function docsTitle(section: string) { + return `Docs ${section} | ${siteName}` +} + +export function docsDescription(section: string) { + return `Documentation for the ${section} section of the head benchmark app.` +} + +export function articleTitle(id: string) { + return `Article ${id} | ${siteName}` +} + +export function articleDescription(id: string) { + return `Long-form article number ${id}, with a description sized like a realistic summary of the page content.` +} + +export function rootHead() { + return { + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + { name: 'application-name', content: siteName }, + { name: 'description', content: 'Client head-management benchmark' }, + { name: 'theme-color', content: '#111827' }, + { property: 'og:type', content: 'website' }, + { property: 'og:site_name', content: siteName }, + ], + links: [ + { rel: 'icon', href: '/favicon.ico' }, + { rel: 'preconnect', href: 'https://assets.example.com' }, + ], + } +} + +export function homeHead() { + return { + meta: [ + { title: homeTitle }, + { name: 'description', content: 'Landing page of the head benchmark' }, + { property: 'og:title', content: homeTitle }, + ], + links: [{ rel: 'canonical', href: 'https://example.com/' }], + } +} + +export function docsLayoutHead() { + return { + meta: [ + // Overridden by the child section route on every docs navigation, so the + // dedupe path is exercised for both `name` and `property` entries. + { name: 'description', content: 'Documentation hub' }, + { property: 'og:title', content: `Docs | ${siteName}` }, + { name: 'docsearch:index', content: 'head-bench-docs' }, + ], + links: [{ rel: 'search', href: '/docs/opensearch.xml' }], + } +} + +export function docsSectionHead(section: string) { + return { + meta: [ + { title: docsTitle(section) }, + { name: 'description', content: docsDescription(section) }, + { name: 'keywords', content: `docs,${section},router,benchmark` }, + { property: 'og:title', content: docsTitle(section) }, + { property: 'og:description', content: docsDescription(section) }, + { property: 'og:url', content: `https://example.com/docs/${section}` }, + { name: 'twitter:card', content: 'summary' }, + { name: 'twitter:title', content: docsTitle(section) }, + ], + links: [ + { rel: 'canonical', href: `https://example.com/docs/${section}` }, + { rel: 'prev', href: `https://example.com/docs/${section}/intro` }, + ], + } +} + +export function articleHead(id: string) { + return { + meta: [ + { title: articleTitle(id) }, + { name: 'description', content: articleDescription(id) }, + { name: 'author', content: 'Bench Author' }, + { property: 'og:title', content: articleTitle(id) }, + { property: 'og:description', content: articleDescription(id) }, + { property: 'og:url', content: `https://example.com/articles/${id}` }, + { property: 'og:image', content: `https://example.com/covers/${id}.png` }, + { property: 'article:published_time', content: '2026-01-01T00:00:00Z' }, + { name: 'twitter:card', content: 'summary_large_image' }, + { name: 'twitter:title', content: articleTitle(id) }, + ], + links: [{ rel: 'canonical', href: `https://example.com/articles/${id}` }], + } +} + +export function settingsHead() { + return { + meta: [ + { title: settingsTitle }, + // Same names as root entries, so the child-wins dedupe path runs. + { name: 'description', content: 'Account settings' }, + { name: 'theme-color', content: '#f9fafb' }, + { name: 'robots', content: 'noindex' }, + ], + links: [], + } +} + +export const steps = [ + { testId: 'go-docs-api', title: docsTitle('api') }, + { testId: 'go-article-1', title: articleTitle('1') }, + { testId: 'go-docs-guide', title: docsTitle('guide') }, + { testId: 'go-settings', title: settingsTitle }, + { testId: 'go-article-2', title: articleTitle('2') }, + { testId: 'go-docs-cli', title: docsTitle('cli') }, + { testId: 'go-article-3', title: articleTitle('3') }, + { testId: 'go-home', title: homeTitle }, +] as const + +export const stepTestIds = steps.map((step) => step.testId) + +export function assertStepResult(stepIndex: number) { + const expected = steps[stepIndex]!.title + if (document.title !== expected) { + throw new Error( + `Expected document.title to be "${expected}" after step ${stepIndex}, received "${document.title}"`, + ) + } +} + +// Two laps through the 8-step sequence per benchmark iteration. +export const ticksPerIteration = 16 + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/head/solid/project.json b/benchmarks/client-nav/scenarios/head/solid/project.json new file mode 100644 index 0000000000..2575a19b89 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-head-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/head/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/head/solid/setup.ts b/benchmarks/client-nav/scenarios/head/solid/setup.ts new file mode 100644 index 0000000000..4ee924acff --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/solid/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, stepTestIds } 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: stepTestIds, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts new file mode 100644 index 0000000000..ca156c950b --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/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-head', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-head 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/head/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/head/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/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/head/solid/src/main.tsx b/benchmarks/client-nav/scenarios/head/solid/src/main.tsx new file mode 100644 index 0000000000..fa9d239418 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/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/head/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..b6f217e527 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts @@ -0,0 +1,145 @@ +/* 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 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 IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const DocsRoute = DocsRouteImport.update({ + id: '/docs', + path: '/docs', + getParentRoute: () => rootRouteImport, +} as any) +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({ + id: '/$section', + path: '/$section', + getParentRoute: () => DocsRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/docs': typeof DocsRouteWithChildren + '/settings': typeof SettingsRoute + '/articles/$id': typeof ArticlesIdRoute + '/docs/$section': typeof DocsSectionRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/docs': typeof DocsRouteWithChildren + '/settings': typeof SettingsRoute + '/articles/$id': typeof ArticlesIdRoute + '/docs/$section': typeof DocsSectionRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/docs': typeof DocsRouteWithChildren + '/settings': typeof SettingsRoute + '/articles/$id': typeof ArticlesIdRoute + '/docs/$section': typeof DocsSectionRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/docs' | '/settings' | '/articles/$id' | '/docs/$section' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/docs' | '/settings' | '/articles/$id' | '/docs/$section' + id: + | '__root__' + | '/' + | '/docs' + | '/settings' + | '/articles/$id' + | '/docs/$section' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + DocsRoute: typeof DocsRouteWithChildren + SettingsRoute: typeof SettingsRoute + ArticlesIdRoute: typeof ArticlesIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/docs': { + id: '/docs' + path: '/docs' + fullPath: '/docs' + preLoaderRoute: typeof DocsRouteImport + parentRoute: typeof rootRouteImport + } + '/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': { + id: '/docs/$section' + path: '/$section' + fullPath: '/docs/$section' + preLoaderRoute: typeof DocsSectionRouteImport + parentRoute: typeof DocsRoute + } + } +} + +interface DocsRouteChildren { + DocsSectionRoute: typeof DocsSectionRoute +} + +const DocsRouteChildren: DocsRouteChildren = { + DocsSectionRoute: DocsSectionRoute, +} + +const DocsRouteWithChildren = DocsRoute._addFileChildren(DocsRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + DocsRoute: DocsRouteWithChildren, + SettingsRoute: SettingsRoute, + ArticlesIdRoute: ArticlesIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/head/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/head/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..52ca7da373 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/solid/src/routes/__root.tsx @@ -0,0 +1,58 @@ +import { For } from 'solid-js' +import { + HeadContent, + Link, + Outlet, + createRootRoute, +} from '@tanstack/solid-router' +import { articleIds, docsSections, rootHead } from '../../../shared' + +export const Route = createRootRoute({ + head: rootHead, + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/head/solid/src/routes/articles.$id.tsx b/benchmarks/client-nav/scenarios/head/solid/src/routes/articles.$id.tsx new file mode 100644 index 0000000000..dab11ada18 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/solid/src/routes/articles.$id.tsx @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { articleDescription, articleHead, articleTitle } from '../../../shared' + +export const Route = createFileRoute('/articles/$id')({ + head: ({ params }) => articleHead(params.id), + component: ArticlePage, +}) + +function ArticlePage() { + const params = Route.useParams() + + return ( +
+

{articleTitle(params().id)}

+

{articleDescription(params().id)}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/head/solid/src/routes/docs.$section.tsx b/benchmarks/client-nav/scenarios/head/solid/src/routes/docs.$section.tsx new file mode 100644 index 0000000000..7ab1123e7a --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/solid/src/routes/docs.$section.tsx @@ -0,0 +1,18 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { docsDescription, docsSectionHead, docsTitle } from '../../../shared' + +export const Route = createFileRoute('/docs/$section')({ + head: ({ params }) => docsSectionHead(params.section), + component: DocsSectionPage, +}) + +function DocsSectionPage() { + const params = Route.useParams() + + return ( +
+

{docsTitle(params().section)}

+

{docsDescription(params().section)}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/head/solid/src/routes/docs.tsx b/benchmarks/client-nav/scenarios/head/solid/src/routes/docs.tsx new file mode 100644 index 0000000000..7f84b214d0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/solid/src/routes/docs.tsx @@ -0,0 +1,16 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { docsLayoutHead } from '../../../shared' + +export const Route = createFileRoute('/docs')({ + head: docsLayoutHead, + component: DocsLayout, +}) + +function DocsLayout() { + return ( +
+

Docs

+ +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/head/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/head/solid/src/routes/index.tsx new file mode 100644 index 0000000000..229eecc8c1 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/solid/src/routes/index.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { homeHead, homeTitle } from '../../../shared' + +export const Route = createFileRoute('/')({ + head: homeHead, + component: HomePage, +}) + +function HomePage() { + return ( +
+

{homeTitle}

+

Landing page

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/head/solid/src/routes/settings.tsx b/benchmarks/client-nav/scenarios/head/solid/src/routes/settings.tsx new file mode 100644 index 0000000000..88424caef3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/solid/src/routes/settings.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { settingsHead, settingsTitle } from '../../../shared' + +export const Route = createFileRoute('/settings')({ + head: settingsHead, + component: SettingsPage, +}) + +function SettingsPage() { + return ( +
+

{settingsTitle}

+

Account settings

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/head/solid/tsconfig.json b/benchmarks/client-nav/scenarios/head/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/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/head/solid/vite.config.ts b/benchmarks/client-nav/scenarios/head/solid/vite.config.ts new file mode 100644 index 0000000000..986b2de2b0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/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 head (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/head/vue/project.json b/benchmarks/client-nav/scenarios/head/vue/project.json new file mode 100644 index 0000000000..5ad7909d74 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-head-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/head/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/head/vue/setup.ts b/benchmarks/client-nav/scenarios/head/vue/setup.ts new file mode 100644 index 0000000000..3dd6bc95a5 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/vue/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, stepTestIds } 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: stepTestIds, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts new file mode 100644 index 0000000000..d188a9dd7a --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/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-head', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-head 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/head/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/head/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/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/head/vue/src/main.tsx b/benchmarks/client-nav/scenarios/head/vue/src/main.tsx new file mode 100644 index 0000000000..cae9b54f1d --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/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/head/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..161f99a65c --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts @@ -0,0 +1,145 @@ +/* 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 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 IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const DocsRoute = DocsRouteImport.update({ + id: '/docs', + path: '/docs', + getParentRoute: () => rootRouteImport, +} as any) +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({ + id: '/$section', + path: '/$section', + getParentRoute: () => DocsRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/docs': typeof DocsRouteWithChildren + '/settings': typeof SettingsRoute + '/articles/$id': typeof ArticlesIdRoute + '/docs/$section': typeof DocsSectionRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/docs': typeof DocsRouteWithChildren + '/settings': typeof SettingsRoute + '/articles/$id': typeof ArticlesIdRoute + '/docs/$section': typeof DocsSectionRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/docs': typeof DocsRouteWithChildren + '/settings': typeof SettingsRoute + '/articles/$id': typeof ArticlesIdRoute + '/docs/$section': typeof DocsSectionRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/docs' | '/settings' | '/articles/$id' | '/docs/$section' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/docs' | '/settings' | '/articles/$id' | '/docs/$section' + id: + | '__root__' + | '/' + | '/docs' + | '/settings' + | '/articles/$id' + | '/docs/$section' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + DocsRoute: typeof DocsRouteWithChildren + SettingsRoute: typeof SettingsRoute + ArticlesIdRoute: typeof ArticlesIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/docs': { + id: '/docs' + path: '/docs' + fullPath: '/docs' + preLoaderRoute: typeof DocsRouteImport + parentRoute: typeof rootRouteImport + } + '/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': { + id: '/docs/$section' + path: '/$section' + fullPath: '/docs/$section' + preLoaderRoute: typeof DocsSectionRouteImport + parentRoute: typeof DocsRoute + } + } +} + +interface DocsRouteChildren { + DocsSectionRoute: typeof DocsSectionRoute +} + +const DocsRouteChildren: DocsRouteChildren = { + DocsSectionRoute: DocsSectionRoute, +} + +const DocsRouteWithChildren = DocsRoute._addFileChildren(DocsRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + DocsRoute: DocsRouteWithChildren, + SettingsRoute: SettingsRoute, + ArticlesIdRoute: ArticlesIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/head/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/head/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..ad87699fef --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/vue/src/routes/__root.tsx @@ -0,0 +1,58 @@ +import * as Vue from 'vue' +import { + HeadContent, + Link, + Outlet, + createRootRoute, +} from '@tanstack/vue-router' +import { articleIds, docsSections, rootHead } from '../../../shared' + +const RootComponent = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + + ) + }, +}) + +export const Route = createRootRoute({ + head: rootHead, + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/head/vue/src/routes/articles.$id.tsx b/benchmarks/client-nav/scenarios/head/vue/src/routes/articles.$id.tsx new file mode 100644 index 0000000000..43a6fade58 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/vue/src/routes/articles.$id.tsx @@ -0,0 +1,21 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { articleDescription, articleHead, articleTitle } from '../../../shared' + +const ArticlePage = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
+

{articleTitle(params.value.id)}

+

{articleDescription(params.value.id)}

+
+ ) + }, +}) + +export const Route = createFileRoute('/articles/$id')({ + head: ({ params }) => articleHead(params.id), + component: ArticlePage, +}) diff --git a/benchmarks/client-nav/scenarios/head/vue/src/routes/docs.$section.tsx b/benchmarks/client-nav/scenarios/head/vue/src/routes/docs.$section.tsx new file mode 100644 index 0000000000..ebb59d61a2 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/vue/src/routes/docs.$section.tsx @@ -0,0 +1,21 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { docsDescription, docsSectionHead, docsTitle } from '../../../shared' + +const DocsSectionPage = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
+

{docsTitle(params.value.section)}

+

{docsDescription(params.value.section)}

+
+ ) + }, +}) + +export const Route = createFileRoute('/docs/$section')({ + head: ({ params }) => docsSectionHead(params.section), + component: DocsSectionPage, +}) diff --git a/benchmarks/client-nav/scenarios/head/vue/src/routes/docs.tsx b/benchmarks/client-nav/scenarios/head/vue/src/routes/docs.tsx new file mode 100644 index 0000000000..feabbc4d4a --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/vue/src/routes/docs.tsx @@ -0,0 +1,19 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { docsLayoutHead } from '../../../shared' + +const DocsLayout = Vue.defineComponent({ + setup() { + return () => ( +
+

Docs

+ +
+ ) + }, +}) + +export const Route = createFileRoute('/docs')({ + head: docsLayoutHead, + component: DocsLayout, +}) diff --git a/benchmarks/client-nav/scenarios/head/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/head/vue/src/routes/index.tsx new file mode 100644 index 0000000000..421478833f --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/vue/src/routes/index.tsx @@ -0,0 +1,19 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { homeHead, homeTitle } from '../../../shared' + +const HomePage = Vue.defineComponent({ + setup() { + return () => ( +
+

{homeTitle}

+

Landing page

+
+ ) + }, +}) + +export const Route = createFileRoute('/')({ + head: homeHead, + component: HomePage, +}) diff --git a/benchmarks/client-nav/scenarios/head/vue/src/routes/settings.tsx b/benchmarks/client-nav/scenarios/head/vue/src/routes/settings.tsx new file mode 100644 index 0000000000..1a519e16c2 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/vue/src/routes/settings.tsx @@ -0,0 +1,19 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { settingsHead, settingsTitle } from '../../../shared' + +const SettingsPage = Vue.defineComponent({ + setup() { + return () => ( +
+

{settingsTitle}

+

Account settings

+
+ ) + }, +}) + +export const Route = createFileRoute('/settings')({ + head: settingsHead, + component: SettingsPage, +}) diff --git a/benchmarks/client-nav/scenarios/head/vue/tsconfig.json b/benchmarks/client-nav/scenarios/head/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/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/head/vue/vite.config.ts b/benchmarks/client-nav/scenarios/head/vue/vite.config.ts new file mode 100644 index 0000000000..bb1126d85f --- /dev/null +++ b/benchmarks/client-nav/scenarios/head/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 head (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/history/react/project.json b/benchmarks/client-nav/scenarios/history/react/project.json new file mode 100644 index 0000000000..a2fe0001be --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-history-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/history/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/history/react/setup.ts b/benchmarks/client-nav/scenarios/history/react/setup.ts new file mode 100644 index 0000000000..c26b7ffd08 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/react/setup.ts @@ -0,0 +1,18 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } 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, + 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 new file mode 100644 index 0000000000..6ec7031857 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/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-history', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-history 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/history/react/speed.flame.ts b/benchmarks/client-nav/scenarios/history/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/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/history/react/src/main.tsx b/benchmarks/client-nav/scenarios/history/react/src/main.tsx new file mode 100644 index 0000000000..5febd6f795 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/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/history/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/history/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..21bb12ba35 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/react/src/routeTree.gen.ts @@ -0,0 +1,113 @@ +/* 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 GalleryRouteImport } from './routes/gallery' +import { Route as PagesNRouteImport } from './routes/pages.$n' +import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const GalleryRoute = GalleryRouteImport.update({ + id: '/gallery', + path: '/gallery', + getParentRoute: () => rootRouteImport, +} as any) +const PagesNRoute = PagesNRouteImport.update({ + id: '/pages/$n', + 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 + '/gallery': typeof GalleryRoute + '/pages/$n': typeof PagesNRoute + '/photos/$photoId': typeof PhotosPhotoIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/gallery': typeof GalleryRoute + '/pages/$n': typeof PagesNRoute + '/photos/$photoId': typeof PhotosPhotoIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/gallery': typeof GalleryRoute + '/pages/$n': typeof PagesNRoute + '/photos/$photoId': typeof PhotosPhotoIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' + id: '__root__' | '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + GalleryRoute: typeof GalleryRoute + PagesNRoute: typeof PagesNRoute + PhotosPhotoIdRoute: typeof PhotosPhotoIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/gallery': { + id: '/gallery' + path: '/gallery' + fullPath: '/gallery' + preLoaderRoute: typeof GalleryRouteImport + parentRoute: typeof rootRouteImport + } + '/pages/$n': { + id: '/pages/$n' + path: '/pages/$n' + fullPath: '/pages/$n' + preLoaderRoute: typeof PagesNRouteImport + parentRoute: typeof rootRouteImport + } + '/photos/$photoId': { + id: '/photos/$photoId' + path: '/photos/$photoId' + fullPath: '/photos/$photoId' + preLoaderRoute: typeof PhotosPhotoIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + GalleryRoute: GalleryRoute, + PagesNRoute: PagesNRoute, + PhotosPhotoIdRoute: PhotosPhotoIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/history/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/history/react/src/routes/__root.tsx new file mode 100644 index 0000000000..240d8719d4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/react/src/routes/__root.tsx @@ -0,0 +1,66 @@ +import { + Link, + Outlet, + createRootRoute, + useBlocker, + useCanGoBack, + useLocation, +} from '@tanstack/react-router' +import { maskedPhotoId, shouldBlockFn } from '../../../shared' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + const pathname = useLocation({ select: (location) => location.pathname }) + const canGoBack = useCanGoBack() + + useBlocker({ shouldBlockFn }) + + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/history/react/src/routes/gallery.tsx b/benchmarks/client-nav/scenarios/history/react/src/routes/gallery.tsx new file mode 100644 index 0000000000..55094556a6 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/react/src/routes/gallery.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/gallery')({ + component: GalleryPage, +}) + +function GalleryPage() { + return ( +
+

Gallery

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/history/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/history/react/src/routes/index.tsx new file mode 100644 index 0000000000..932a72f2ef --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/react/src/routes/index.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return ( +
+

Home

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/history/react/src/routes/pages.$n.tsx b/benchmarks/client-nav/scenarios/history/react/src/routes/pages.$n.tsx new file mode 100644 index 0000000000..b9c5e2f8d0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/react/src/routes/pages.$n.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/react-router' +import { pageLabel } from '../../../shared' + +export const Route = createFileRoute('/pages/$n')({ + component: PageComponent, +}) + +function PageComponent() { + const params = Route.useParams() + + return ( +
+

{pageLabel(params.n)}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/history/react/src/routes/photos.$photoId.tsx b/benchmarks/client-nav/scenarios/history/react/src/routes/photos.$photoId.tsx new file mode 100644 index 0000000000..793b531c89 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/react/src/routes/photos.$photoId.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/react-router' +import { photoLabel } from '../../../shared' + +export const Route = createFileRoute('/photos/$photoId')({ + component: PhotoComponent, +}) + +function PhotoComponent() { + const params = Route.useParams() + + return ( +
+

{photoLabel(params.photoId)}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/history/react/tsconfig.json b/benchmarks/client-nav/scenarios/history/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/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/history/react/vite.config.ts b/benchmarks/client-nav/scenarios/history/react/vite.config.ts new file mode 100644 index 0000000000..bdbde9c668 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/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 history (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/history/shared.ts b/benchmarks/client-nav/scenarios/history/shared.ts new file mode 100644 index 0000000000..be6096cea8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/shared.ts @@ -0,0 +1,94 @@ +/** + * Shared definition of the `history` scenario: push/replace/back/forward + * traversal, location masking, blocker registration overhead (the blocker + * never blocks), and useLocation/useCanGoBack subscriptions. + * + * The step lap is designed to keep the history depth stationary: it ends back + * on the initial entry, so the first push of the next lap truncates the stale + * 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' + +export function pageLabel(n: string) { + return `Page ${n}` +} + +export function photoLabel(id: string) { + return `Photo ${id}` +} + +/** Registered on every navigation, never blocks. */ +export const shouldBlockFn = () => false + +interface HistoryStepExpectation { + step: ScenarioStep + /** Expected router location pathname (the REAL location, even when masked). */ + pathname: string + /** 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 +} + +export const stepExpectations: ReadonlyArray = [ + { step: 'p-1', pathname: '/pages/1', marker: 'page-state' }, + { step: 'p-2', pathname: '/pages/2', marker: 'page-state' }, + { + step: 'photo-masked', + pathname: `/photos/${maskedPhotoId}`, + windowPathname: '/gallery', + marker: 'photo-state', + }, + { step: { type: 'back' }, pathname: '/pages/2', marker: 'page-state' }, + { step: { type: 'back' }, pathname: '/pages/1', marker: 'page-state' }, + { step: { type: 'forward' }, pathname: '/pages/2', marker: 'page-state' }, + { step: 'p-3-replace', pathname: '/pages/3', marker: 'page-state' }, + { step: { type: 'back' }, pathname: '/pages/1', marker: 'page-state' }, + { step: { type: 'back' }, pathname: '/', marker: 'home-state' }, +] + +export const steps = stepExpectations.map((expectation) => expectation.step) + +export function assertStepResult( + stepIndex: number, + container: HTMLElement, + history: RouterHistory, +) { + const expected = stepExpectations[stepIndex]! + + const loc = container.querySelector('[data-testid="loc"]')?.textContent + if (loc !== expected.pathname) { + throw new Error( + `Expected location marker to be "${expected.pathname}" after step ${stepIndex}, received "${loc}"`, + ) + } + + const windowPathname = expected.windowPathname ?? expected.pathname + if (history.location.pathname !== windowPathname) { + throw new Error( + `Expected history.location.pathname to be "${windowPathname}" after step ${stepIndex}, received "${history.location.pathname}"`, + ) + } + + if ( + expected.marker && + !container.querySelector(`[data-testid="${expected.marker}"]`) + ) { + throw new Error( + `Expected marker "${expected.marker}" to be rendered after step ${stepIndex}`, + ) + } +} + +// Two laps through the 9-step sequence per benchmark iteration. +export const ticksPerIteration = 18 + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/history/solid/project.json b/benchmarks/client-nav/scenarios/history/solid/project.json new file mode 100644 index 0000000000..6f4bba1ca5 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-history-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/history/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/history/solid/setup.ts b/benchmarks/client-nav/scenarios/history/solid/setup.ts new file mode 100644 index 0000000000..4adf55d6df --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/solid/setup.ts @@ -0,0 +1,18 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } 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, + 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 new file mode 100644 index 0000000000..56af035b2b --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/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-history', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-history 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/history/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/history/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/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/history/solid/src/main.tsx b/benchmarks/client-nav/scenarios/history/solid/src/main.tsx new file mode 100644 index 0000000000..fa9d239418 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/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/history/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..af253f4a15 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts @@ -0,0 +1,113 @@ +/* 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 GalleryRouteImport } from './routes/gallery' +import { Route as PagesNRouteImport } from './routes/pages.$n' +import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const GalleryRoute = GalleryRouteImport.update({ + id: '/gallery', + path: '/gallery', + getParentRoute: () => rootRouteImport, +} as any) +const PagesNRoute = PagesNRouteImport.update({ + id: '/pages/$n', + 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 + '/gallery': typeof GalleryRoute + '/pages/$n': typeof PagesNRoute + '/photos/$photoId': typeof PhotosPhotoIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/gallery': typeof GalleryRoute + '/pages/$n': typeof PagesNRoute + '/photos/$photoId': typeof PhotosPhotoIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/gallery': typeof GalleryRoute + '/pages/$n': typeof PagesNRoute + '/photos/$photoId': typeof PhotosPhotoIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' + id: '__root__' | '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + GalleryRoute: typeof GalleryRoute + PagesNRoute: typeof PagesNRoute + PhotosPhotoIdRoute: typeof PhotosPhotoIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/gallery': { + id: '/gallery' + path: '/gallery' + fullPath: '/gallery' + preLoaderRoute: typeof GalleryRouteImport + parentRoute: typeof rootRouteImport + } + '/pages/$n': { + id: '/pages/$n' + path: '/pages/$n' + fullPath: '/pages/$n' + preLoaderRoute: typeof PagesNRouteImport + parentRoute: typeof rootRouteImport + } + '/photos/$photoId': { + id: '/photos/$photoId' + path: '/photos/$photoId' + fullPath: '/photos/$photoId' + preLoaderRoute: typeof PhotosPhotoIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + GalleryRoute: GalleryRoute, + PagesNRoute: PagesNRoute, + PhotosPhotoIdRoute: PhotosPhotoIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/history/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/history/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..edf7368929 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/solid/src/routes/__root.tsx @@ -0,0 +1,66 @@ +import { + Link, + Outlet, + createRootRoute, + useBlocker, + useCanGoBack, + useLocation, +} from '@tanstack/solid-router' +import { maskedPhotoId, shouldBlockFn } from '../../../shared' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + const pathname = useLocation({ select: (location) => location.pathname }) + const canGoBack = useCanGoBack() + + useBlocker({ shouldBlockFn }) + + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/history/solid/src/routes/gallery.tsx b/benchmarks/client-nav/scenarios/history/solid/src/routes/gallery.tsx new file mode 100644 index 0000000000..b72d1c6195 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/solid/src/routes/gallery.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/gallery')({ + component: GalleryPage, +}) + +function GalleryPage() { + return ( +
+

Gallery

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/history/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/history/solid/src/routes/index.tsx new file mode 100644 index 0000000000..44a0b8045a --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/solid/src/routes/index.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return ( +
+

Home

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/history/solid/src/routes/pages.$n.tsx b/benchmarks/client-nav/scenarios/history/solid/src/routes/pages.$n.tsx new file mode 100644 index 0000000000..1def6674c6 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/solid/src/routes/pages.$n.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { pageLabel } from '../../../shared' + +export const Route = createFileRoute('/pages/$n')({ + component: PageComponent, +}) + +function PageComponent() { + const params = Route.useParams() + + return ( +
+

{pageLabel(params().n)}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/history/solid/src/routes/photos.$photoId.tsx b/benchmarks/client-nav/scenarios/history/solid/src/routes/photos.$photoId.tsx new file mode 100644 index 0000000000..ab2fe06e3f --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/solid/src/routes/photos.$photoId.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { photoLabel } from '../../../shared' + +export const Route = createFileRoute('/photos/$photoId')({ + component: PhotoComponent, +}) + +function PhotoComponent() { + const params = Route.useParams() + + return ( +
+

{photoLabel(params().photoId)}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/history/solid/tsconfig.json b/benchmarks/client-nav/scenarios/history/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/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/history/solid/vite.config.ts b/benchmarks/client-nav/scenarios/history/solid/vite.config.ts new file mode 100644 index 0000000000..4da589ff0e --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/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 history (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/history/vue/project.json b/benchmarks/client-nav/scenarios/history/vue/project.json new file mode 100644 index 0000000000..17fca887ca --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-history-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/history/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/history/vue/setup.ts b/benchmarks/client-nav/scenarios/history/vue/setup.ts new file mode 100644 index 0000000000..df689964e4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/vue/setup.ts @@ -0,0 +1,18 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } 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, + 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 new file mode 100644 index 0000000000..3d36ac4cfa --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/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-history', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-history 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/history/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/history/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/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/history/vue/src/main.tsx b/benchmarks/client-nav/scenarios/history/vue/src/main.tsx new file mode 100644 index 0000000000..cae9b54f1d --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/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/history/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..519aef7c8f --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts @@ -0,0 +1,113 @@ +/* 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 GalleryRouteImport } from './routes/gallery' +import { Route as PagesNRouteImport } from './routes/pages.$n' +import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const GalleryRoute = GalleryRouteImport.update({ + id: '/gallery', + path: '/gallery', + getParentRoute: () => rootRouteImport, +} as any) +const PagesNRoute = PagesNRouteImport.update({ + id: '/pages/$n', + 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 + '/gallery': typeof GalleryRoute + '/pages/$n': typeof PagesNRoute + '/photos/$photoId': typeof PhotosPhotoIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/gallery': typeof GalleryRoute + '/pages/$n': typeof PagesNRoute + '/photos/$photoId': typeof PhotosPhotoIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/gallery': typeof GalleryRoute + '/pages/$n': typeof PagesNRoute + '/photos/$photoId': typeof PhotosPhotoIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' + id: '__root__' | '/' | '/gallery' | '/pages/$n' | '/photos/$photoId' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + GalleryRoute: typeof GalleryRoute + PagesNRoute: typeof PagesNRoute + PhotosPhotoIdRoute: typeof PhotosPhotoIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/gallery': { + id: '/gallery' + path: '/gallery' + fullPath: '/gallery' + preLoaderRoute: typeof GalleryRouteImport + parentRoute: typeof rootRouteImport + } + '/pages/$n': { + id: '/pages/$n' + path: '/pages/$n' + fullPath: '/pages/$n' + preLoaderRoute: typeof PagesNRouteImport + parentRoute: typeof rootRouteImport + } + '/photos/$photoId': { + id: '/photos/$photoId' + path: '/photos/$photoId' + fullPath: '/photos/$photoId' + preLoaderRoute: typeof PhotosPhotoIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + GalleryRoute: GalleryRoute, + PagesNRoute: PagesNRoute, + PhotosPhotoIdRoute: PhotosPhotoIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/history/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/history/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..7f7dff159c --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/vue/src/routes/__root.tsx @@ -0,0 +1,69 @@ +import * as Vue from 'vue' +import { + Link, + Outlet, + createRootRoute, + useBlocker, + useCanGoBack, + useLocation, +} from '@tanstack/vue-router' +import { maskedPhotoId, shouldBlockFn } from '../../../shared' + +const RootComponent = Vue.defineComponent({ + setup() { + const pathname = useLocation({ select: (location) => location.pathname }) + const canGoBack = useCanGoBack() + + useBlocker({ shouldBlockFn }) + + return () => ( + <> + + + + ) + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/history/vue/src/routes/gallery.tsx b/benchmarks/client-nav/scenarios/history/vue/src/routes/gallery.tsx new file mode 100644 index 0000000000..3a397b1843 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/vue/src/routes/gallery.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const GalleryPage = Vue.defineComponent({ + setup() { + return () => ( +
+

Gallery

+
+ ) + }, +}) + +export const Route = createFileRoute('/gallery')({ + component: GalleryPage, +}) diff --git a/benchmarks/client-nav/scenarios/history/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/history/vue/src/routes/index.tsx new file mode 100644 index 0000000000..fbc5b957a7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/vue/src/routes/index.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const HomePage = Vue.defineComponent({ + setup() { + return () => ( +
+

Home

+
+ ) + }, +}) + +export const Route = createFileRoute('/')({ + component: HomePage, +}) diff --git a/benchmarks/client-nav/scenarios/history/vue/src/routes/pages.$n.tsx b/benchmarks/client-nav/scenarios/history/vue/src/routes/pages.$n.tsx new file mode 100644 index 0000000000..560e83ed29 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/vue/src/routes/pages.$n.tsx @@ -0,0 +1,19 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { pageLabel } from '../../../shared' + +const PageComponent = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
+

{pageLabel(params.value.n)}

+
+ ) + }, +}) + +export const Route = createFileRoute('/pages/$n')({ + component: PageComponent, +}) diff --git a/benchmarks/client-nav/scenarios/history/vue/src/routes/photos.$photoId.tsx b/benchmarks/client-nav/scenarios/history/vue/src/routes/photos.$photoId.tsx new file mode 100644 index 0000000000..186566fe72 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/vue/src/routes/photos.$photoId.tsx @@ -0,0 +1,19 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { photoLabel } from '../../../shared' + +const PhotoComponent = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
+

{photoLabel(params.value.photoId)}

+
+ ) + }, +}) + +export const Route = createFileRoute('/photos/$photoId')({ + component: PhotoComponent, +}) diff --git a/benchmarks/client-nav/scenarios/history/vue/tsconfig.json b/benchmarks/client-nav/scenarios/history/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/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/history/vue/vite.config.ts b/benchmarks/client-nav/scenarios/history/vue/vite.config.ts new file mode 100644 index 0000000000..c5f1ca9807 --- /dev/null +++ b/benchmarks/client-nav/scenarios/history/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 history (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) 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/project.json b/benchmarks/client-nav/scenarios/links/react/project.json new file mode 100644 index 0000000000..52c9df8a68 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-links-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/links/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/links/react/setup.ts b/benchmarks/client-nav/scenarios/links/react/setup.ts new file mode 100644 index 0000000000..5409df903c --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/react/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, 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, + }) +} diff --git a/benchmarks/client-nav/scenarios/links/react/speed.bench.ts b/benchmarks/client-nav/scenarios/links/react/speed.bench.ts new file mode 100644 index 0000000000..75f5f725d4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/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-links', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-links 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/links/react/speed.flame.ts b/benchmarks/client-nav/scenarios/links/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/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/links/react/src/main.tsx b/benchmarks/client-nav/scenarios/links/react/src/main.tsx new file mode 100644 index 0000000000..5febd6f795 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/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/links/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/links/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..6e0c29ca88 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/react/src/routeTree.gen.ts @@ -0,0 +1,95 @@ +/* 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 AboutRouteImport } from './routes/about' +import { Route as ItemsIdRouteImport } from './routes/items.$id' + +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', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/about' | '/items/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/about' | '/items/$id' + id: '__root__' | '/' | '/about' | '/items/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + AboutRoute: typeof AboutRoute + ItemsIdRoute: typeof ItemsIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + 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' + fullPath: '/items/$id' + preLoaderRoute: typeof ItemsIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + AboutRoute: AboutRoute, + ItemsIdRoute: ItemsIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/links/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/links/react/src/routes/__root.tsx new file mode 100644 index 0000000000..7a48510e8a --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/react/src/routes/__root.tsx @@ -0,0 +1,104 @@ +import { + Link, + Outlet, + createRootRoute, + useMatchRoute, +} from '@tanstack/react-router' +import { + itemIds, + matchProbeIds, + stepItemIds, + variantSearch, +} from '../../../shared' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function StatusPanel() { + const matchRoute = useMatchRoute() + + return ( + + ) +} + +function LinkGrid() { + return ( +
+ {itemIds.map((id) => ( +
+ + {`Item ${id}`} + + + {`Item ${id} exact`} + + + {`Item ${id} search`} + + + {`Item ${id} hash`} + + + {({ isActive }) => (isActive ? `Item ${id} on` : `Item ${id} off`)} + +
+ ))} +
+ ) +} + +function RootComponent() { + return ( + <> + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/links/react/src/routes/about.tsx b/benchmarks/client-nav/scenarios/links/react/src/routes/about.tsx new file mode 100644 index 0000000000..0e4afc9297 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/react/src/routes/about.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/react-router' +import { aboutMarker } from '../../../shared' + +export const Route = createFileRoute('/about')({ + component: AboutPage, +}) + +function AboutPage() { + return ( +
+

{aboutMarker}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/links/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/links/react/src/routes/index.tsx new file mode 100644 index 0000000000..2b8c83ebab --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/react/src/routes/index.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/react-router' +import { homeMarker } from '../../../shared' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return ( +
+

{homeMarker}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/links/react/src/routes/items.$id.tsx b/benchmarks/client-nav/scenarios/links/react/src/routes/items.$id.tsx new file mode 100644 index 0000000000..23121edb5c --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/react/src/routes/items.$id.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/react-router' +import { itemMarker } from '../../../shared' + +export const Route = createFileRoute('/items/$id')({ + component: ItemPage, +}) + +function ItemPage() { + const params = Route.useParams() + + return ( +
+

{itemMarker(params.id)}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/links/react/tsconfig.json b/benchmarks/client-nav/scenarios/links/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/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/links/react/vite.config.ts b/benchmarks/client-nav/scenarios/links/react/vite.config.ts new file mode 100644 index 0000000000..69de10b5b7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/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 links (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/links/shared.ts b/benchmarks/client-nav/scenarios/links/shared.ts new file mode 100644 index 0000000000..6e75ea045c --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/shared.ts @@ -0,0 +1,133 @@ +/** + * Shared definition of the `links` scenario: a large persistent grid of + * ``s in the root layout so every navigation recomputes link props and + * active state across many activeOptions variants, plus `useMatchRoute` / + * `MatchRoute` consumers. The three framework apps consume these constants so + * the workload is identical modulo the rendering layer. + */ +import type { ScenarioStep } from '../harness' + +// 40 item ids x 5 link variants = 200 links mounted in the root layout. +export const LINK_ITEM_COUNT = 40 +export const LINK_VARIANT_COUNT = 5 + +export const itemIds = Array.from({ length: LINK_ITEM_COUNT }, (_, index) => + String(index + 1), +) + +// Static search object attached to the includeSearch:false variant. +export const variantSearch = { tab: 'specs', page: 2 } + +// Item ids that get a `go-item-` test id on their plain variant link. +export const stepItemIds = ['1', '7', '13', '25', '40'] + +// Ids probed by the useMatchRoute checks in the root StatusPanel. +export const matchProbeIds = [ + '1', + '5', + '7', + '13', + '20', + '25', + '30', + '35', + '40', + '2', +] + +export function itemMarker(id: string) { + return `item-${id}` +} + +export const homeMarker = 'home' +export const aboutMarker = 'about' + +interface StepDef { + testId: string + marker: string + /** Expected number of `.active-link` elements after the step. */ + activeCount: number + /** When one link is active, its href must include this substring. */ + activeHrefPart?: string +} + +export const stepDefs: ReadonlyArray = [ + { + testId: 'go-item-1', + marker: itemMarker('1'), + activeCount: 1, + activeHrefPart: '/items/1', + }, + { + testId: 'go-item-7', + marker: itemMarker('7'), + activeCount: 1, + activeHrefPart: '/items/7', + }, + { testId: 'go-about', marker: aboutMarker, activeCount: 0 }, + { + testId: 'go-item-13', + marker: itemMarker('13'), + activeCount: 1, + activeHrefPart: '/items/13', + }, + { + testId: 'go-item-25', + marker: itemMarker('25'), + activeCount: 1, + activeHrefPart: '/items/25', + }, + { + testId: 'go-item-40', + marker: itemMarker('40'), + activeCount: 1, + activeHrefPart: '/items/40', + }, + { + testId: 'go-item-7', + marker: itemMarker('7'), + activeCount: 1, + activeHrefPart: '/items/7', + }, + { testId: 'go-home', marker: homeMarker, activeCount: 0 }, +] + +export const scenarioSteps: ReadonlyArray = stepDefs.map( + (step) => step.testId, +) + +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}`, + ) + } + if (step.activeHrefPart) { + const href = activeLinks[0]!.getAttribute('href') ?? '' + if (!href.includes(step.activeHrefPart)) { + throw new Error( + `Expected the active link href to include "${step.activeHrefPart}" after step ${stepIndex}, received "${href}"`, + ) + } + } +} + +// One lap through the 8-step sequence per benchmark iteration; each step +// recomputes all 200 links plus the match probes. +export const ticksPerIteration = 8 + +export const benchOptions = { + warmupIterations: 50, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/links/solid/project.json b/benchmarks/client-nav/scenarios/links/solid/project.json new file mode 100644 index 0000000000..ef1dab4c50 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-links-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/links/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/links/solid/setup.ts b/benchmarks/client-nav/scenarios/links/solid/setup.ts new file mode 100644 index 0000000000..34270fe8a4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/solid/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, 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, + }) +} diff --git a/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts new file mode 100644 index 0000000000..fc7f3e71e7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/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-links', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-links 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/links/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/links/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/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/links/solid/src/main.tsx b/benchmarks/client-nav/scenarios/links/solid/src/main.tsx new file mode 100644 index 0000000000..fa9d239418 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/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/links/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..0da70513e8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts @@ -0,0 +1,95 @@ +/* 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 AboutRouteImport } from './routes/about' +import { Route as ItemsIdRouteImport } from './routes/items.$id' + +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', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/about' | '/items/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/about' | '/items/$id' + id: '__root__' | '/' | '/about' | '/items/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + AboutRoute: typeof AboutRoute + ItemsIdRoute: typeof ItemsIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + 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' + fullPath: '/items/$id' + preLoaderRoute: typeof ItemsIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + AboutRoute: AboutRoute, + ItemsIdRoute: ItemsIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/links/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/links/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..a889a26854 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/solid/src/routes/__root.tsx @@ -0,0 +1,119 @@ +import { For } from 'solid-js' +import { + Link, + Outlet, + createRootRoute, + useMatchRoute, +} from '@tanstack/solid-router' +import { + itemIds, + matchProbeIds, + stepItemIds, + variantSearch, +} from '../../../shared' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function StatusPanel() { + const matchRoute = useMatchRoute() + + return ( + + ) +} + +function LinkGrid() { + return ( +
+ + {(id) => ( +
+ + {`Item ${id}`} + + + {`Item ${id} exact`} + + + {`Item ${id} search`} + + + {`Item ${id} hash`} + + + {({ isActive }) => + isActive ? `Item ${id} on` : `Item ${id} off` + } + +
+ )} +
+
+ ) +} + +function RootComponent() { + return ( + <> + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/links/solid/src/routes/about.tsx b/benchmarks/client-nav/scenarios/links/solid/src/routes/about.tsx new file mode 100644 index 0000000000..a2a71678b7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/solid/src/routes/about.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { aboutMarker } from '../../../shared' + +export const Route = createFileRoute('/about')({ + component: AboutPage, +}) + +function AboutPage() { + return ( +
+

{aboutMarker}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/links/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/links/solid/src/routes/index.tsx new file mode 100644 index 0000000000..72fbfe387a --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/solid/src/routes/index.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { homeMarker } from '../../../shared' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return ( +
+

{homeMarker}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/links/solid/src/routes/items.$id.tsx b/benchmarks/client-nav/scenarios/links/solid/src/routes/items.$id.tsx new file mode 100644 index 0000000000..64d84f81f4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/solid/src/routes/items.$id.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { itemMarker } from '../../../shared' + +export const Route = createFileRoute('/items/$id')({ + component: ItemPage, +}) + +function ItemPage() { + const params = Route.useParams() + + return ( +
+

{itemMarker(params().id)}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/links/solid/tsconfig.json b/benchmarks/client-nav/scenarios/links/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/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/links/solid/vite.config.ts b/benchmarks/client-nav/scenarios/links/solid/vite.config.ts new file mode 100644 index 0000000000..e37342ffc3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/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 links (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/links/vue/project.json b/benchmarks/client-nav/scenarios/links/vue/project.json new file mode 100644 index 0000000000..fe1e68fad3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-links-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/links/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/links/vue/setup.ts b/benchmarks/client-nav/scenarios/links/vue/setup.ts new file mode 100644 index 0000000000..f70a154909 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/vue/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, 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, + }) +} diff --git a/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts new file mode 100644 index 0000000000..2ace7a8409 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/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-links', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-links 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/links/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/links/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/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/links/vue/src/main.tsx b/benchmarks/client-nav/scenarios/links/vue/src/main.tsx new file mode 100644 index 0000000000..cae9b54f1d --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/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/links/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..7d2b1e9bbb --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts @@ -0,0 +1,95 @@ +/* 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 AboutRouteImport } from './routes/about' +import { Route as ItemsIdRouteImport } from './routes/items.$id' + +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', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/items/$id': typeof ItemsIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/about' | '/items/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/about' | '/items/$id' + id: '__root__' | '/' | '/about' | '/items/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + AboutRoute: typeof AboutRoute + ItemsIdRoute: typeof ItemsIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + 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' + fullPath: '/items/$id' + preLoaderRoute: typeof ItemsIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + AboutRoute: AboutRoute, + ItemsIdRoute: ItemsIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/links/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/links/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..04f99677fd --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/vue/src/routes/__root.tsx @@ -0,0 +1,120 @@ +import * as Vue from 'vue' +import { + Link, + Outlet, + createRootRoute, + useMatchRoute, +} from '@tanstack/vue-router' +import { + itemIds, + matchProbeIds, + stepItemIds, + variantSearch, +} from '../../../shared' + +const StatusPanel = Vue.defineComponent({ + setup() { + const matchRoute = useMatchRoute() + const probes = matchProbeIds.map((id) => ({ + id, + match: matchRoute({ to: '/items/$id', params: { id } }), + })) + // Static probes use the setup-scoped matchRoute instead of : + // vue-router's MatchRoute creates an undisposed watcher per render (one + // leaked subscription per navigation), so all three apps use + // useMatchRoute for cross-framework parity. + const atHome = matchRoute({ to: '/' }) + const atAbout = matchRoute({ to: '/about' }) + const underRoot = matchRoute({ to: '/', fuzzy: true }) + const underAbout = matchRoute({ to: '/about', fuzzy: true }) + const aboutSearch = matchRoute({ to: '/about', includeSearch: true }) + + return () => ( + + ) + }, +}) + +const LinkGrid = Vue.defineComponent({ + setup() { + return () => ( +
+ {itemIds.map((id) => ( +
+ + {`Item ${id}`} + + + {`Item ${id} exact`} + + + {`Item ${id} search`} + + + {`Item ${id} hash`} + + + {({ isActive }: { isActive: boolean }) => + isActive ? `Item ${id} on` : `Item ${id} off` + } + +
+ ))} +
+ ) + }, +}) + +const RootComponent = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + + + ) + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/links/vue/src/routes/about.tsx b/benchmarks/client-nav/scenarios/links/vue/src/routes/about.tsx new file mode 100644 index 0000000000..5cc1473bff --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/vue/src/routes/about.tsx @@ -0,0 +1,17 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { aboutMarker } from '../../../shared' + +const AboutPage = Vue.defineComponent({ + setup() { + return () => ( +
+

{aboutMarker}

+
+ ) + }, +}) + +export const Route = createFileRoute('/about')({ + component: AboutPage, +}) diff --git a/benchmarks/client-nav/scenarios/links/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/links/vue/src/routes/index.tsx new file mode 100644 index 0000000000..f04a9f5796 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/vue/src/routes/index.tsx @@ -0,0 +1,17 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { homeMarker } from '../../../shared' + +const HomePage = Vue.defineComponent({ + setup() { + return () => ( +
+

{homeMarker}

+
+ ) + }, +}) + +export const Route = createFileRoute('/')({ + component: HomePage, +}) diff --git a/benchmarks/client-nav/scenarios/links/vue/src/routes/items.$id.tsx b/benchmarks/client-nav/scenarios/links/vue/src/routes/items.$id.tsx new file mode 100644 index 0000000000..0dc5efa3d3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/vue/src/routes/items.$id.tsx @@ -0,0 +1,19 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { itemMarker } from '../../../shared' + +const ItemPage = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
+

{itemMarker(params.value.id)}

+
+ ) + }, +}) + +export const Route = createFileRoute('/items/$id')({ + component: ItemPage, +}) diff --git a/benchmarks/client-nav/scenarios/links/vue/tsconfig.json b/benchmarks/client-nav/scenarios/links/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/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/links/vue/vite.config.ts b/benchmarks/client-nav/scenarios/links/vue/vite.config.ts new file mode 100644 index 0000000000..ad89a49d70 --- /dev/null +++ b/benchmarks/client-nav/scenarios/links/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 links (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/loaders/react/project.json b/benchmarks/client-nav/scenarios/loaders/react/project.json new file mode 100644 index 0000000000..d3dbe585d4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-loaders-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/loaders/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/loaders/react/setup.ts b/benchmarks/client-nav/scenarios/loaders/react/setup.ts new file mode 100644 index 0000000000..130583b190 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/react/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } 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, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts b/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts new file mode 100644 index 0000000000..8bcc53b88e --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/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-loaders', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-loaders 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/loaders/react/speed.flame.ts b/benchmarks/client-nav/scenarios/loaders/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/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/loaders/react/src/main.tsx b/benchmarks/client-nav/scenarios/loaders/react/src/main.tsx new file mode 100644 index 0000000000..5febd6f795 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/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/loaders/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/loaders/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..35908a225f --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/react/src/routeTree.gen.ts @@ -0,0 +1,113 @@ +/* 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 DepsRouteImport } from './routes/deps' +import { Route as CachedIdRouteImport } from './routes/cached.$id' +import { Route as FreshIdRouteImport } from './routes/fresh.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const DepsRoute = DepsRouteImport.update({ + id: '/deps', + path: '/deps', + getParentRoute: () => rootRouteImport, +} as any) +const CachedIdRoute = CachedIdRouteImport.update({ + id: '/cached/$id', + 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 + '/deps': typeof DepsRoute + '/cached/$id': typeof CachedIdRoute + '/fresh/$id': typeof FreshIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/deps': typeof DepsRoute + '/cached/$id': typeof CachedIdRoute + '/fresh/$id': typeof FreshIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/deps': typeof DepsRoute + '/cached/$id': typeof CachedIdRoute + '/fresh/$id': typeof FreshIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/deps' | '/cached/$id' | '/fresh/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/deps' | '/cached/$id' | '/fresh/$id' + id: '__root__' | '/' | '/deps' | '/cached/$id' | '/fresh/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + DepsRoute: typeof DepsRoute + CachedIdRoute: typeof CachedIdRoute + FreshIdRoute: typeof FreshIdRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/deps': { + id: '/deps' + path: '/deps' + fullPath: '/deps' + preLoaderRoute: typeof DepsRouteImport + parentRoute: typeof rootRouteImport + } + '/cached/$id': { + id: '/cached/$id' + path: '/cached/$id' + fullPath: '/cached/$id' + preLoaderRoute: typeof CachedIdRouteImport + parentRoute: typeof rootRouteImport + } + '/fresh/$id': { + id: '/fresh/$id' + path: '/fresh/$id' + fullPath: '/fresh/$id' + preLoaderRoute: typeof FreshIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + DepsRoute: DepsRoute, + CachedIdRoute: CachedIdRoute, + FreshIdRoute: FreshIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/loaders/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/loaders/react/src/routes/__root.tsx new file mode 100644 index 0000000000..6309763cf3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/react/src/routes/__root.tsx @@ -0,0 +1,70 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/loaders/react/src/routes/cached.$id.tsx b/benchmarks/client-nav/scenarios/loaders/react/src/routes/cached.$id.tsx new file mode 100644 index 0000000000..9b954185cc --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/react/src/routes/cached.$id.tsx @@ -0,0 +1,55 @@ +import { createFileRoute } from '@tanstack/react-router' +import { computeChecksum, itemsChecksum, makeItems } from '../../../shared' + +export const Route = createFileRoute('/cached/$id')({ + loader: ({ params }) => { + const items = makeItems(`cached-${params.id}`) + return { items, checksum: itemsChecksum(items) } + }, + staleTime: 1e9, + gcTime: 1e9, + component: CachedPage, +}) + +const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) + +function SumSubscriber() { + const value = Route.useLoaderData({ + select: (data) => computeChecksum(data.checksum), + }) + + void computeChecksum(value) + return null +} + +function FirstItemSubscriber() { + const value = Route.useLoaderData({ + select: (data) => computeChecksum(data.items[0]?.value ?? 0), + }) + + void computeChecksum(value) + return null +} + +function CachedPage() { + const params = Route.useParams() + const loaderData = Route.useLoaderData() + + return ( +
+ {subscriberIndexes.map((index) => ( + + ))} + {subscriberIndexes.map((index) => ( + + ))} +

Cached

+
{`c-${params.id}-${loaderData.checksum}`}
+
    + {loaderData.items.slice(0, 5).map((item) => ( +
  • {item.name}
  • + ))} +
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/loaders/react/src/routes/deps.tsx b/benchmarks/client-nav/scenarios/loaders/react/src/routes/deps.tsx new file mode 100644 index 0000000000..92afe04a21 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/react/src/routes/deps.tsx @@ -0,0 +1,65 @@ +import { createFileRoute } from '@tanstack/react-router' +import type { SearchSchemaInput } from '@tanstack/react-router' +import { + computeChecksum, + itemsChecksum, + makeItems, + normalizePage, +} from '../../../shared' + +export const Route = createFileRoute('/deps')({ + validateSearch: (search: Record & SearchSchemaInput) => ({ + page: normalizePage(search.page), + }), + loaderDeps: ({ search }) => ({ page: search.page }), + loader: ({ deps }) => { + const items = makeItems(`deps-${deps.page}`) + return { items, checksum: itemsChecksum(items) } + }, + staleTime: 1e9, + gcTime: 1e9, + component: DepsPage, +}) + +const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) + +function SumSubscriber() { + const value = Route.useLoaderData({ + select: (data) => computeChecksum(data.checksum), + }) + + void computeChecksum(value) + return null +} + +function DepsSubscriber() { + const value = Route.useLoaderDeps({ + select: (deps) => computeChecksum(deps.page * 17), + }) + + void computeChecksum(value) + return null +} + +function DepsPage() { + const search = Route.useSearch() + const loaderData = Route.useLoaderData() + + return ( +
+ {subscriberIndexes.map((index) => ( + + ))} + {subscriberIndexes.map((index) => ( + + ))} +

Deps

+
{`d-${search.page}-${loaderData.checksum}`}
+
    + {loaderData.items.slice(0, 5).map((item) => ( +
  • {item.name}
  • + ))} +
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/loaders/react/src/routes/fresh.$id.tsx b/benchmarks/client-nav/scenarios/loaders/react/src/routes/fresh.$id.tsx new file mode 100644 index 0000000000..fb7cbf2f00 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/react/src/routes/fresh.$id.tsx @@ -0,0 +1,55 @@ +import { createFileRoute } from '@tanstack/react-router' +import { computeChecksum, itemsChecksum, makeItems } from '../../../shared' + +export const Route = createFileRoute('/fresh/$id')({ + loader: ({ params }) => { + const items = makeItems(`fresh-${params.id}`) + return { items, checksum: itemsChecksum(items) } + }, + staleTime: 0, + gcTime: 0, + component: FreshPage, +}) + +const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) + +function SumSubscriber() { + const value = Route.useLoaderData({ + select: (data) => computeChecksum(data.checksum), + }) + + void computeChecksum(value) + return null +} + +function FirstItemSubscriber() { + const value = Route.useLoaderData({ + select: (data) => computeChecksum(data.items[0]?.value ?? 0), + }) + + void computeChecksum(value) + return null +} + +function FreshPage() { + const params = Route.useParams() + const loaderData = Route.useLoaderData() + + return ( +
+ {subscriberIndexes.map((index) => ( + + ))} + {subscriberIndexes.map((index) => ( + + ))} +

Fresh

+
{`f-${params.id}-${loaderData.checksum}`}
+
    + {loaderData.items.slice(0, 5).map((item) => ( +
  • {item.name}
  • + ))} +
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/loaders/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/loaders/react/src/routes/index.tsx new file mode 100644 index 0000000000..9203c00841 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/react/src/routes/index.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return ( +
+

Loaders Bench

+
home
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/loaders/react/tsconfig.json b/benchmarks/client-nav/scenarios/loaders/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/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/loaders/react/vite.config.ts b/benchmarks/client-nav/scenarios/loaders/react/vite.config.ts new file mode 100644 index 0000000000..818b224130 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/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 loaders (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/loaders/shared.ts b/benchmarks/client-nav/scenarios/loaders/shared.ts new file mode 100644 index 0000000000..f744246160 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/shared.ts @@ -0,0 +1,134 @@ +/** + * Shared definition of the `loaders` scenario: deterministic loader data + * derivation, the click sequence, and per-step sanity assertions. The three + * framework apps consume these builders so the workload is identical modulo + * the rendering layer. + * + * Isolates: client loader dispatch — always-stale re-runs (staleTime 0), + * pure cache hits (staleTime 1e9), loaderDeps-keyed caching, + * router.invalidate(), and useLoaderData selector subscriptions. + */ + +import type { ScenarioStep } from '../harness' + +export function computeChecksum(seed: number) { + let value = Math.trunc(seed) | 0 + + for (let index = 0; index < 40; index++) { + value = (value * 1664525 + 1013904223 + index) >>> 0 + } + + return value +} + +export interface LoaderItem { + id: string + name: string + value: number + flag: boolean +} + +export function makeItems(seedText: string): Array { + let seed = 0 + for (let index = 0; index < seedText.length; index++) { + seed = (seed * 31 + seedText.charCodeAt(index)) >>> 0 + } + + const items: Array = [] + let value = seed + + for (let index = 0; index < 50; index++) { + value = (value * 1664525 + 1013904223) >>> 0 + items.push({ + id: `${seedText}-${index}`, + name: `Item ${index} of ${seedText}`, + value: value % 100000, + flag: value % 3 === 0, + }) + } + + return items +} + +export function itemsChecksum(items: Array) { + let sum = 0 + for (const item of items) { + sum = (sum + item.value + (item.flag ? 1 : 0)) >>> 0 + } + return sum +} + +export function normalizePage(value: unknown) { + const page = Number(value) + return Number.isFinite(page) && page > 0 ? Math.trunc(page) : 1 +} + +export function freshMarkerText(id: string) { + return `f-${id}-${itemsChecksum(makeItems(`fresh-${id}`))}` +} + +export function cachedMarkerText(id: string) { + return `c-${id}-${itemsChecksum(makeItems(`cached-${id}`))}` +} + +export function depsMarkerText(page: number) { + return `d-${page}-${itemsChecksum(makeItems(`deps-${page}`))}` +} + +export const steps: ReadonlyArray = [ + 'go-fresh-1', + 'go-fresh-2', + 'go-cached-1', + 'go-cached-2', + 'go-deps-1', + 'go-deps-2', + // Invalidates the currently matched routes (the deps route), re-running its + // loader with unchanged deps. Note: this also marks the cached fresh/cached + // matches invalid, so each of those loaders re-runs once per lap on its next + // visit — deterministic, identical work every lap. + { type: 'invalidate' }, + 'go-home', +] + +interface ExpectedState { + testId: string + text?: string +} + +const expectedStates: ReadonlyArray = [ + { testId: 'fresh-state', text: freshMarkerText('1') }, + { testId: 'fresh-state', text: freshMarkerText('2') }, + { testId: 'cached-state', text: cachedMarkerText('1') }, + { testId: 'cached-state', text: cachedMarkerText('2') }, + { testId: 'deps-state', text: depsMarkerText(1) }, + { testId: 'deps-state', text: depsMarkerText(2) }, + // After invalidate the deps loader re-ran with the same deps. + { testId: 'deps-state', text: depsMarkerText(2) }, + { testId: 'home-state' }, +] + +export function assertStepResult(stepIndex: number, container: HTMLElement) { + const expected = expectedStates[stepIndex]! + const element = container.querySelector(`[data-testid="${expected.testId}"]`) + + if (!element) { + throw new Error( + `Expected marker "${expected.testId}" to exist after step ${stepIndex}`, + ) + } + + if (expected.text !== undefined && element.textContent !== expected.text) { + throw new Error( + `Expected marker "${expected.testId}" to read "${expected.text}" after step ${stepIndex}, received "${element.textContent}"`, + ) + } +} + +// Two laps through the 8-step sequence per benchmark iteration. +export const ticksPerIteration = 16 + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/project.json b/benchmarks/client-nav/scenarios/loaders/solid/project.json new file mode 100644 index 0000000000..071e6bc385 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-loaders-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/loaders/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/setup.ts b/benchmarks/client-nav/scenarios/loaders/solid/setup.ts new file mode 100644 index 0000000000..6a46971603 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/solid/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } 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, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts new file mode 100644 index 0000000000..953a17b31a --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/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-loaders', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-loaders 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/loaders/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/loaders/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/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/loaders/solid/src/main.tsx b/benchmarks/client-nav/scenarios/loaders/solid/src/main.tsx new file mode 100644 index 0000000000..fa9d239418 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/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/loaders/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..fa5d032141 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts @@ -0,0 +1,113 @@ +/* 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 DepsRouteImport } from './routes/deps' +import { Route as CachedIdRouteImport } from './routes/cached.$id' +import { Route as FreshIdRouteImport } from './routes/fresh.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const DepsRoute = DepsRouteImport.update({ + id: '/deps', + path: '/deps', + getParentRoute: () => rootRouteImport, +} as any) +const CachedIdRoute = CachedIdRouteImport.update({ + id: '/cached/$id', + 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 + '/deps': typeof DepsRoute + '/cached/$id': typeof CachedIdRoute + '/fresh/$id': typeof FreshIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/deps': typeof DepsRoute + '/cached/$id': typeof CachedIdRoute + '/fresh/$id': typeof FreshIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/deps': typeof DepsRoute + '/cached/$id': typeof CachedIdRoute + '/fresh/$id': typeof FreshIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/deps' | '/cached/$id' | '/fresh/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/deps' | '/cached/$id' | '/fresh/$id' + id: '__root__' | '/' | '/deps' | '/cached/$id' | '/fresh/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + DepsRoute: typeof DepsRoute + CachedIdRoute: typeof CachedIdRoute + FreshIdRoute: typeof FreshIdRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/deps': { + id: '/deps' + path: '/deps' + fullPath: '/deps' + preLoaderRoute: typeof DepsRouteImport + parentRoute: typeof rootRouteImport + } + '/cached/$id': { + id: '/cached/$id' + path: '/cached/$id' + fullPath: '/cached/$id' + preLoaderRoute: typeof CachedIdRouteImport + parentRoute: typeof rootRouteImport + } + '/fresh/$id': { + id: '/fresh/$id' + path: '/fresh/$id' + fullPath: '/fresh/$id' + preLoaderRoute: typeof FreshIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + DepsRoute: DepsRoute, + CachedIdRoute: CachedIdRoute, + FreshIdRoute: FreshIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/loaders/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/loaders/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..30350f7907 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/solid/src/routes/__root.tsx @@ -0,0 +1,66 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/src/routes/cached.$id.tsx b/benchmarks/client-nav/scenarios/loaders/solid/src/routes/cached.$id.tsx new file mode 100644 index 0000000000..aab6be74dc --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/solid/src/routes/cached.$id.tsx @@ -0,0 +1,62 @@ +import { For, createRenderEffect } from 'solid-js' +import { createFileRoute } from '@tanstack/solid-router' +import { computeChecksum, itemsChecksum, makeItems } from '../../../shared' + +export const Route = createFileRoute('/cached/$id')({ + loader: ({ params }) => { + const items = makeItems(`cached-${params.id}`) + return { items, checksum: itemsChecksum(items) } + }, + staleTime: 1e9, + gcTime: 1e9, + component: CachedPage, +}) + +const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) + +function PerfValue(props: { value: () => number }) { + createRenderEffect(() => { + void props.value() + }) + + return null +} + +function SumSubscriber() { + const value = Route.useLoaderData({ + select: (data) => computeChecksum(data.checksum), + }) + + return computeChecksum(value())} /> +} + +function FirstItemSubscriber() { + const value = Route.useLoaderData({ + select: (data) => computeChecksum(data.items[0]?.value ?? 0), + }) + + return computeChecksum(value())} /> +} + +function CachedPage() { + const params = Route.useParams() + const loaderData = Route.useLoaderData() + + return ( +
+ {subscriberIndexes.map(() => ( + + ))} + {subscriberIndexes.map(() => ( + + ))} +

Cached

+
{`c-${params().id}-${loaderData().checksum}`}
+
    + + {(item) =>
  • {item.name}
  • } +
    +
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/src/routes/deps.tsx b/benchmarks/client-nav/scenarios/loaders/solid/src/routes/deps.tsx new file mode 100644 index 0000000000..2f23f2d3da --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/solid/src/routes/deps.tsx @@ -0,0 +1,72 @@ +import { For, createRenderEffect } from 'solid-js' +import { createFileRoute } from '@tanstack/solid-router' +import type { SearchSchemaInput } from '@tanstack/solid-router' +import { + computeChecksum, + itemsChecksum, + makeItems, + normalizePage, +} from '../../../shared' + +export const Route = createFileRoute('/deps')({ + validateSearch: (search: Record & SearchSchemaInput) => ({ + page: normalizePage(search.page), + }), + loaderDeps: ({ search }) => ({ page: search.page }), + loader: ({ deps }) => { + const items = makeItems(`deps-${deps.page}`) + return { items, checksum: itemsChecksum(items) } + }, + staleTime: 1e9, + gcTime: 1e9, + component: DepsPage, +}) + +const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) + +function PerfValue(props: { value: () => number }) { + createRenderEffect(() => { + void props.value() + }) + + return null +} + +function SumSubscriber() { + const value = Route.useLoaderData({ + select: (data) => computeChecksum(data.checksum), + }) + + return computeChecksum(value())} /> +} + +function DepsSubscriber() { + const value = Route.useLoaderDeps({ + select: (deps) => computeChecksum(deps.page * 17), + }) + + return computeChecksum(value())} /> +} + +function DepsPage() { + const search = Route.useSearch() + const loaderData = Route.useLoaderData() + + return ( +
+ {subscriberIndexes.map(() => ( + + ))} + {subscriberIndexes.map(() => ( + + ))} +

Deps

+
{`d-${search().page}-${loaderData().checksum}`}
+
    + + {(item) =>
  • {item.name}
  • } +
    +
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/src/routes/fresh.$id.tsx b/benchmarks/client-nav/scenarios/loaders/solid/src/routes/fresh.$id.tsx new file mode 100644 index 0000000000..acd6a9aa27 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/solid/src/routes/fresh.$id.tsx @@ -0,0 +1,62 @@ +import { For, createRenderEffect } from 'solid-js' +import { createFileRoute } from '@tanstack/solid-router' +import { computeChecksum, itemsChecksum, makeItems } from '../../../shared' + +export const Route = createFileRoute('/fresh/$id')({ + loader: ({ params }) => { + const items = makeItems(`fresh-${params.id}`) + return { items, checksum: itemsChecksum(items) } + }, + staleTime: 0, + gcTime: 0, + component: FreshPage, +}) + +const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) + +function PerfValue(props: { value: () => number }) { + createRenderEffect(() => { + void props.value() + }) + + return null +} + +function SumSubscriber() { + const value = Route.useLoaderData({ + select: (data) => computeChecksum(data.checksum), + }) + + return computeChecksum(value())} /> +} + +function FirstItemSubscriber() { + const value = Route.useLoaderData({ + select: (data) => computeChecksum(data.items[0]?.value ?? 0), + }) + + return computeChecksum(value())} /> +} + +function FreshPage() { + const params = Route.useParams() + const loaderData = Route.useLoaderData() + + return ( +
+ {subscriberIndexes.map(() => ( + + ))} + {subscriberIndexes.map(() => ( + + ))} +

Fresh

+
{`f-${params().id}-${loaderData().checksum}`}
+
    + + {(item) =>
  • {item.name}
  • } +
    +
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/loaders/solid/src/routes/index.tsx new file mode 100644 index 0000000000..7287d47d0a --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/solid/src/routes/index.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return ( +
+

Loaders Bench

+
home
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/loaders/solid/tsconfig.json b/benchmarks/client-nav/scenarios/loaders/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/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/loaders/solid/vite.config.ts b/benchmarks/client-nav/scenarios/loaders/solid/vite.config.ts new file mode 100644 index 0000000000..90584d3b7e --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/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 loaders (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/loaders/vue/project.json b/benchmarks/client-nav/scenarios/loaders/vue/project.json new file mode 100644 index 0000000000..69bd95837d --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-loaders-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/loaders/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/loaders/vue/setup.ts b/benchmarks/client-nav/scenarios/loaders/vue/setup.ts new file mode 100644 index 0000000000..97b74b3892 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/vue/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } 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, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts new file mode 100644 index 0000000000..1ae2f89a56 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/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-loaders', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-loaders 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/loaders/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/loaders/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/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/loaders/vue/src/main.tsx b/benchmarks/client-nav/scenarios/loaders/vue/src/main.tsx new file mode 100644 index 0000000000..cae9b54f1d --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/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/loaders/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..10cb8f2aca --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts @@ -0,0 +1,113 @@ +/* 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 DepsRouteImport } from './routes/deps' +import { Route as CachedIdRouteImport } from './routes/cached.$id' +import { Route as FreshIdRouteImport } from './routes/fresh.$id' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const DepsRoute = DepsRouteImport.update({ + id: '/deps', + path: '/deps', + getParentRoute: () => rootRouteImport, +} as any) +const CachedIdRoute = CachedIdRouteImport.update({ + id: '/cached/$id', + 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 + '/deps': typeof DepsRoute + '/cached/$id': typeof CachedIdRoute + '/fresh/$id': typeof FreshIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/deps': typeof DepsRoute + '/cached/$id': typeof CachedIdRoute + '/fresh/$id': typeof FreshIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/deps': typeof DepsRoute + '/cached/$id': typeof CachedIdRoute + '/fresh/$id': typeof FreshIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/deps' | '/cached/$id' | '/fresh/$id' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/deps' | '/cached/$id' | '/fresh/$id' + id: '__root__' | '/' | '/deps' | '/cached/$id' | '/fresh/$id' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + DepsRoute: typeof DepsRoute + CachedIdRoute: typeof CachedIdRoute + FreshIdRoute: typeof FreshIdRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/deps': { + id: '/deps' + path: '/deps' + fullPath: '/deps' + preLoaderRoute: typeof DepsRouteImport + parentRoute: typeof rootRouteImport + } + '/cached/$id': { + id: '/cached/$id' + path: '/cached/$id' + fullPath: '/cached/$id' + preLoaderRoute: typeof CachedIdRouteImport + parentRoute: typeof rootRouteImport + } + '/fresh/$id': { + id: '/fresh/$id' + path: '/fresh/$id' + fullPath: '/fresh/$id' + preLoaderRoute: typeof FreshIdRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + DepsRoute: DepsRoute, + CachedIdRoute: CachedIdRoute, + FreshIdRoute: FreshIdRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/loaders/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/loaders/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..b9102a92c4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/vue/src/routes/__root.tsx @@ -0,0 +1,69 @@ +import * as Vue from 'vue' +import { Link, Outlet, createRootRoute } from '@tanstack/vue-router' + +const RootComponent = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + ) + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/loaders/vue/src/routes/cached.$id.tsx b/benchmarks/client-nav/scenarios/loaders/vue/src/routes/cached.$id.tsx new file mode 100644 index 0000000000..a426e35765 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/vue/src/routes/cached.$id.tsx @@ -0,0 +1,68 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { computeChecksum, itemsChecksum, makeItems } from '../../../shared' + +const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) + +const SumSubscriber = Vue.defineComponent({ + setup() { + const value = Route.useLoaderData({ + select: (data) => computeChecksum(data.checksum), + }) + + return () => { + void computeChecksum(value.value) + return null + } + }, +}) + +const FirstItemSubscriber = Vue.defineComponent({ + setup() { + const value = Route.useLoaderData({ + select: (data) => computeChecksum(data.items[0]?.value ?? 0), + }) + + return () => { + void computeChecksum(value.value) + return null + } + }, +}) + +const CachedPage = Vue.defineComponent({ + setup() { + const params = Route.useParams() + const loaderData = Route.useLoaderData() + + return () => ( +
+ {subscriberIndexes.map((index) => ( + + ))} + {subscriberIndexes.map((index) => ( + + ))} +

Cached

+
+ {`c-${params.value.id}-${loaderData.value.checksum}`} +
+
    + {loaderData.value.items.slice(0, 5).map((item) => ( +
  • {item.name}
  • + ))} +
+
+ ) + }, +}) + +export const Route = createFileRoute('/cached/$id')({ + loader: ({ params }) => { + const items = makeItems(`cached-${params.id}`) + return { items, checksum: itemsChecksum(items) } + }, + staleTime: 1e9, + gcTime: 1e9, + component: CachedPage, +}) diff --git a/benchmarks/client-nav/scenarios/loaders/vue/src/routes/deps.tsx b/benchmarks/client-nav/scenarios/loaders/vue/src/routes/deps.tsx new file mode 100644 index 0000000000..f987d15d34 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/vue/src/routes/deps.tsx @@ -0,0 +1,78 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import type { SearchSchemaInput } from '@tanstack/vue-router' +import { + computeChecksum, + itemsChecksum, + makeItems, + normalizePage, +} from '../../../shared' + +const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) + +const SumSubscriber = Vue.defineComponent({ + setup() { + const value = Route.useLoaderData({ + select: (data) => computeChecksum(data.checksum), + }) + + return () => { + void computeChecksum(value.value) + return null + } + }, +}) + +const DepsSubscriber = Vue.defineComponent({ + setup() { + const value = Route.useLoaderDeps({ + select: (deps) => computeChecksum(deps.page * 17), + }) + + return () => { + void computeChecksum(value.value) + return null + } + }, +}) + +const DepsPage = Vue.defineComponent({ + setup() { + const search = Route.useSearch() + const loaderData = Route.useLoaderData() + + return () => ( +
+ {subscriberIndexes.map((index) => ( + + ))} + {subscriberIndexes.map((index) => ( + + ))} +

Deps

+
+ {`d-${search.value.page}-${loaderData.value.checksum}`} +
+
    + {loaderData.value.items.slice(0, 5).map((item) => ( +
  • {item.name}
  • + ))} +
+
+ ) + }, +}) + +export const Route = createFileRoute('/deps')({ + validateSearch: (search: Record & SearchSchemaInput) => ({ + page: normalizePage(search.page), + }), + loaderDeps: ({ search }) => ({ page: search.page }), + loader: ({ deps }) => { + const items = makeItems(`deps-${deps.page}`) + return { items, checksum: itemsChecksum(items) } + }, + staleTime: 1e9, + gcTime: 1e9, + component: DepsPage, +}) diff --git a/benchmarks/client-nav/scenarios/loaders/vue/src/routes/fresh.$id.tsx b/benchmarks/client-nav/scenarios/loaders/vue/src/routes/fresh.$id.tsx new file mode 100644 index 0000000000..64eec85cfa --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/vue/src/routes/fresh.$id.tsx @@ -0,0 +1,68 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { computeChecksum, itemsChecksum, makeItems } from '../../../shared' + +const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) + +const SumSubscriber = Vue.defineComponent({ + setup() { + const value = Route.useLoaderData({ + select: (data) => computeChecksum(data.checksum), + }) + + return () => { + void computeChecksum(value.value) + return null + } + }, +}) + +const FirstItemSubscriber = Vue.defineComponent({ + setup() { + const value = Route.useLoaderData({ + select: (data) => computeChecksum(data.items[0]?.value ?? 0), + }) + + return () => { + void computeChecksum(value.value) + return null + } + }, +}) + +const FreshPage = Vue.defineComponent({ + setup() { + const params = Route.useParams() + const loaderData = Route.useLoaderData() + + return () => ( +
+ {subscriberIndexes.map((index) => ( + + ))} + {subscriberIndexes.map((index) => ( + + ))} +

Fresh

+
+ {`f-${params.value.id}-${loaderData.value.checksum}`} +
+
    + {loaderData.value.items.slice(0, 5).map((item) => ( +
  • {item.name}
  • + ))} +
+
+ ) + }, +}) + +export const Route = createFileRoute('/fresh/$id')({ + loader: ({ params }) => { + const items = makeItems(`fresh-${params.id}`) + return { items, checksum: itemsChecksum(items) } + }, + staleTime: 0, + gcTime: 0, + component: FreshPage, +}) diff --git a/benchmarks/client-nav/scenarios/loaders/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/loaders/vue/src/routes/index.tsx new file mode 100644 index 0000000000..c9724c90a4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/vue/src/routes/index.tsx @@ -0,0 +1,17 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const HomePage = Vue.defineComponent({ + setup() { + return () => ( +
+

Loaders Bench

+
home
+
+ ) + }, +}) + +export const Route = createFileRoute('/')({ + component: HomePage, +}) diff --git a/benchmarks/client-nav/scenarios/loaders/vue/tsconfig.json b/benchmarks/client-nav/scenarios/loaders/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/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/loaders/vue/vite.config.ts b/benchmarks/client-nav/scenarios/loaders/vue/vite.config.ts new file mode 100644 index 0000000000..ecf4cce139 --- /dev/null +++ b/benchmarks/client-nav/scenarios/loaders/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 loaders (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/mount/react/project.json b/benchmarks/client-nav/scenarios/mount/react/project.json new file mode 100644 index 0000000000..61839943b3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-mount-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/mount/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/mount/react/setup.ts b/benchmarks/client-nav/scenarios/mount/react/setup.ts new file mode 100644 index 0000000000..ed0426c696 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/setup.ts @@ -0,0 +1,17 @@ +import { createMountLoopSetup } from '../../harness' +import { assertReady, readyTestId } 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 createMountLoopSetup({ + frameworkLabel: 'React', + mount: mountTestApp, + readyTestId, + assertReady, + }) +} diff --git a/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts b/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts new file mode 100644 index 0000000000..6c3a64b026 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/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-mount', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-mount 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/mount/react/speed.flame.ts b/benchmarks/client-nav/scenarios/mount/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/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/mount/react/src/main.tsx b/benchmarks/client-nav/scenarios/mount/react/src/main.tsx new file mode 100644 index 0000000000..4e45ed7ef3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/src/main.tsx @@ -0,0 +1,38 @@ +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { createRoot } from 'react-dom/client' +import { routeTree } from './routeTree.gen' +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 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. + */ +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + }) +} + +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/mount/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/mount/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..f9b7e5c268 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/src/routeTree.gen.ts @@ -0,0 +1,264 @@ +/* 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 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 BlogSlugRouteImport } from './routes/blog.$slug' +import { Route as ShopIndexRouteImport } from './routes/shop.index' +import { Route as ShopProductIdRouteImport } from './routes/shop.$productId' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) +const BlogRoute = BlogRouteImport.update({ + id: '/blog', + path: '/blog', + getParentRoute: () => rootRouteImport, +} as any) +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 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 + '/about': typeof AboutRoute + '/blog': typeof BlogRouteWithChildren + '/search': typeof SearchRoute + '/settings': typeof SettingsRoute + '/shop': typeof ShopRouteWithChildren + '/blog/$slug': typeof BlogSlugRoute + '/shop/$productId': typeof ShopProductIdRoute + '/blog/': typeof BlogIndexRoute + '/shop/': typeof ShopIndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/search': typeof SearchRoute + '/settings': typeof SettingsRoute + '/blog/$slug': typeof BlogSlugRoute + '/shop/$productId': typeof ShopProductIdRoute + '/blog': typeof BlogIndexRoute + '/shop': typeof ShopIndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/blog': typeof BlogRouteWithChildren + '/search': typeof SearchRoute + '/settings': typeof SettingsRoute + '/shop': typeof ShopRouteWithChildren + '/blog/$slug': typeof BlogSlugRoute + '/shop/$productId': typeof ShopProductIdRoute + '/blog/': typeof BlogIndexRoute + '/shop/': typeof ShopIndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/about' + | '/blog' + | '/search' + | '/settings' + | '/shop' + | '/blog/$slug' + | '/shop/$productId' + | '/blog/' + | '/shop/' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/about' + | '/search' + | '/settings' + | '/blog/$slug' + | '/shop/$productId' + | '/blog' + | '/shop' + id: + | '__root__' + | '/' + | '/about' + | '/blog' + | '/search' + | '/settings' + | '/shop' + | '/blog/$slug' + | '/shop/$productId' + | '/blog/' + | '/shop/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + AboutRoute: typeof AboutRoute + BlogRoute: typeof BlogRouteWithChildren + SearchRoute: typeof SearchRoute + SettingsRoute: typeof SettingsRoute + ShopRoute: typeof ShopRouteWithChildren +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } + '/blog': { + id: '/blog' + path: '/blog' + fullPath: '/blog' + preLoaderRoute: typeof BlogRouteImport + parentRoute: typeof rootRouteImport + } + '/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/' + path: '/' + fullPath: '/blog/' + preLoaderRoute: typeof BlogIndexRouteImport + parentRoute: typeof BlogRoute + } + '/blog/$slug': { + id: '/blog/$slug' + path: '/$slug' + fullPath: '/blog/$slug' + 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 + } + } +} + +interface BlogRouteChildren { + BlogSlugRoute: typeof BlogSlugRoute + BlogIndexRoute: typeof BlogIndexRoute +} + +const BlogRouteChildren: BlogRouteChildren = { + BlogSlugRoute: BlogSlugRoute, + BlogIndexRoute: BlogIndexRoute, +} + +const BlogRouteWithChildren = BlogRoute._addFileChildren(BlogRouteChildren) + +interface ShopRouteChildren { + ShopProductIdRoute: typeof ShopProductIdRoute + ShopIndexRoute: typeof ShopIndexRoute +} + +const ShopRouteChildren: ShopRouteChildren = { + ShopProductIdRoute: ShopProductIdRoute, + ShopIndexRoute: ShopIndexRoute, +} + +const ShopRouteWithChildren = ShopRoute._addFileChildren(ShopRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + AboutRoute: AboutRoute, + BlogRoute: BlogRouteWithChildren, + SearchRoute: SearchRoute, + SettingsRoute: SettingsRoute, + ShopRoute: ShopRouteWithChildren, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/__root.tsx new file mode 100644 index 0000000000..0deab171d8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/src/routes/__root.tsx @@ -0,0 +1,41 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/about.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/about.tsx new file mode 100644 index 0000000000..3fedde283b --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/src/routes/about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/about')({ + component: AboutPage, +}) + +function AboutPage() { + return

About

+} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/blog.$slug.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/blog.$slug.tsx new file mode 100644 index 0000000000..f995d95d94 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/src/routes/blog.$slug.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/react-router' +import { articleData } from '../../../shared' + +export const Route = createFileRoute('/blog/$slug')({ + loader: ({ params }) => articleData(params.slug), + component: ArticlePage, +}) + +function ArticlePage() { + const article = Route.useLoaderData() + + return
{`${article.title} (${article.words} words)`}
+} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/blog.index.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/blog.index.tsx new file mode 100644 index 0000000000..437187eb4f --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/src/routes/blog.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/blog/')({ + component: BlogIndexPage, +}) + +function BlogIndexPage() { + return

All articles

+} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/blog.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/blog.tsx new file mode 100644 index 0000000000..ab4fbeb482 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/src/routes/blog.tsx @@ -0,0 +1,16 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { blogContext } from '../../../shared' + +export const Route = createFileRoute('/blog')({ + beforeLoad: () => blogContext(), + component: BlogLayout, +}) + +function BlogLayout() { + return ( +
+

Blog

+ +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/index.tsx new file mode 100644 index 0000000000..dbc99d8f66 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/src/routes/index.tsx @@ -0,0 +1,22 @@ +import { createFileRoute } from '@tanstack/react-router' +import { homeItems, readyTestId } from '../../../shared' + +export const Route = createFileRoute('/')({ + loader: () => homeItems(), + component: HomePage, +}) + +function HomePage() { + const items = Route.useLoaderData() + + return ( +
+

{`Home (${items.length} items)`}

+
    + {items.map((item) => ( +
  • {`${item.label}: ${item.score}`}
  • + ))} +
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/search.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/search.tsx new file mode 100644 index 0000000000..faba50fc72 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/src/routes/search.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/react-router' +import { normalizePage, normalizeQuery } from '../../../shared' + +export const Route = createFileRoute('/search')({ + validateSearch: (search: Record) => ({ + q: normalizeQuery(search.q), + page: normalizePage(search.page), + }), + component: SearchPage, +}) + +function SearchPage() { + const search = Route.useSearch() + + return

{`Results for "${search.q}" page ${search.page}`}

+} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/settings.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/settings.tsx new file mode 100644 index 0000000000..1f46d9d885 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/src/routes/settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/settings')({ + component: SettingsPage, +}) + +function SettingsPage() { + return

Settings

+} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/shop.$productId.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/shop.$productId.tsx new file mode 100644 index 0000000000..7b729a3dca --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/src/routes/shop.$productId.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/react-router' +import { productData } from '../../../shared' + +export const Route = createFileRoute('/shop/$productId')({ + loader: ({ params }) => productData(params.productId), + component: ProductPage, +}) + +function ProductPage() { + const product = Route.useLoaderData() + + return
{`${product.name}: ${product.price}`}
+} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/shop.index.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/shop.index.tsx new file mode 100644 index 0000000000..dbca94357a --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/src/routes/shop.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/shop/')({ + component: ShopIndexPage, +}) + +function ShopIndexPage() { + return

All products

+} diff --git a/benchmarks/client-nav/scenarios/mount/react/src/routes/shop.tsx b/benchmarks/client-nav/scenarios/mount/react/src/routes/shop.tsx new file mode 100644 index 0000000000..5243d7bb0e --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/react/src/routes/shop.tsx @@ -0,0 +1,16 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { shopContext } from '../../../shared' + +export const Route = createFileRoute('/shop')({ + beforeLoad: () => shopContext(), + component: ShopLayout, +}) + +function ShopLayout() { + return ( +
+

Shop

+ +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/mount/react/tsconfig.json b/benchmarks/client-nav/scenarios/mount/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/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/mount/react/vite.config.ts b/benchmarks/client-nav/scenarios/mount/react/vite.config.ts new file mode 100644 index 0000000000..e197d33a9e --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/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 mount (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/mount/shared.ts b/benchmarks/client-nav/scenarios/mount/shared.ts new file mode 100644 index 0000000000..a8f3d2c7bd --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/shared.ts @@ -0,0 +1,75 @@ +/** + * Shared definition of the `mount` scenario: cold start of a moderate, + * realistic app — router creation (processRouteTree), first render, initial + * `router.load()`, and unmount. This is the only scenario where router + * construction is inside the measured loop; the wider tree exists as + * realistic route-processing weight even though only the index route loads. + */ + +export const readyTestId = 'mount-ready' + +export const homeItemCount = 5 + +export function homeItems() { + return Array.from({ length: homeItemCount }, (_, index) => ({ + id: `item-${index}`, + label: `Featured item ${index}`, + score: index * 17 + 3, + })) +} + +export const homeReadyText = `Home (${homeItemCount} items)` + +export function shopContext() { + return { shopSeed: 7 } +} + +export function blogContext() { + return { blogSeed: 13 } +} + +export function productData(productId: string) { + return { + id: productId, + name: `Product ${productId}`, + price: productId.length * 100 + 42, + } +} + +export function articleData(slug: string) { + return { + slug, + title: `Article ${slug}`, + words: slug.length * 250, + } +} + +export function normalizePage(value: unknown) { + const page = Number(value) + return Number.isFinite(page) && page > 0 ? Math.trunc(page) : 1 +} + +export function normalizeQuery(value: unknown) { + return typeof value === 'string' ? value : '' +} + +export function assertReady(container: HTMLElement) { + const marker = container.querySelector(`[data-testid="${readyTestId}"]`) + if (marker?.textContent !== homeReadyText) { + throw new Error( + `Expected mount marker to be "${homeReadyText}", received "${marker?.textContent}"`, + ) + } +} + +// Mounts per benchmark iteration. +// 6 mounts per iteration: a single mount simulates to only ~8ms of CPU, and +// very short measures amplify the relative impact of allocator/GC +// quantization; 6 keeps the measure comfortably above ~50ms simulated. +export const ticksPerIteration = 6 + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/mount/solid/project.json b/benchmarks/client-nav/scenarios/mount/solid/project.json new file mode 100644 index 0000000000..4349570654 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-mount-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/mount/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/mount/solid/setup.ts b/benchmarks/client-nav/scenarios/mount/solid/setup.ts new file mode 100644 index 0000000000..810ea38c91 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/setup.ts @@ -0,0 +1,17 @@ +import { createMountLoopSetup } from '../../harness' +import { assertReady, readyTestId } 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 createMountLoopSetup({ + frameworkLabel: 'Solid', + mount: mountTestApp, + readyTestId, + assertReady, + }) +} diff --git a/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts new file mode 100644 index 0000000000..236f875f57 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/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-mount', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-mount 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/mount/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/mount/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/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/mount/solid/src/main.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/main.tsx new file mode 100644 index 0000000000..2586872f5c --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/src/main.tsx @@ -0,0 +1,37 @@ +import { render } from 'solid-js/web' +import { RouterProvider, createRouter } from '@tanstack/solid-router' +import { routeTree } from './routeTree.gen' +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 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. + */ +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + }) +} + +declare module '@tanstack/solid-router' { + interface Register { + router: ReturnType + } +} + +export function mountTestApp(container: HTMLElement, history: RouterHistory) { + const router = createTestRouter(history) + + const dispose = render(() => , container) + + return { + router, + unmount() { + dispose() + }, + } +} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/mount/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..30247636dd --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/src/routeTree.gen.ts @@ -0,0 +1,264 @@ +/* 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 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 BlogSlugRouteImport } from './routes/blog.$slug' +import { Route as ShopIndexRouteImport } from './routes/shop.index' +import { Route as ShopProductIdRouteImport } from './routes/shop.$productId' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) +const BlogRoute = BlogRouteImport.update({ + id: '/blog', + path: '/blog', + getParentRoute: () => rootRouteImport, +} as any) +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 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 + '/about': typeof AboutRoute + '/blog': typeof BlogRouteWithChildren + '/search': typeof SearchRoute + '/settings': typeof SettingsRoute + '/shop': typeof ShopRouteWithChildren + '/blog/$slug': typeof BlogSlugRoute + '/shop/$productId': typeof ShopProductIdRoute + '/blog/': typeof BlogIndexRoute + '/shop/': typeof ShopIndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/search': typeof SearchRoute + '/settings': typeof SettingsRoute + '/blog/$slug': typeof BlogSlugRoute + '/shop/$productId': typeof ShopProductIdRoute + '/blog': typeof BlogIndexRoute + '/shop': typeof ShopIndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/blog': typeof BlogRouteWithChildren + '/search': typeof SearchRoute + '/settings': typeof SettingsRoute + '/shop': typeof ShopRouteWithChildren + '/blog/$slug': typeof BlogSlugRoute + '/shop/$productId': typeof ShopProductIdRoute + '/blog/': typeof BlogIndexRoute + '/shop/': typeof ShopIndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/about' + | '/blog' + | '/search' + | '/settings' + | '/shop' + | '/blog/$slug' + | '/shop/$productId' + | '/blog/' + | '/shop/' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/about' + | '/search' + | '/settings' + | '/blog/$slug' + | '/shop/$productId' + | '/blog' + | '/shop' + id: + | '__root__' + | '/' + | '/about' + | '/blog' + | '/search' + | '/settings' + | '/shop' + | '/blog/$slug' + | '/shop/$productId' + | '/blog/' + | '/shop/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + AboutRoute: typeof AboutRoute + BlogRoute: typeof BlogRouteWithChildren + SearchRoute: typeof SearchRoute + SettingsRoute: typeof SettingsRoute + ShopRoute: typeof ShopRouteWithChildren +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } + '/blog': { + id: '/blog' + path: '/blog' + fullPath: '/blog' + preLoaderRoute: typeof BlogRouteImport + parentRoute: typeof rootRouteImport + } + '/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/' + path: '/' + fullPath: '/blog/' + preLoaderRoute: typeof BlogIndexRouteImport + parentRoute: typeof BlogRoute + } + '/blog/$slug': { + id: '/blog/$slug' + path: '/$slug' + fullPath: '/blog/$slug' + 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 + } + } +} + +interface BlogRouteChildren { + BlogSlugRoute: typeof BlogSlugRoute + BlogIndexRoute: typeof BlogIndexRoute +} + +const BlogRouteChildren: BlogRouteChildren = { + BlogSlugRoute: BlogSlugRoute, + BlogIndexRoute: BlogIndexRoute, +} + +const BlogRouteWithChildren = BlogRoute._addFileChildren(BlogRouteChildren) + +interface ShopRouteChildren { + ShopProductIdRoute: typeof ShopProductIdRoute + ShopIndexRoute: typeof ShopIndexRoute +} + +const ShopRouteChildren: ShopRouteChildren = { + ShopProductIdRoute: ShopProductIdRoute, + ShopIndexRoute: ShopIndexRoute, +} + +const ShopRouteWithChildren = ShopRoute._addFileChildren(ShopRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + AboutRoute: AboutRoute, + BlogRoute: BlogRouteWithChildren, + SearchRoute: SearchRoute, + SettingsRoute: SettingsRoute, + ShopRoute: ShopRouteWithChildren, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..f5c3be2641 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/src/routes/__root.tsx @@ -0,0 +1,41 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/about.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/about.tsx new file mode 100644 index 0000000000..f74d85aa06 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/src/routes/about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/about')({ + component: AboutPage, +}) + +function AboutPage() { + return

About

+} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/blog.$slug.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/blog.$slug.tsx new file mode 100644 index 0000000000..82caee757a --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/src/routes/blog.$slug.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { articleData } from '../../../shared' + +export const Route = createFileRoute('/blog/$slug')({ + loader: ({ params }) => articleData(params.slug), + component: ArticlePage, +}) + +function ArticlePage() { + const article = Route.useLoaderData() + + return
{`${article().title} (${article().words} words)`}
+} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/blog.index.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/blog.index.tsx new file mode 100644 index 0000000000..8e75108aca --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/src/routes/blog.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/blog/')({ + component: BlogIndexPage, +}) + +function BlogIndexPage() { + return

All articles

+} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/blog.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/blog.tsx new file mode 100644 index 0000000000..1e2cfbd019 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/src/routes/blog.tsx @@ -0,0 +1,16 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { blogContext } from '../../../shared' + +export const Route = createFileRoute('/blog')({ + beforeLoad: () => blogContext(), + component: BlogLayout, +}) + +function BlogLayout() { + return ( +
+

Blog

+ +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/index.tsx new file mode 100644 index 0000000000..30665ba224 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/src/routes/index.tsx @@ -0,0 +1,23 @@ +import { For } from 'solid-js' +import { createFileRoute } from '@tanstack/solid-router' +import { homeItems, readyTestId } from '../../../shared' + +export const Route = createFileRoute('/')({ + loader: () => homeItems(), + component: HomePage, +}) + +function HomePage() { + const items = Route.useLoaderData() + + return ( +
+

{`Home (${items().length} items)`}

+
    + + {(item) =>
  • {`${item.label}: ${item.score}`}
  • } +
    +
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/search.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/search.tsx new file mode 100644 index 0000000000..3f8b2d9dd7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/src/routes/search.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { normalizePage, normalizeQuery } from '../../../shared' + +export const Route = createFileRoute('/search')({ + validateSearch: (search: Record) => ({ + q: normalizeQuery(search.q), + page: normalizePage(search.page), + }), + component: SearchPage, +}) + +function SearchPage() { + const search = Route.useSearch() + + return

{`Results for "${search().q}" page ${search().page}`}

+} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/settings.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/settings.tsx new file mode 100644 index 0000000000..c6b95424d9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/src/routes/settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/settings')({ + component: SettingsPage, +}) + +function SettingsPage() { + return

Settings

+} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/shop.$productId.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/shop.$productId.tsx new file mode 100644 index 0000000000..71b0411d6b --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/src/routes/shop.$productId.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { productData } from '../../../shared' + +export const Route = createFileRoute('/shop/$productId')({ + loader: ({ params }) => productData(params.productId), + component: ProductPage, +}) + +function ProductPage() { + const product = Route.useLoaderData() + + return
{`${product().name}: ${product().price}`}
+} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/shop.index.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/shop.index.tsx new file mode 100644 index 0000000000..e33c8779f9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/src/routes/shop.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/shop/')({ + component: ShopIndexPage, +}) + +function ShopIndexPage() { + return

All products

+} diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routes/shop.tsx b/benchmarks/client-nav/scenarios/mount/solid/src/routes/shop.tsx new file mode 100644 index 0000000000..ff2ca78653 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/solid/src/routes/shop.tsx @@ -0,0 +1,16 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { shopContext } from '../../../shared' + +export const Route = createFileRoute('/shop')({ + beforeLoad: () => shopContext(), + component: ShopLayout, +}) + +function ShopLayout() { + return ( +
+

Shop

+ +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/mount/solid/tsconfig.json b/benchmarks/client-nav/scenarios/mount/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/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/mount/solid/vite.config.ts b/benchmarks/client-nav/scenarios/mount/solid/vite.config.ts new file mode 100644 index 0000000000..5b586dd128 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/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 mount (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/project.json b/benchmarks/client-nav/scenarios/mount/vue/project.json new file mode 100644 index 0000000000..f2dbd10440 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-mount-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/mount/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/mount/vue/setup.ts b/benchmarks/client-nav/scenarios/mount/vue/setup.ts new file mode 100644 index 0000000000..3976e71c51 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/setup.ts @@ -0,0 +1,17 @@ +import { createMountLoopSetup } from '../../harness' +import { assertReady, readyTestId } 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 createMountLoopSetup({ + frameworkLabel: 'Vue', + mount: mountTestApp, + readyTestId, + assertReady, + }) +} diff --git a/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts new file mode 100644 index 0000000000..d9268ba91b --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts @@ -0,0 +1,15 @@ +import { test } from 'vitest' +import { benchLifecycle } from '../../../../cpu-simulation' +import { benchOptions, ticksPerIteration } from '../shared' +import { setup } from './setup' + +test('client-mount', async ({ bench }) => { + const scenario = setup() + + 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/speed.flame.ts b/benchmarks/client-nav/scenarios/mount/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/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/mount/vue/src/main.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/main.tsx new file mode 100644 index 0000000000..fc493c10a5 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/src/main.tsx @@ -0,0 +1,42 @@ +import * as Vue from 'vue' +import { RouterProvider, createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' +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 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. + */ +export function createTestRouter(history: RouterHistory) { + return createRouter({ + routeTree, + history, + }) +} + +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/mount/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/mount/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..cd27c917e1 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/src/routeTree.gen.ts @@ -0,0 +1,264 @@ +/* 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 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 BlogSlugRouteImport } from './routes/blog.$slug' +import { Route as ShopIndexRouteImport } from './routes/shop.index' +import { Route as ShopProductIdRouteImport } from './routes/shop.$productId' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) +const BlogRoute = BlogRouteImport.update({ + id: '/blog', + path: '/blog', + getParentRoute: () => rootRouteImport, +} as any) +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 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 + '/about': typeof AboutRoute + '/blog': typeof BlogRouteWithChildren + '/search': typeof SearchRoute + '/settings': typeof SettingsRoute + '/shop': typeof ShopRouteWithChildren + '/blog/$slug': typeof BlogSlugRoute + '/shop/$productId': typeof ShopProductIdRoute + '/blog/': typeof BlogIndexRoute + '/shop/': typeof ShopIndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/search': typeof SearchRoute + '/settings': typeof SettingsRoute + '/blog/$slug': typeof BlogSlugRoute + '/shop/$productId': typeof ShopProductIdRoute + '/blog': typeof BlogIndexRoute + '/shop': typeof ShopIndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/about': typeof AboutRoute + '/blog': typeof BlogRouteWithChildren + '/search': typeof SearchRoute + '/settings': typeof SettingsRoute + '/shop': typeof ShopRouteWithChildren + '/blog/$slug': typeof BlogSlugRoute + '/shop/$productId': typeof ShopProductIdRoute + '/blog/': typeof BlogIndexRoute + '/shop/': typeof ShopIndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/about' + | '/blog' + | '/search' + | '/settings' + | '/shop' + | '/blog/$slug' + | '/shop/$productId' + | '/blog/' + | '/shop/' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/about' + | '/search' + | '/settings' + | '/blog/$slug' + | '/shop/$productId' + | '/blog' + | '/shop' + id: + | '__root__' + | '/' + | '/about' + | '/blog' + | '/search' + | '/settings' + | '/shop' + | '/blog/$slug' + | '/shop/$productId' + | '/blog/' + | '/shop/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + AboutRoute: typeof AboutRoute + BlogRoute: typeof BlogRouteWithChildren + SearchRoute: typeof SearchRoute + SettingsRoute: typeof SettingsRoute + ShopRoute: typeof ShopRouteWithChildren +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } + '/blog': { + id: '/blog' + path: '/blog' + fullPath: '/blog' + preLoaderRoute: typeof BlogRouteImport + parentRoute: typeof rootRouteImport + } + '/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/' + path: '/' + fullPath: '/blog/' + preLoaderRoute: typeof BlogIndexRouteImport + parentRoute: typeof BlogRoute + } + '/blog/$slug': { + id: '/blog/$slug' + path: '/$slug' + fullPath: '/blog/$slug' + 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 + } + } +} + +interface BlogRouteChildren { + BlogSlugRoute: typeof BlogSlugRoute + BlogIndexRoute: typeof BlogIndexRoute +} + +const BlogRouteChildren: BlogRouteChildren = { + BlogSlugRoute: BlogSlugRoute, + BlogIndexRoute: BlogIndexRoute, +} + +const BlogRouteWithChildren = BlogRoute._addFileChildren(BlogRouteChildren) + +interface ShopRouteChildren { + ShopProductIdRoute: typeof ShopProductIdRoute + ShopIndexRoute: typeof ShopIndexRoute +} + +const ShopRouteChildren: ShopRouteChildren = { + ShopProductIdRoute: ShopProductIdRoute, + ShopIndexRoute: ShopIndexRoute, +} + +const ShopRouteWithChildren = ShopRoute._addFileChildren(ShopRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + AboutRoute: AboutRoute, + BlogRoute: BlogRouteWithChildren, + SearchRoute: SearchRoute, + SettingsRoute: SettingsRoute, + ShopRoute: ShopRouteWithChildren, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..5c2b7b52d0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/src/routes/__root.tsx @@ -0,0 +1,44 @@ +import * as Vue from 'vue' +import { Link, Outlet, createRootRoute } from '@tanstack/vue-router' + +const RootComponent = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + ) + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/about.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/about.tsx new file mode 100644 index 0000000000..254ecca29c --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/src/routes/about.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const AboutPage = Vue.defineComponent({ + setup() { + return () =>

About

+ }, +}) + +export const Route = createFileRoute('/about')({ + component: AboutPage, +}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/blog.$slug.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/blog.$slug.tsx new file mode 100644 index 0000000000..3b2e855a6e --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/src/routes/blog.$slug.tsx @@ -0,0 +1,18 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { articleData } from '../../../shared' + +const ArticlePage = Vue.defineComponent({ + setup() { + const article = Route.useLoaderData() + + return () => ( +
{`${article.value.title} (${article.value.words} words)`}
+ ) + }, +}) + +export const Route = createFileRoute('/blog/$slug')({ + loader: ({ params }) => articleData(params.slug), + component: ArticlePage, +}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/blog.index.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/blog.index.tsx new file mode 100644 index 0000000000..d3c2bd0305 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/src/routes/blog.index.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const BlogIndexPage = Vue.defineComponent({ + setup() { + return () =>

All articles

+ }, +}) + +export const Route = createFileRoute('/blog/')({ + component: BlogIndexPage, +}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/blog.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/blog.tsx new file mode 100644 index 0000000000..fe9532cc6f --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/src/routes/blog.tsx @@ -0,0 +1,19 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { blogContext } from '../../../shared' + +const BlogLayout = Vue.defineComponent({ + setup() { + return () => ( +
+

Blog

+ +
+ ) + }, +}) + +export const Route = createFileRoute('/blog')({ + beforeLoad: () => blogContext(), + component: BlogLayout, +}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/index.tsx new file mode 100644 index 0000000000..b0be4d78bb --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/src/routes/index.tsx @@ -0,0 +1,27 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { homeItems, readyTestId } from '../../../shared' + +const HomePage = Vue.defineComponent({ + setup() { + const items = Route.useLoaderData() + + return () => ( +
+

{`Home (${items.value.length} items)`}

+
    + {items.value.map((item) => ( +
  • {`${item.label}: ${item.score}`}
  • + ))} +
+
+ ) + }, +}) + +export const Route = createFileRoute('/')({ + loader: () => homeItems(), + component: HomePage, +}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/search.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/search.tsx new file mode 100644 index 0000000000..09fdb29c1e --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/src/routes/search.tsx @@ -0,0 +1,21 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { normalizePage, normalizeQuery } from '../../../shared' + +const SearchPage = Vue.defineComponent({ + setup() { + const search = Route.useSearch() + + return () => ( +

{`Results for "${search.value.q}" page ${search.value.page}`}

+ ) + }, +}) + +export const Route = createFileRoute('/search')({ + validateSearch: (search: Record) => ({ + q: normalizeQuery(search.q), + page: normalizePage(search.page), + }), + component: SearchPage, +}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/settings.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/settings.tsx new file mode 100644 index 0000000000..3fc0485606 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/src/routes/settings.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const SettingsPage = Vue.defineComponent({ + setup() { + return () =>

Settings

+ }, +}) + +export const Route = createFileRoute('/settings')({ + component: SettingsPage, +}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/shop.$productId.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/shop.$productId.tsx new file mode 100644 index 0000000000..897559599a --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/src/routes/shop.$productId.tsx @@ -0,0 +1,18 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { productData } from '../../../shared' + +const ProductPage = Vue.defineComponent({ + setup() { + const product = Route.useLoaderData() + + return () => ( +
{`${product.value.name}: ${product.value.price}`}
+ ) + }, +}) + +export const Route = createFileRoute('/shop/$productId')({ + loader: ({ params }) => productData(params.productId), + component: ProductPage, +}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/shop.index.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/shop.index.tsx new file mode 100644 index 0000000000..1040520f03 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/src/routes/shop.index.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const ShopIndexPage = Vue.defineComponent({ + setup() { + return () =>

All products

+ }, +}) + +export const Route = createFileRoute('/shop/')({ + component: ShopIndexPage, +}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routes/shop.tsx b/benchmarks/client-nav/scenarios/mount/vue/src/routes/shop.tsx new file mode 100644 index 0000000000..184807cfa0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/vue/src/routes/shop.tsx @@ -0,0 +1,19 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { shopContext } from '../../../shared' + +const ShopLayout = Vue.defineComponent({ + setup() { + return () => ( +
+

Shop

+ +
+ ) + }, +}) + +export const Route = createFileRoute('/shop')({ + beforeLoad: () => shopContext(), + component: ShopLayout, +}) diff --git a/benchmarks/client-nav/scenarios/mount/vue/tsconfig.json b/benchmarks/client-nav/scenarios/mount/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/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/mount/vue/vite.config.ts b/benchmarks/client-nav/scenarios/mount/vue/vite.config.ts new file mode 100644 index 0000000000..8d4005f339 --- /dev/null +++ b/benchmarks/client-nav/scenarios/mount/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 mount (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/react/project.json b/benchmarks/client-nav/scenarios/nested-params/react/project.json new file mode 100644 index 0000000000..800f8af9a8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-nested-params-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/nested-params/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/setup.ts b/benchmarks/client-nav/scenarios/nested-params/react/setup.ts new file mode 100644 index 0000000000..130583b190 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } 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, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts b/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts new file mode 100644 index 0000000000..fa5809c1fd --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/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-nested-params', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-nested-params 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/nested-params/react/speed.flame.ts b/benchmarks/client-nav/scenarios/nested-params/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/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/nested-params/react/src/main.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/main.tsx new file mode 100644 index 0000000000..5febd6f795 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/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/nested-params/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/nested-params/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..95d4b46623 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/routeTree.gen.ts @@ -0,0 +1,291 @@ +/* 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 LARouteImport } from './routes/l.$a' +import { Route as LABRouteImport } from './routes/l.$a.$b' +import { Route as LABCRouteImport } from './routes/l.$a.$b.$c' +import { Route as LABCDRouteImport } from './routes/l.$a.$b.$c.$d' +import { Route as LABCDERouteImport } from './routes/l.$a.$b.$c.$d.$e' +import { Route as LABCDEFRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f' +import { Route as LABCDEFGRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f.$g' +import { Route as LABCDEFGHRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f.$g.$h' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const LARoute = LARouteImport.update({ + id: '/l/$a', + path: '/l/$a', + getParentRoute: () => rootRouteImport, +} as any) +const LABRoute = LABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => LARoute, +} as any) +const LABCRoute = LABCRouteImport.update({ + id: '/$c', + path: '/$c', + getParentRoute: () => LABRoute, +} as any) +const LABCDRoute = LABCDRouteImport.update({ + id: '/$d', + path: '/$d', + getParentRoute: () => LABCRoute, +} as any) +const LABCDERoute = LABCDERouteImport.update({ + id: '/$e', + path: '/$e', + getParentRoute: () => LABCDRoute, +} as any) +const LABCDEFRoute = LABCDEFRouteImport.update({ + id: '/$f', + path: '/$f', + getParentRoute: () => LABCDERoute, +} as any) +const LABCDEFGRoute = LABCDEFGRouteImport.update({ + id: '/$g', + path: '/$g', + getParentRoute: () => LABCDEFRoute, +} as any) +const LABCDEFGHRoute = LABCDEFGHRouteImport.update({ + id: '/$h', + path: '/$h', + getParentRoute: () => LABCDEFGRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/l/$a': typeof LARouteWithChildren + '/l/$a/$b': typeof LABRouteWithChildren + '/l/$a/$b/$c': typeof LABCRouteWithChildren + '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren + '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren + '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/l/$a': typeof LARouteWithChildren + '/l/$a/$b': typeof LABRouteWithChildren + '/l/$a/$b/$c': typeof LABCRouteWithChildren + '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren + '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren + '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/l/$a': typeof LARouteWithChildren + '/l/$a/$b': typeof LABRouteWithChildren + '/l/$a/$b/$c': typeof LABCRouteWithChildren + '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren + '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren + '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/l/$a' + | '/l/$a/$b' + | '/l/$a/$b/$c' + | '/l/$a/$b/$c/$d' + | '/l/$a/$b/$c/$d/$e' + | '/l/$a/$b/$c/$d/$e/$f' + | '/l/$a/$b/$c/$d/$e/$f/$g' + | '/l/$a/$b/$c/$d/$e/$f/$g/$h' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/l/$a' + | '/l/$a/$b' + | '/l/$a/$b/$c' + | '/l/$a/$b/$c/$d' + | '/l/$a/$b/$c/$d/$e' + | '/l/$a/$b/$c/$d/$e/$f' + | '/l/$a/$b/$c/$d/$e/$f/$g' + | '/l/$a/$b/$c/$d/$e/$f/$g/$h' + id: + | '__root__' + | '/' + | '/l/$a' + | '/l/$a/$b' + | '/l/$a/$b/$c' + | '/l/$a/$b/$c/$d' + | '/l/$a/$b/$c/$d/$e' + | '/l/$a/$b/$c/$d/$e/$f' + | '/l/$a/$b/$c/$d/$e/$f/$g' + | '/l/$a/$b/$c/$d/$e/$f/$g/$h' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + LARoute: typeof LARouteWithChildren +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/l/$a': { + id: '/l/$a' + path: '/l/$a' + fullPath: '/l/$a' + preLoaderRoute: typeof LARouteImport + parentRoute: typeof rootRouteImport + } + '/l/$a/$b': { + id: '/l/$a/$b' + path: '/$b' + fullPath: '/l/$a/$b' + preLoaderRoute: typeof LABRouteImport + parentRoute: typeof LARoute + } + '/l/$a/$b/$c': { + id: '/l/$a/$b/$c' + path: '/$c' + fullPath: '/l/$a/$b/$c' + preLoaderRoute: typeof LABCRouteImport + parentRoute: typeof LABRoute + } + '/l/$a/$b/$c/$d': { + id: '/l/$a/$b/$c/$d' + path: '/$d' + fullPath: '/l/$a/$b/$c/$d' + preLoaderRoute: typeof LABCDRouteImport + parentRoute: typeof LABCRoute + } + '/l/$a/$b/$c/$d/$e': { + id: '/l/$a/$b/$c/$d/$e' + path: '/$e' + fullPath: '/l/$a/$b/$c/$d/$e' + preLoaderRoute: typeof LABCDERouteImport + parentRoute: typeof LABCDRoute + } + '/l/$a/$b/$c/$d/$e/$f': { + id: '/l/$a/$b/$c/$d/$e/$f' + path: '/$f' + fullPath: '/l/$a/$b/$c/$d/$e/$f' + preLoaderRoute: typeof LABCDEFRouteImport + parentRoute: typeof LABCDERoute + } + '/l/$a/$b/$c/$d/$e/$f/$g': { + id: '/l/$a/$b/$c/$d/$e/$f/$g' + path: '/$g' + fullPath: '/l/$a/$b/$c/$d/$e/$f/$g' + preLoaderRoute: typeof LABCDEFGRouteImport + parentRoute: typeof LABCDEFRoute + } + '/l/$a/$b/$c/$d/$e/$f/$g/$h': { + id: '/l/$a/$b/$c/$d/$e/$f/$g/$h' + path: '/$h' + fullPath: '/l/$a/$b/$c/$d/$e/$f/$g/$h' + preLoaderRoute: typeof LABCDEFGHRouteImport + parentRoute: typeof LABCDEFGRoute + } + } +} + +interface LABCDEFGRouteChildren { + LABCDEFGHRoute: typeof LABCDEFGHRoute +} + +const LABCDEFGRouteChildren: LABCDEFGRouteChildren = { + LABCDEFGHRoute: LABCDEFGHRoute, +} + +const LABCDEFGRouteWithChildren = LABCDEFGRoute._addFileChildren( + LABCDEFGRouteChildren, +) + +interface LABCDEFRouteChildren { + LABCDEFGRoute: typeof LABCDEFGRouteWithChildren +} + +const LABCDEFRouteChildren: LABCDEFRouteChildren = { + LABCDEFGRoute: LABCDEFGRouteWithChildren, +} + +const LABCDEFRouteWithChildren = + LABCDEFRoute._addFileChildren(LABCDEFRouteChildren) + +interface LABCDERouteChildren { + LABCDEFRoute: typeof LABCDEFRouteWithChildren +} + +const LABCDERouteChildren: LABCDERouteChildren = { + LABCDEFRoute: LABCDEFRouteWithChildren, +} + +const LABCDERouteWithChildren = + LABCDERoute._addFileChildren(LABCDERouteChildren) + +interface LABCDRouteChildren { + LABCDERoute: typeof LABCDERouteWithChildren +} + +const LABCDRouteChildren: LABCDRouteChildren = { + LABCDERoute: LABCDERouteWithChildren, +} + +const LABCDRouteWithChildren = LABCDRoute._addFileChildren(LABCDRouteChildren) + +interface LABCRouteChildren { + LABCDRoute: typeof LABCDRouteWithChildren +} + +const LABCRouteChildren: LABCRouteChildren = { + LABCDRoute: LABCDRouteWithChildren, +} + +const LABCRouteWithChildren = LABCRoute._addFileChildren(LABCRouteChildren) + +interface LABRouteChildren { + LABCRoute: typeof LABCRouteWithChildren +} + +const LABRouteChildren: LABRouteChildren = { + LABCRoute: LABCRouteWithChildren, +} + +const LABRouteWithChildren = LABRoute._addFileChildren(LABRouteChildren) + +interface LARouteChildren { + LABRoute: typeof LABRouteWithChildren +} + +const LARouteChildren: LARouteChildren = { + LABRoute: LABRouteWithChildren, +} + +const LARouteWithChildren = LARoute._addFileChildren(LARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + LARoute: LARouteWithChildren, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/__root.tsx new file mode 100644 index 0000000000..ef2c7b1b18 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/__root.tsx @@ -0,0 +1,50 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/react-router' +import { leafParamSets, midParams } from '../../../shared' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/index.tsx new file mode 100644 index 0000000000..24e856ea15 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return
home
+} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx new file mode 100644 index 0000000000..9789e28040 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx @@ -0,0 +1,63 @@ +import { createFileRoute } from '@tanstack/react-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f/$g/$h')({ + params: { + parse: (params) => ({ ...params, h: normalizeParam(params.h) }), + stringify: (params) => ({ ...params, h: String(params.h) }), + }, + beforeLoad: ({ params }) => ({ ctxH: smallHash(params.h) }), + component: LevelH, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.h) }) + void value + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.h}:2`), + }) + void value + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxH }) + void value + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxH * 31 + 7) >>> 0, + }) + void value + return null +} + +function LevelH() { + const params = Route.useParams() + return ( + <> + + + + +
+ {[ + params.a, + params.b, + params.c, + params.d, + params.e, + params.f, + params.g, + params.h, + ].join('.')} +
+ + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx new file mode 100644 index 0000000000..650b32ce96 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx @@ -0,0 +1,51 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f/$g')({ + params: { + parse: (params) => ({ ...params, g: normalizeParam(params.g) }), + stringify: (params) => ({ ...params, g: String(params.g) }), + }, + beforeLoad: ({ params }) => ({ ctxG: smallHash(params.g) }), + component: LevelG, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.g) }) + void value + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.g}:2`), + }) + void value + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxG }) + void value + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxG * 31 + 7) >>> 0, + }) + void value + return null +} + +function LevelG() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.tsx new file mode 100644 index 0000000000..ca18e3ccd2 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.$f.tsx @@ -0,0 +1,51 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f')({ + params: { + parse: (params) => ({ ...params, f: normalizeParam(params.f) }), + stringify: (params) => ({ ...params, f: String(params.f) }), + }, + beforeLoad: ({ params }) => ({ ctxF: smallHash(params.f) }), + component: LevelF, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.f) }) + void value + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.f}:2`), + }) + void value + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxF }) + void value + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxF * 31 + 7) >>> 0, + }) + void value + return null +} + +function LevelF() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.tsx new file mode 100644 index 0000000000..782c1808c7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.$e.tsx @@ -0,0 +1,51 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e')({ + params: { + parse: (params) => ({ ...params, e: normalizeParam(params.e) }), + stringify: (params) => ({ ...params, e: String(params.e) }), + }, + beforeLoad: ({ params }) => ({ ctxE: smallHash(params.e) }), + component: LevelE, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.e) }) + void value + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.e}:2`), + }) + void value + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxE }) + void value + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxE * 31 + 7) >>> 0, + }) + void value + return null +} + +function LevelE() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.tsx new file mode 100644 index 0000000000..a874bbcb63 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.$d.tsx @@ -0,0 +1,55 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c/$d')({ + params: { + parse: (params) => ({ ...params, d: normalizeParam(params.d) }), + stringify: (params) => ({ ...params, d: String(params.d) }), + }, + beforeLoad: ({ params }) => ({ ctxD: smallHash(params.d) }), + component: LevelD, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.d) }) + void value + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.d}:2`), + }) + void value + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxD }) + void value + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxD * 31 + 7) >>> 0, + }) + void value + return null +} + +function LevelD() { + const params = Route.useParams() + return ( + <> + + + + +
+ {[params.a, params.b, params.c, params.d].join('.')} +
+ + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.tsx new file mode 100644 index 0000000000..94aba79453 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.$c.tsx @@ -0,0 +1,51 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c')({ + params: { + parse: (params) => ({ ...params, c: normalizeParam(params.c) }), + stringify: (params) => ({ ...params, c: String(params.c) }), + }, + beforeLoad: ({ params }) => ({ ctxC: smallHash(params.c) }), + component: LevelC, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.c) }) + void value + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.c}:2`), + }) + void value + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxC }) + void value + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxC * 31 + 7) >>> 0, + }) + void value + return null +} + +function LevelC() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.tsx new file mode 100644 index 0000000000..1960b68276 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.$b.tsx @@ -0,0 +1,51 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b')({ + params: { + parse: (params) => ({ ...params, b: normalizeParam(params.b) }), + stringify: (params) => ({ ...params, b: String(params.b) }), + }, + beforeLoad: ({ params }) => ({ ctxB: smallHash(params.b) }), + component: LevelB, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.b) }) + void value + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.b}:2`), + }) + void value + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxB }) + void value + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxB * 31 + 7) >>> 0, + }) + void value + return null +} + +function LevelB() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.tsx b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.tsx new file mode 100644 index 0000000000..85d1de6f68 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/react/src/routes/l.$a.tsx @@ -0,0 +1,51 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a')({ + params: { + parse: (params) => ({ ...params, a: normalizeParam(params.a) }), + stringify: (params) => ({ ...params, a: String(params.a) }), + }, + beforeLoad: ({ params }) => ({ ctxA: smallHash(params.a) }), + component: LevelA, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.a) }) + void value + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.a}:2`), + }) + void value + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxA }) + void value + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxA * 31 + 7) >>> 0, + }) + void value + return null +} + +function LevelA() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/react/tsconfig.json b/benchmarks/client-nav/scenarios/nested-params/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/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/nested-params/react/vite.config.ts b/benchmarks/client-nav/scenarios/nested-params/react/vite.config.ts new file mode 100644 index 0000000000..a99060bf1c --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/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 nested-params (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/shared.ts b/benchmarks/client-nav/scenarios/nested-params/shared.ts new file mode 100644 index 0000000000..06c968bb18 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/shared.ts @@ -0,0 +1,143 @@ +/** + * Shared definition of the `nested-params` scenario: deep dynamic nesting with + * per-level params.parse/stringify, beforeLoad context accumulation, and + * useParams/useRouteContext subscribers at every level. The three framework + * apps consume these builders so the workload is identical modulo the + * rendering layer. + */ + +export interface LeafParams { + a: string + b: string + c: string + d: string + e: string + f: string + g: string + h: string +} + +// Several values need percent-encoding in the URL (spaces, `&`, `%`, `+`, +// unicode) so every navigation exercises the param encode/decode paths, not +// just plain-ASCII interpolation. +const baseParams: LeafParams = { + a: 'alpha', + b: 'bravo & co', + c: 'charlie 100%', + d: 'delta', + e: 'écho-café', + f: 'foxtrot+one', + g: 'golf', + h: 'hôtel', +} + +/** + * set 0: base; set 1: only the deepest param differs (only the leaf re-runs); + * set 2: a mid param differs (levels d..h re-run); set 3: the top param + * differs (every level re-runs). + */ +export const leafParamSets: ReadonlyArray = [ + baseParams, + { ...baseParams, h: 'hilton' }, + { ...baseParams, d: 'dover' }, + { ...baseParams, a: 'axel' }, +] + +export const midParams = { + a: baseParams.a, + b: baseParams.b, + c: baseParams.c, + d: baseParams.d, +} + +export function normalizeParam(value: unknown) { + const raw = String(value) + return raw.length > 24 ? raw.slice(0, 24) : raw +} + +export function smallHash(value: string | number) { + const input = `${value}` + let hash = 5381 + for (let index = 0; index < input.length; index++) { + hash = ((hash * 33) ^ input.charCodeAt(index)) >>> 0 + } + return hash +} + +export function leafMarker(params: LeafParams) { + return [ + params.a, + params.b, + params.c, + params.d, + params.e, + params.f, + params.g, + params.h, + ] + .map(normalizeParam) + .join('.') +} + +export function midMarker(params: typeof midParams) { + return [params.a, params.b, params.c, params.d].map(normalizeParam).join('.') +} + +export const steps = [ + 'leaf-1', + 'leaf-2', + 'leaf-3', + 'leaf-4', + 'mid-4', + 'home', +] as const + +function requireText(container: HTMLElement, testId: string, expected: string) { + const element = container.querySelector(`[data-testid="${testId}"]`) + if (!element || element.textContent !== expected) { + throw new Error( + `Expected [data-testid="${testId}"] to render "${expected}", received "${element?.textContent ?? ''}"`, + ) + } +} + +function requireAbsent(container: HTMLElement, testId: string) { + if (container.querySelector(`[data-testid="${testId}"]`)) { + throw new Error(`Expected [data-testid="${testId}"] to be absent`) + } +} + +export function assertStepResult(stepIndex: number, container: HTMLElement) { + const step = steps[stepIndex % steps.length]! + switch (step) { + case 'leaf-1': + requireText(container, 'leaf-state', leafMarker(leafParamSets[0]!)) + break + case 'leaf-2': + requireText(container, 'leaf-state', leafMarker(leafParamSets[1]!)) + break + case 'leaf-3': + requireText(container, 'leaf-state', leafMarker(leafParamSets[2]!)) + break + case 'leaf-4': + requireText(container, 'leaf-state', leafMarker(leafParamSets[3]!)) + break + case 'mid-4': + requireAbsent(container, 'leaf-state') + requireText(container, 'mid-state', midMarker(midParams)) + break + case 'home': + requireAbsent(container, 'leaf-state') + requireAbsent(container, 'mid-state') + break + } +} + +// Three laps through the 6-step sequence per benchmark iteration. +export const ticksPerIteration = 18 + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/project.json b/benchmarks/client-nav/scenarios/nested-params/solid/project.json new file mode 100644 index 0000000000..eb0b91bd6c --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-nested-params-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/nested-params/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/setup.ts b/benchmarks/client-nav/scenarios/nested-params/solid/setup.ts new file mode 100644 index 0000000000..6a46971603 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } 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, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts new file mode 100644 index 0000000000..2c64d9a221 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/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-nested-params', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-nested-params 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/nested-params/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/nested-params/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/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/nested-params/solid/src/main.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/main.tsx new file mode 100644 index 0000000000..fa9d239418 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/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/nested-params/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/nested-params/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..9065c9294f --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/routeTree.gen.ts @@ -0,0 +1,291 @@ +/* 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 LARouteImport } from './routes/l.$a' +import { Route as LABRouteImport } from './routes/l.$a.$b' +import { Route as LABCRouteImport } from './routes/l.$a.$b.$c' +import { Route as LABCDRouteImport } from './routes/l.$a.$b.$c.$d' +import { Route as LABCDERouteImport } from './routes/l.$a.$b.$c.$d.$e' +import { Route as LABCDEFRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f' +import { Route as LABCDEFGRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f.$g' +import { Route as LABCDEFGHRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f.$g.$h' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const LARoute = LARouteImport.update({ + id: '/l/$a', + path: '/l/$a', + getParentRoute: () => rootRouteImport, +} as any) +const LABRoute = LABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => LARoute, +} as any) +const LABCRoute = LABCRouteImport.update({ + id: '/$c', + path: '/$c', + getParentRoute: () => LABRoute, +} as any) +const LABCDRoute = LABCDRouteImport.update({ + id: '/$d', + path: '/$d', + getParentRoute: () => LABCRoute, +} as any) +const LABCDERoute = LABCDERouteImport.update({ + id: '/$e', + path: '/$e', + getParentRoute: () => LABCDRoute, +} as any) +const LABCDEFRoute = LABCDEFRouteImport.update({ + id: '/$f', + path: '/$f', + getParentRoute: () => LABCDERoute, +} as any) +const LABCDEFGRoute = LABCDEFGRouteImport.update({ + id: '/$g', + path: '/$g', + getParentRoute: () => LABCDEFRoute, +} as any) +const LABCDEFGHRoute = LABCDEFGHRouteImport.update({ + id: '/$h', + path: '/$h', + getParentRoute: () => LABCDEFGRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/l/$a': typeof LARouteWithChildren + '/l/$a/$b': typeof LABRouteWithChildren + '/l/$a/$b/$c': typeof LABCRouteWithChildren + '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren + '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren + '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/l/$a': typeof LARouteWithChildren + '/l/$a/$b': typeof LABRouteWithChildren + '/l/$a/$b/$c': typeof LABCRouteWithChildren + '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren + '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren + '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/l/$a': typeof LARouteWithChildren + '/l/$a/$b': typeof LABRouteWithChildren + '/l/$a/$b/$c': typeof LABCRouteWithChildren + '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren + '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren + '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/l/$a' + | '/l/$a/$b' + | '/l/$a/$b/$c' + | '/l/$a/$b/$c/$d' + | '/l/$a/$b/$c/$d/$e' + | '/l/$a/$b/$c/$d/$e/$f' + | '/l/$a/$b/$c/$d/$e/$f/$g' + | '/l/$a/$b/$c/$d/$e/$f/$g/$h' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/l/$a' + | '/l/$a/$b' + | '/l/$a/$b/$c' + | '/l/$a/$b/$c/$d' + | '/l/$a/$b/$c/$d/$e' + | '/l/$a/$b/$c/$d/$e/$f' + | '/l/$a/$b/$c/$d/$e/$f/$g' + | '/l/$a/$b/$c/$d/$e/$f/$g/$h' + id: + | '__root__' + | '/' + | '/l/$a' + | '/l/$a/$b' + | '/l/$a/$b/$c' + | '/l/$a/$b/$c/$d' + | '/l/$a/$b/$c/$d/$e' + | '/l/$a/$b/$c/$d/$e/$f' + | '/l/$a/$b/$c/$d/$e/$f/$g' + | '/l/$a/$b/$c/$d/$e/$f/$g/$h' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + LARoute: typeof LARouteWithChildren +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/l/$a': { + id: '/l/$a' + path: '/l/$a' + fullPath: '/l/$a' + preLoaderRoute: typeof LARouteImport + parentRoute: typeof rootRouteImport + } + '/l/$a/$b': { + id: '/l/$a/$b' + path: '/$b' + fullPath: '/l/$a/$b' + preLoaderRoute: typeof LABRouteImport + parentRoute: typeof LARoute + } + '/l/$a/$b/$c': { + id: '/l/$a/$b/$c' + path: '/$c' + fullPath: '/l/$a/$b/$c' + preLoaderRoute: typeof LABCRouteImport + parentRoute: typeof LABRoute + } + '/l/$a/$b/$c/$d': { + id: '/l/$a/$b/$c/$d' + path: '/$d' + fullPath: '/l/$a/$b/$c/$d' + preLoaderRoute: typeof LABCDRouteImport + parentRoute: typeof LABCRoute + } + '/l/$a/$b/$c/$d/$e': { + id: '/l/$a/$b/$c/$d/$e' + path: '/$e' + fullPath: '/l/$a/$b/$c/$d/$e' + preLoaderRoute: typeof LABCDERouteImport + parentRoute: typeof LABCDRoute + } + '/l/$a/$b/$c/$d/$e/$f': { + id: '/l/$a/$b/$c/$d/$e/$f' + path: '/$f' + fullPath: '/l/$a/$b/$c/$d/$e/$f' + preLoaderRoute: typeof LABCDEFRouteImport + parentRoute: typeof LABCDERoute + } + '/l/$a/$b/$c/$d/$e/$f/$g': { + id: '/l/$a/$b/$c/$d/$e/$f/$g' + path: '/$g' + fullPath: '/l/$a/$b/$c/$d/$e/$f/$g' + preLoaderRoute: typeof LABCDEFGRouteImport + parentRoute: typeof LABCDEFRoute + } + '/l/$a/$b/$c/$d/$e/$f/$g/$h': { + id: '/l/$a/$b/$c/$d/$e/$f/$g/$h' + path: '/$h' + fullPath: '/l/$a/$b/$c/$d/$e/$f/$g/$h' + preLoaderRoute: typeof LABCDEFGHRouteImport + parentRoute: typeof LABCDEFGRoute + } + } +} + +interface LABCDEFGRouteChildren { + LABCDEFGHRoute: typeof LABCDEFGHRoute +} + +const LABCDEFGRouteChildren: LABCDEFGRouteChildren = { + LABCDEFGHRoute: LABCDEFGHRoute, +} + +const LABCDEFGRouteWithChildren = LABCDEFGRoute._addFileChildren( + LABCDEFGRouteChildren, +) + +interface LABCDEFRouteChildren { + LABCDEFGRoute: typeof LABCDEFGRouteWithChildren +} + +const LABCDEFRouteChildren: LABCDEFRouteChildren = { + LABCDEFGRoute: LABCDEFGRouteWithChildren, +} + +const LABCDEFRouteWithChildren = + LABCDEFRoute._addFileChildren(LABCDEFRouteChildren) + +interface LABCDERouteChildren { + LABCDEFRoute: typeof LABCDEFRouteWithChildren +} + +const LABCDERouteChildren: LABCDERouteChildren = { + LABCDEFRoute: LABCDEFRouteWithChildren, +} + +const LABCDERouteWithChildren = + LABCDERoute._addFileChildren(LABCDERouteChildren) + +interface LABCDRouteChildren { + LABCDERoute: typeof LABCDERouteWithChildren +} + +const LABCDRouteChildren: LABCDRouteChildren = { + LABCDERoute: LABCDERouteWithChildren, +} + +const LABCDRouteWithChildren = LABCDRoute._addFileChildren(LABCDRouteChildren) + +interface LABCRouteChildren { + LABCDRoute: typeof LABCDRouteWithChildren +} + +const LABCRouteChildren: LABCRouteChildren = { + LABCDRoute: LABCDRouteWithChildren, +} + +const LABCRouteWithChildren = LABCRoute._addFileChildren(LABCRouteChildren) + +interface LABRouteChildren { + LABCRoute: typeof LABCRouteWithChildren +} + +const LABRouteChildren: LABRouteChildren = { + LABCRoute: LABCRouteWithChildren, +} + +const LABRouteWithChildren = LABRoute._addFileChildren(LABRouteChildren) + +interface LARouteChildren { + LABRoute: typeof LABRouteWithChildren +} + +const LARouteChildren: LARouteChildren = { + LABRoute: LABRouteWithChildren, +} + +const LARouteWithChildren = LARoute._addFileChildren(LARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + LARoute: LARouteWithChildren, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..6fe7ab3e3d --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/__root.tsx @@ -0,0 +1,50 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/solid-router' +import { leafParamSets, midParams } from '../../../shared' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/index.tsx new file mode 100644 index 0000000000..cc46764de5 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return
home
+} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx new file mode 100644 index 0000000000..7dc55db0e4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx @@ -0,0 +1,72 @@ +import { createRenderEffect } from 'solid-js' +import { createFileRoute } from '@tanstack/solid-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f/$g/$h')({ + params: { + parse: (params) => ({ ...params, h: normalizeParam(params.h) }), + stringify: (params) => ({ ...params, h: String(params.h) }), + }, + beforeLoad: ({ params }) => ({ ctxH: smallHash(params.h) }), + component: LevelH, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.h) }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.h}:2`), + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxH }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxH * 31 + 7) >>> 0, + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function LevelH() { + const params = Route.useParams() + return ( + <> + + + + +
+ {[ + params().a, + params().b, + params().c, + params().d, + params().e, + params().f, + params().g, + params().h, + ].join('.')} +
+ + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx new file mode 100644 index 0000000000..d9c6c9429b --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx @@ -0,0 +1,60 @@ +import { createRenderEffect } from 'solid-js' +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f/$g')({ + params: { + parse: (params) => ({ ...params, g: normalizeParam(params.g) }), + stringify: (params) => ({ ...params, g: String(params.g) }), + }, + beforeLoad: ({ params }) => ({ ctxG: smallHash(params.g) }), + component: LevelG, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.g) }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.g}:2`), + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxG }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxG * 31 + 7) >>> 0, + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function LevelG() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.tsx new file mode 100644 index 0000000000..010f89bc4d --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.$f.tsx @@ -0,0 +1,60 @@ +import { createRenderEffect } from 'solid-js' +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f')({ + params: { + parse: (params) => ({ ...params, f: normalizeParam(params.f) }), + stringify: (params) => ({ ...params, f: String(params.f) }), + }, + beforeLoad: ({ params }) => ({ ctxF: smallHash(params.f) }), + component: LevelF, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.f) }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.f}:2`), + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxF }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxF * 31 + 7) >>> 0, + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function LevelF() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.tsx new file mode 100644 index 0000000000..08c107f0c6 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.$e.tsx @@ -0,0 +1,60 @@ +import { createRenderEffect } from 'solid-js' +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e')({ + params: { + parse: (params) => ({ ...params, e: normalizeParam(params.e) }), + stringify: (params) => ({ ...params, e: String(params.e) }), + }, + beforeLoad: ({ params }) => ({ ctxE: smallHash(params.e) }), + component: LevelE, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.e) }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.e}:2`), + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxE }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxE * 31 + 7) >>> 0, + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function LevelE() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.tsx new file mode 100644 index 0000000000..1b64edd58b --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.$d.tsx @@ -0,0 +1,64 @@ +import { createRenderEffect } from 'solid-js' +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c/$d')({ + params: { + parse: (params) => ({ ...params, d: normalizeParam(params.d) }), + stringify: (params) => ({ ...params, d: String(params.d) }), + }, + beforeLoad: ({ params }) => ({ ctxD: smallHash(params.d) }), + component: LevelD, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.d) }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.d}:2`), + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxD }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxD * 31 + 7) >>> 0, + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function LevelD() { + const params = Route.useParams() + return ( + <> + + + + +
+ {[params().a, params().b, params().c, params().d].join('.')} +
+ + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.tsx new file mode 100644 index 0000000000..e509ea82c6 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.$c.tsx @@ -0,0 +1,60 @@ +import { createRenderEffect } from 'solid-js' +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b/$c')({ + params: { + parse: (params) => ({ ...params, c: normalizeParam(params.c) }), + stringify: (params) => ({ ...params, c: String(params.c) }), + }, + beforeLoad: ({ params }) => ({ ctxC: smallHash(params.c) }), + component: LevelC, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.c) }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.c}:2`), + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxC }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxC * 31 + 7) >>> 0, + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function LevelC() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.tsx new file mode 100644 index 0000000000..ada853b845 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.$b.tsx @@ -0,0 +1,60 @@ +import { createRenderEffect } from 'solid-js' +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a/$b')({ + params: { + parse: (params) => ({ ...params, b: normalizeParam(params.b) }), + stringify: (params) => ({ ...params, b: String(params.b) }), + }, + beforeLoad: ({ params }) => ({ ctxB: smallHash(params.b) }), + component: LevelB, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.b) }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.b}:2`), + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxB }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxB * 31 + 7) >>> 0, + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function LevelB() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.tsx b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.tsx new file mode 100644 index 0000000000..5ecf004fae --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/solid/src/routes/l.$a.tsx @@ -0,0 +1,60 @@ +import { createRenderEffect } from 'solid-js' +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { normalizeParam, smallHash } from '../../../shared' + +export const Route = createFileRoute('/l/$a')({ + params: { + parse: (params) => ({ ...params, a: normalizeParam(params.a) }), + stringify: (params) => ({ ...params, a: String(params.a) }), + }, + beforeLoad: ({ params }) => ({ ctxA: smallHash(params.a) }), + component: LevelA, +}) + +function ParamsSubscriberOne() { + const value = Route.useParams({ select: (params) => smallHash(params.a) }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ParamsSubscriberTwo() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.a}:2`), + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberOne() { + const value = Route.useRouteContext({ select: (context) => context.ctxA }) + createRenderEffect(() => { + void value() + }) + return null +} + +function ContextSubscriberTwo() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxA * 31 + 7) >>> 0, + }) + createRenderEffect(() => { + void value() + }) + return null +} + +function LevelA() { + return ( + <> + + + + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/tsconfig.json b/benchmarks/client-nav/scenarios/nested-params/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/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/nested-params/solid/vite.config.ts b/benchmarks/client-nav/scenarios/nested-params/solid/vite.config.ts new file mode 100644 index 0000000000..9897e2c199 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/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 nested-params (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/project.json b/benchmarks/client-nav/scenarios/nested-params/vue/project.json new file mode 100644 index 0000000000..83c234382c --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-nested-params-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/nested-params/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/setup.ts b/benchmarks/client-nav/scenarios/nested-params/vue/setup.ts new file mode 100644 index 0000000000..97b74b3892 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } 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, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts new file mode 100644 index 0000000000..bd3e82e070 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/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-nested-params', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-nested-params 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/nested-params/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/nested-params/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/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/nested-params/vue/src/main.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/main.tsx new file mode 100644 index 0000000000..cae9b54f1d --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/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/nested-params/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/nested-params/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..a7d1049b49 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/routeTree.gen.ts @@ -0,0 +1,291 @@ +/* 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 LARouteImport } from './routes/l.$a' +import { Route as LABRouteImport } from './routes/l.$a.$b' +import { Route as LABCRouteImport } from './routes/l.$a.$b.$c' +import { Route as LABCDRouteImport } from './routes/l.$a.$b.$c.$d' +import { Route as LABCDERouteImport } from './routes/l.$a.$b.$c.$d.$e' +import { Route as LABCDEFRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f' +import { Route as LABCDEFGRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f.$g' +import { Route as LABCDEFGHRouteImport } from './routes/l.$a.$b.$c.$d.$e.$f.$g.$h' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const LARoute = LARouteImport.update({ + id: '/l/$a', + path: '/l/$a', + getParentRoute: () => rootRouteImport, +} as any) +const LABRoute = LABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => LARoute, +} as any) +const LABCRoute = LABCRouteImport.update({ + id: '/$c', + path: '/$c', + getParentRoute: () => LABRoute, +} as any) +const LABCDRoute = LABCDRouteImport.update({ + id: '/$d', + path: '/$d', + getParentRoute: () => LABCRoute, +} as any) +const LABCDERoute = LABCDERouteImport.update({ + id: '/$e', + path: '/$e', + getParentRoute: () => LABCDRoute, +} as any) +const LABCDEFRoute = LABCDEFRouteImport.update({ + id: '/$f', + path: '/$f', + getParentRoute: () => LABCDERoute, +} as any) +const LABCDEFGRoute = LABCDEFGRouteImport.update({ + id: '/$g', + path: '/$g', + getParentRoute: () => LABCDEFRoute, +} as any) +const LABCDEFGHRoute = LABCDEFGHRouteImport.update({ + id: '/$h', + path: '/$h', + getParentRoute: () => LABCDEFGRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/l/$a': typeof LARouteWithChildren + '/l/$a/$b': typeof LABRouteWithChildren + '/l/$a/$b/$c': typeof LABCRouteWithChildren + '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren + '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren + '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/l/$a': typeof LARouteWithChildren + '/l/$a/$b': typeof LABRouteWithChildren + '/l/$a/$b/$c': typeof LABCRouteWithChildren + '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren + '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren + '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/l/$a': typeof LARouteWithChildren + '/l/$a/$b': typeof LABRouteWithChildren + '/l/$a/$b/$c': typeof LABCRouteWithChildren + '/l/$a/$b/$c/$d': typeof LABCDRouteWithChildren + '/l/$a/$b/$c/$d/$e': typeof LABCDERouteWithChildren + '/l/$a/$b/$c/$d/$e/$f': typeof LABCDEFRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g': typeof LABCDEFGRouteWithChildren + '/l/$a/$b/$c/$d/$e/$f/$g/$h': typeof LABCDEFGHRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/l/$a' + | '/l/$a/$b' + | '/l/$a/$b/$c' + | '/l/$a/$b/$c/$d' + | '/l/$a/$b/$c/$d/$e' + | '/l/$a/$b/$c/$d/$e/$f' + | '/l/$a/$b/$c/$d/$e/$f/$g' + | '/l/$a/$b/$c/$d/$e/$f/$g/$h' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/l/$a' + | '/l/$a/$b' + | '/l/$a/$b/$c' + | '/l/$a/$b/$c/$d' + | '/l/$a/$b/$c/$d/$e' + | '/l/$a/$b/$c/$d/$e/$f' + | '/l/$a/$b/$c/$d/$e/$f/$g' + | '/l/$a/$b/$c/$d/$e/$f/$g/$h' + id: + | '__root__' + | '/' + | '/l/$a' + | '/l/$a/$b' + | '/l/$a/$b/$c' + | '/l/$a/$b/$c/$d' + | '/l/$a/$b/$c/$d/$e' + | '/l/$a/$b/$c/$d/$e/$f' + | '/l/$a/$b/$c/$d/$e/$f/$g' + | '/l/$a/$b/$c/$d/$e/$f/$g/$h' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + LARoute: typeof LARouteWithChildren +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/l/$a': { + id: '/l/$a' + path: '/l/$a' + fullPath: '/l/$a' + preLoaderRoute: typeof LARouteImport + parentRoute: typeof rootRouteImport + } + '/l/$a/$b': { + id: '/l/$a/$b' + path: '/$b' + fullPath: '/l/$a/$b' + preLoaderRoute: typeof LABRouteImport + parentRoute: typeof LARoute + } + '/l/$a/$b/$c': { + id: '/l/$a/$b/$c' + path: '/$c' + fullPath: '/l/$a/$b/$c' + preLoaderRoute: typeof LABCRouteImport + parentRoute: typeof LABRoute + } + '/l/$a/$b/$c/$d': { + id: '/l/$a/$b/$c/$d' + path: '/$d' + fullPath: '/l/$a/$b/$c/$d' + preLoaderRoute: typeof LABCDRouteImport + parentRoute: typeof LABCRoute + } + '/l/$a/$b/$c/$d/$e': { + id: '/l/$a/$b/$c/$d/$e' + path: '/$e' + fullPath: '/l/$a/$b/$c/$d/$e' + preLoaderRoute: typeof LABCDERouteImport + parentRoute: typeof LABCDRoute + } + '/l/$a/$b/$c/$d/$e/$f': { + id: '/l/$a/$b/$c/$d/$e/$f' + path: '/$f' + fullPath: '/l/$a/$b/$c/$d/$e/$f' + preLoaderRoute: typeof LABCDEFRouteImport + parentRoute: typeof LABCDERoute + } + '/l/$a/$b/$c/$d/$e/$f/$g': { + id: '/l/$a/$b/$c/$d/$e/$f/$g' + path: '/$g' + fullPath: '/l/$a/$b/$c/$d/$e/$f/$g' + preLoaderRoute: typeof LABCDEFGRouteImport + parentRoute: typeof LABCDEFRoute + } + '/l/$a/$b/$c/$d/$e/$f/$g/$h': { + id: '/l/$a/$b/$c/$d/$e/$f/$g/$h' + path: '/$h' + fullPath: '/l/$a/$b/$c/$d/$e/$f/$g/$h' + preLoaderRoute: typeof LABCDEFGHRouteImport + parentRoute: typeof LABCDEFGRoute + } + } +} + +interface LABCDEFGRouteChildren { + LABCDEFGHRoute: typeof LABCDEFGHRoute +} + +const LABCDEFGRouteChildren: LABCDEFGRouteChildren = { + LABCDEFGHRoute: LABCDEFGHRoute, +} + +const LABCDEFGRouteWithChildren = LABCDEFGRoute._addFileChildren( + LABCDEFGRouteChildren, +) + +interface LABCDEFRouteChildren { + LABCDEFGRoute: typeof LABCDEFGRouteWithChildren +} + +const LABCDEFRouteChildren: LABCDEFRouteChildren = { + LABCDEFGRoute: LABCDEFGRouteWithChildren, +} + +const LABCDEFRouteWithChildren = + LABCDEFRoute._addFileChildren(LABCDEFRouteChildren) + +interface LABCDERouteChildren { + LABCDEFRoute: typeof LABCDEFRouteWithChildren +} + +const LABCDERouteChildren: LABCDERouteChildren = { + LABCDEFRoute: LABCDEFRouteWithChildren, +} + +const LABCDERouteWithChildren = + LABCDERoute._addFileChildren(LABCDERouteChildren) + +interface LABCDRouteChildren { + LABCDERoute: typeof LABCDERouteWithChildren +} + +const LABCDRouteChildren: LABCDRouteChildren = { + LABCDERoute: LABCDERouteWithChildren, +} + +const LABCDRouteWithChildren = LABCDRoute._addFileChildren(LABCDRouteChildren) + +interface LABCRouteChildren { + LABCDRoute: typeof LABCDRouteWithChildren +} + +const LABCRouteChildren: LABCRouteChildren = { + LABCDRoute: LABCDRouteWithChildren, +} + +const LABCRouteWithChildren = LABCRoute._addFileChildren(LABCRouteChildren) + +interface LABRouteChildren { + LABCRoute: typeof LABCRouteWithChildren +} + +const LABRouteChildren: LABRouteChildren = { + LABCRoute: LABCRouteWithChildren, +} + +const LABRouteWithChildren = LABRoute._addFileChildren(LABRouteChildren) + +interface LARouteChildren { + LABRoute: typeof LABRouteWithChildren +} + +const LARouteChildren: LARouteChildren = { + LABRoute: LABRouteWithChildren, +} + +const LARouteWithChildren = LARoute._addFileChildren(LARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + LARoute: LARouteWithChildren, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..28dd4e847a --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/__root.tsx @@ -0,0 +1,53 @@ +import * as Vue from 'vue' +import { Link, Outlet, createRootRoute } from '@tanstack/vue-router' +import { leafParamSets, midParams } from '../../../shared' + +const RootComponent = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + ) + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/index.tsx new file mode 100644 index 0000000000..f3ffc58610 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/index.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const HomePage = Vue.defineComponent({ + setup() { + return () =>
home
+ }, +}) + +export const Route = createFileRoute('/')({ + component: HomePage, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx new file mode 100644 index 0000000000..756c31e1a9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.$g.$h.tsx @@ -0,0 +1,86 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { normalizeParam, smallHash } from '../../../shared' + +const ParamsSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(params.h), + }) + return () => { + void value.value + return null + } + }, +}) + +const ParamsSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.h}:2`), + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => context.ctxH, + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxH * 31 + 7) >>> 0, + }) + return () => { + void value.value + return null + } + }, +}) + +const LevelH = Vue.defineComponent({ + setup() { + const params = Route.useParams() + return () => ( + <> + + + + +
+ {[ + params.value.a, + params.value.b, + params.value.c, + params.value.d, + params.value.e, + params.value.f, + params.value.g, + params.value.h, + ].join('.')} +
+ + ) + }, +}) + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f/$g/$h')({ + params: { + parse: (params) => ({ ...params, h: normalizeParam(params.h) }), + stringify: (params) => ({ ...params, h: String(params.h) }), + }, + beforeLoad: ({ params }) => ({ ctxH: smallHash(params.h) }), + component: LevelH, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx new file mode 100644 index 0000000000..d6b9ccde83 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.$g.tsx @@ -0,0 +1,74 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { normalizeParam, smallHash } from '../../../shared' + +const ParamsSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(params.g), + }) + return () => { + void value.value + return null + } + }, +}) + +const ParamsSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.g}:2`), + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => context.ctxG, + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxG * 31 + 7) >>> 0, + }) + return () => { + void value.value + return null + } + }, +}) + +const LevelG = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + + + + ) + }, +}) + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f/$g')({ + params: { + parse: (params) => ({ ...params, g: normalizeParam(params.g) }), + stringify: (params) => ({ ...params, g: String(params.g) }), + }, + beforeLoad: ({ params }) => ({ ctxG: smallHash(params.g) }), + component: LevelG, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.tsx new file mode 100644 index 0000000000..76ed24904c --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.$f.tsx @@ -0,0 +1,74 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { normalizeParam, smallHash } from '../../../shared' + +const ParamsSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(params.f), + }) + return () => { + void value.value + return null + } + }, +}) + +const ParamsSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.f}:2`), + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => context.ctxF, + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxF * 31 + 7) >>> 0, + }) + return () => { + void value.value + return null + } + }, +}) + +const LevelF = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + + + + ) + }, +}) + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e/$f')({ + params: { + parse: (params) => ({ ...params, f: normalizeParam(params.f) }), + stringify: (params) => ({ ...params, f: String(params.f) }), + }, + beforeLoad: ({ params }) => ({ ctxF: smallHash(params.f) }), + component: LevelF, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.tsx new file mode 100644 index 0000000000..e24d3dc373 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.$e.tsx @@ -0,0 +1,74 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { normalizeParam, smallHash } from '../../../shared' + +const ParamsSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(params.e), + }) + return () => { + void value.value + return null + } + }, +}) + +const ParamsSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.e}:2`), + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => context.ctxE, + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxE * 31 + 7) >>> 0, + }) + return () => { + void value.value + return null + } + }, +}) + +const LevelE = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + + + + ) + }, +}) + +export const Route = createFileRoute('/l/$a/$b/$c/$d/$e')({ + params: { + parse: (params) => ({ ...params, e: normalizeParam(params.e) }), + stringify: (params) => ({ ...params, e: String(params.e) }), + }, + beforeLoad: ({ params }) => ({ ctxE: smallHash(params.e) }), + component: LevelE, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.tsx new file mode 100644 index 0000000000..7785638ee7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.$d.tsx @@ -0,0 +1,83 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { normalizeParam, smallHash } from '../../../shared' + +const ParamsSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(params.d), + }) + return () => { + void value.value + return null + } + }, +}) + +const ParamsSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.d}:2`), + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => context.ctxD, + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxD * 31 + 7) >>> 0, + }) + return () => { + void value.value + return null + } + }, +}) + +const LevelD = Vue.defineComponent({ + setup() { + const params = Route.useParams() + return () => ( + <> + + + + +
+ {[ + params.value.a, + params.value.b, + params.value.c, + params.value.d, + ].join('.')} +
+ + + ) + }, +}) + +export const Route = createFileRoute('/l/$a/$b/$c/$d')({ + params: { + parse: (params) => ({ ...params, d: normalizeParam(params.d) }), + stringify: (params) => ({ ...params, d: String(params.d) }), + }, + beforeLoad: ({ params }) => ({ ctxD: smallHash(params.d) }), + component: LevelD, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.tsx new file mode 100644 index 0000000000..0d0adc65ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.$c.tsx @@ -0,0 +1,74 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { normalizeParam, smallHash } from '../../../shared' + +const ParamsSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(params.c), + }) + return () => { + void value.value + return null + } + }, +}) + +const ParamsSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.c}:2`), + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => context.ctxC, + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxC * 31 + 7) >>> 0, + }) + return () => { + void value.value + return null + } + }, +}) + +const LevelC = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + + + + ) + }, +}) + +export const Route = createFileRoute('/l/$a/$b/$c')({ + params: { + parse: (params) => ({ ...params, c: normalizeParam(params.c) }), + stringify: (params) => ({ ...params, c: String(params.c) }), + }, + beforeLoad: ({ params }) => ({ ctxC: smallHash(params.c) }), + component: LevelC, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.tsx new file mode 100644 index 0000000000..f013d865af --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.$b.tsx @@ -0,0 +1,74 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { normalizeParam, smallHash } from '../../../shared' + +const ParamsSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(params.b), + }) + return () => { + void value.value + return null + } + }, +}) + +const ParamsSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.b}:2`), + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => context.ctxB, + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxB * 31 + 7) >>> 0, + }) + return () => { + void value.value + return null + } + }, +}) + +const LevelB = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + + + + ) + }, +}) + +export const Route = createFileRoute('/l/$a/$b')({ + params: { + parse: (params) => ({ ...params, b: normalizeParam(params.b) }), + stringify: (params) => ({ ...params, b: String(params.b) }), + }, + beforeLoad: ({ params }) => ({ ctxB: smallHash(params.b) }), + component: LevelB, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.tsx b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.tsx new file mode 100644 index 0000000000..d5764c0985 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/vue/src/routes/l.$a.tsx @@ -0,0 +1,74 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { normalizeParam, smallHash } from '../../../shared' + +const ParamsSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(params.a), + }) + return () => { + void value.value + return null + } + }, +}) + +const ParamsSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useParams({ + select: (params) => smallHash(`${params.a}:2`), + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberOne = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => context.ctxA, + }) + return () => { + void value.value + return null + } + }, +}) + +const ContextSubscriberTwo = Vue.defineComponent({ + setup() { + const value = Route.useRouteContext({ + select: (context) => (context.ctxA * 31 + 7) >>> 0, + }) + return () => { + void value.value + return null + } + }, +}) + +const LevelA = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + + + + ) + }, +}) + +export const Route = createFileRoute('/l/$a')({ + params: { + parse: (params) => ({ ...params, a: normalizeParam(params.a) }), + stringify: (params) => ({ ...params, a: String(params.a) }), + }, + beforeLoad: ({ params }) => ({ ctxA: smallHash(params.a) }), + component: LevelA, +}) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/tsconfig.json b/benchmarks/client-nav/scenarios/nested-params/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/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/nested-params/vue/vite.config.ts b/benchmarks/client-nav/scenarios/nested-params/vue/vite.config.ts new file mode 100644 index 0000000000..0d74eb7a7c --- /dev/null +++ b/benchmarks/client-nav/scenarios/nested-params/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 nested-params (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/preload/react/project.json b/benchmarks/client-nav/scenarios/preload/react/project.json new file mode 100644 index 0000000000..f095228746 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-preload-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/preload/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/preload/react/setup.ts b/benchmarks/client-nav/scenarios/preload/react/setup.ts new file mode 100644 index 0000000000..5409df903c --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/react/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, 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, + }) +} diff --git a/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts b/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts new file mode 100644 index 0000000000..5c210b2fd7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/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-preload', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-preload interaction 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/preload/react/speed.flame.ts b/benchmarks/client-nav/scenarios/preload/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/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/preload/react/src/main.tsx b/benchmarks/client-nav/scenarios/preload/react/src/main.tsx new file mode 100644 index 0000000000..395867f674 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/react/src/main.tsx @@ -0,0 +1,40 @@ +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, + defaultPreload: 'intent', + defaultPreloadDelay: 0, + defaultPreloadStaleTime: 0, + }) +} + +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/preload/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/preload/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..20619341c0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/react/src/routeTree.gen.ts @@ -0,0 +1,95 @@ +/* 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 DocsRouteImport } from './routes/docs' +import { Route as SectionsSectionRouteImport } from './routes/sections.$section' + +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', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/docs': typeof DocsRoute + '/sections/$section': typeof SectionsSectionRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/docs': typeof DocsRoute + '/sections/$section': typeof SectionsSectionRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/docs': typeof DocsRoute + '/sections/$section': typeof SectionsSectionRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/docs' | '/sections/$section' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/docs' | '/sections/$section' + id: '__root__' | '/' | '/docs' | '/sections/$section' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + DocsRoute: typeof DocsRoute + SectionsSectionRoute: typeof SectionsSectionRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + 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' + fullPath: '/sections/$section' + preLoaderRoute: typeof SectionsSectionRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + DocsRoute: DocsRoute, + SectionsSectionRoute: SectionsSectionRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/preload/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/preload/react/src/routes/__root.tsx new file mode 100644 index 0000000000..b659fe4d26 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/react/src/routes/__root.tsx @@ -0,0 +1,32 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/react-router' +import { sections } from '../../../shared' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/preload/react/src/routes/docs.tsx b/benchmarks/client-nav/scenarios/preload/react/src/routes/docs.tsx new file mode 100644 index 0000000000..1f87530bac --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/react/src/routes/docs.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/react-router' +import { docsMarker } from '../../../shared' + +export const Route = createFileRoute('/docs')({ + component: DocsPage, +}) + +function DocsPage() { + return ( +
+

{docsMarker}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/preload/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/preload/react/src/routes/index.tsx new file mode 100644 index 0000000000..2b8c83ebab --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/react/src/routes/index.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/react-router' +import { homeMarker } from '../../../shared' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return ( +
+

{homeMarker}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/preload/react/src/routes/sections.$section.tsx b/benchmarks/client-nav/scenarios/preload/react/src/routes/sections.$section.tsx new file mode 100644 index 0000000000..42962b8be7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/react/src/routes/sections.$section.tsx @@ -0,0 +1,32 @@ +import { createFileRoute } from '@tanstack/react-router' +import { sectionItems } from '../../../shared' + +export const Route = createFileRoute('/sections/$section')({ + loader: ({ params }) => { + const items = sectionItems(params.section) + const checksum = items.reduce( + (sum, item) => (sum + item.value) % 1_000_000_007, + 0, + ) + return { items, checksum } + }, + staleTime: 0, + gcTime: 0, + component: SectionPage, +}) + +function SectionPage() { + const params = Route.useParams() + const data = Route.useLoaderData() + + return ( +
+

{`${params.section}:${data.checksum}`}

+
    + {data.items.map((item) => ( +
  • {`${item.name}=${item.value}`}
  • + ))} +
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/preload/react/tsconfig.json b/benchmarks/client-nav/scenarios/preload/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/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/preload/react/vite.config.ts b/benchmarks/client-nav/scenarios/preload/react/vite.config.ts new file mode 100644 index 0000000000..8a41fc8707 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/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 preload (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/preload/shared.ts b/benchmarks/client-nav/scenarios/preload/shared.ts new file mode 100644 index 0000000000..d061f99451 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/shared.ts @@ -0,0 +1,119 @@ +/** + * Shared definition of the `preload` scenario: intent preloading via link + * hover, programmatic `router.preloadRoute`, and commit-time preload-cache + * maintenance. The router is configured with `defaultPreload: 'intent'`, + * `defaultPreloadDelay: 0` (no wall-clock debounce timer) and + * `defaultPreloadStaleTime: 0` — the default 30s wall-clock threshold would + * flip cache-hit behavior mid-run; with 0 every hover re-runs the preload + * work, keeping the loop stationary. + * + * Hover-intent preloading was verified manually per adapter (standalone jsdom + * run inspecting the router's cached matches after dispatching `mouseover` on + * a link). The harness hover step dispatches a single `mouseover`, which + * triggers the preload pipeline exactly once in every adapter: React + * synthesizes mouseEnter from it, Solid/Vue attach a native `mouseover` + * handler. (Solid/Vue also listen to `mouseenter`; dispatching both events + * would preload twice for them but once for React.) + */ +import type { ScenarioStep } from '../harness' + +export const sections = ['a', 'b', 'c', 'd', 'e'] as const + +export const SECTION_ITEM_COUNT = 30 + +/** Deterministic LCG stream seeded from a string — no Math.random. */ +function seededValues(seedText: string, count: number) { + let value = 0 + for (let i = 0; i < seedText.length; i++) { + value = (value * 31 + seedText.charCodeAt(i)) >>> 0 + } + + const values: Array = [] + for (let i = 0; i < count; i++) { + value = (value * 1664525 + 1013904223) >>> 0 + values.push(value % 100_000) + } + return values +} + +export interface SectionItem { + name: string + value: number +} + +export function sectionItems(section: string): Array { + return seededValues(`section-${section}`, SECTION_ITEM_COUNT).map( + (value, index) => ({ + name: `item-${section}-${index}`, + value, + }), + ) +} + +export function sectionChecksum(section: string) { + return sectionItems(section).reduce( + (sum, item) => (sum + item.value) % 1_000_000_007, + 0, + ) +} + +export function sectionMarker(section: string) { + return `${section}:${sectionChecksum(section)}` +} + +export const docsMarker = 'docs' +export const homeMarker = 'home' + +interface StepDef { + step: ScenarioStep + /** Expected page marker after the step; undefined for non-navigation steps. */ + marker?: string +} + +export const stepDefs: ReadonlyArray = [ + { step: { type: 'hover', testId: 's-a' } }, + { step: { type: 'hover', testId: 's-b' } }, + { step: 's-a', marker: sectionMarker('a') }, + { step: { type: 'hover', testId: 's-c' } }, + { step: 's-c', marker: sectionMarker('c') }, + { + step: { + type: 'preload', + getOptions: () => ({ + to: '/sections/$section', + params: { section: 'd' }, + }), + }, + }, + { step: 's-d', marker: sectionMarker('d') }, + { step: { type: 'hover', testId: 's-e' } }, + { step: 'go-docs', marker: docsMarker }, + { step: 'go-home', marker: homeMarker }, +] + +export const scenarioSteps: ReadonlyArray = stepDefs.map( + (def) => def.step, +) + +export function assertStepResult(stepIndex: number, container: HTMLElement) { + const def = stepDefs[stepIndex]! + if (!def.marker) { + return + } + + const marker = container.querySelector('[data-testid="page-state"]') + if (marker?.textContent !== def.marker) { + throw new Error( + `Expected page marker "${def.marker}" after step ${stepIndex}, received "${marker?.textContent}"`, + ) + } +} + +// Two laps through the 10-step sequence per benchmark iteration. +export const ticksPerIteration = 20 + +export const benchOptions = { + warmupIterations: 50, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/preload/solid/project.json b/benchmarks/client-nav/scenarios/preload/solid/project.json new file mode 100644 index 0000000000..a186879335 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-preload-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/preload/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/preload/solid/setup.ts b/benchmarks/client-nav/scenarios/preload/solid/setup.ts new file mode 100644 index 0000000000..34270fe8a4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/solid/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, 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, + }) +} diff --git a/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts new file mode 100644 index 0000000000..f835b4a7b9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/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-preload', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-preload interaction 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/preload/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/preload/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/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/preload/solid/src/main.tsx b/benchmarks/client-nav/scenarios/preload/solid/src/main.tsx new file mode 100644 index 0000000000..3791156c64 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/solid/src/main.tsx @@ -0,0 +1,37 @@ +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, + defaultPreload: 'intent', + defaultPreloadDelay: 0, + defaultPreloadStaleTime: 0, + }) +} + +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/preload/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/preload/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..97e215b6da --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/solid/src/routeTree.gen.ts @@ -0,0 +1,95 @@ +/* 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 DocsRouteImport } from './routes/docs' +import { Route as SectionsSectionRouteImport } from './routes/sections.$section' + +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', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/docs': typeof DocsRoute + '/sections/$section': typeof SectionsSectionRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/docs': typeof DocsRoute + '/sections/$section': typeof SectionsSectionRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/docs': typeof DocsRoute + '/sections/$section': typeof SectionsSectionRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/docs' | '/sections/$section' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/docs' | '/sections/$section' + id: '__root__' | '/' | '/docs' | '/sections/$section' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + DocsRoute: typeof DocsRoute + SectionsSectionRoute: typeof SectionsSectionRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + 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' + fullPath: '/sections/$section' + preLoaderRoute: typeof SectionsSectionRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + DocsRoute: DocsRoute, + SectionsSectionRoute: SectionsSectionRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/preload/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/preload/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..a805ed0feb --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/solid/src/routes/__root.tsx @@ -0,0 +1,34 @@ +import { For } from 'solid-js' +import { Link, Outlet, createRootRoute } from '@tanstack/solid-router' +import { sections } from '../../../shared' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/preload/solid/src/routes/docs.tsx b/benchmarks/client-nav/scenarios/preload/solid/src/routes/docs.tsx new file mode 100644 index 0000000000..b077cfd18f --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/solid/src/routes/docs.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { docsMarker } from '../../../shared' + +export const Route = createFileRoute('/docs')({ + component: DocsPage, +}) + +function DocsPage() { + return ( +
+

{docsMarker}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/preload/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/preload/solid/src/routes/index.tsx new file mode 100644 index 0000000000..72fbfe387a --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/solid/src/routes/index.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { homeMarker } from '../../../shared' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return ( +
+

{homeMarker}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/preload/solid/src/routes/sections.$section.tsx b/benchmarks/client-nav/scenarios/preload/solid/src/routes/sections.$section.tsx new file mode 100644 index 0000000000..2a7fb2ad1b --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/solid/src/routes/sections.$section.tsx @@ -0,0 +1,33 @@ +import { For } from 'solid-js' +import { createFileRoute } from '@tanstack/solid-router' +import { sectionItems } from '../../../shared' + +export const Route = createFileRoute('/sections/$section')({ + loader: ({ params }) => { + const items = sectionItems(params.section) + const checksum = items.reduce( + (sum, item) => (sum + item.value) % 1_000_000_007, + 0, + ) + return { items, checksum } + }, + staleTime: 0, + gcTime: 0, + component: SectionPage, +}) + +function SectionPage() { + const params = Route.useParams() + const data = Route.useLoaderData() + + return ( +
+

{`${params().section}:${data().checksum}`}

+
    + + {(item) =>
  • {`${item.name}=${item.value}`}
  • } +
    +
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/preload/solid/tsconfig.json b/benchmarks/client-nav/scenarios/preload/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/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/preload/solid/vite.config.ts b/benchmarks/client-nav/scenarios/preload/solid/vite.config.ts new file mode 100644 index 0000000000..07014e6124 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/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 preload (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/preload/vue/project.json b/benchmarks/client-nav/scenarios/preload/vue/project.json new file mode 100644 index 0000000000..404476723d --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-preload-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/preload/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/preload/vue/setup.ts b/benchmarks/client-nav/scenarios/preload/vue/setup.ts new file mode 100644 index 0000000000..f70a154909 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/vue/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, 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, + }) +} diff --git a/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts new file mode 100644 index 0000000000..e0ec83619b --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/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-preload', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-preload interaction 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/preload/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/preload/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/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/preload/vue/src/main.tsx b/benchmarks/client-nav/scenarios/preload/vue/src/main.tsx new file mode 100644 index 0000000000..3da20b2cbf --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/vue/src/main.tsx @@ -0,0 +1,44 @@ +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, + defaultPreload: 'intent', + defaultPreloadDelay: 0, + defaultPreloadStaleTime: 0, + }) +} + +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/preload/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/preload/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..5f95d09da0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/vue/src/routeTree.gen.ts @@ -0,0 +1,95 @@ +/* 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 DocsRouteImport } from './routes/docs' +import { Route as SectionsSectionRouteImport } from './routes/sections.$section' + +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', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/docs': typeof DocsRoute + '/sections/$section': typeof SectionsSectionRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/docs': typeof DocsRoute + '/sections/$section': typeof SectionsSectionRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/docs': typeof DocsRoute + '/sections/$section': typeof SectionsSectionRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/docs' | '/sections/$section' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/docs' | '/sections/$section' + id: '__root__' | '/' | '/docs' | '/sections/$section' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + DocsRoute: typeof DocsRoute + SectionsSectionRoute: typeof SectionsSectionRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + 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' + fullPath: '/sections/$section' + preLoaderRoute: typeof SectionsSectionRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + DocsRoute: DocsRoute, + SectionsSectionRoute: SectionsSectionRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/preload/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/preload/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..bf91ba3770 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/vue/src/routes/__root.tsx @@ -0,0 +1,35 @@ +import * as Vue from 'vue' +import { Link, Outlet, createRootRoute } from '@tanstack/vue-router' +import { sections } from '../../../shared' + +const RootComponent = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + ) + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/preload/vue/src/routes/docs.tsx b/benchmarks/client-nav/scenarios/preload/vue/src/routes/docs.tsx new file mode 100644 index 0000000000..07d0a989ad --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/vue/src/routes/docs.tsx @@ -0,0 +1,17 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { docsMarker } from '../../../shared' + +const DocsPage = Vue.defineComponent({ + setup() { + return () => ( +
+

{docsMarker}

+
+ ) + }, +}) + +export const Route = createFileRoute('/docs')({ + component: DocsPage, +}) diff --git a/benchmarks/client-nav/scenarios/preload/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/preload/vue/src/routes/index.tsx new file mode 100644 index 0000000000..f04a9f5796 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/vue/src/routes/index.tsx @@ -0,0 +1,17 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { homeMarker } from '../../../shared' + +const HomePage = Vue.defineComponent({ + setup() { + return () => ( +
+

{homeMarker}

+
+ ) + }, +}) + +export const Route = createFileRoute('/')({ + component: HomePage, +}) diff --git a/benchmarks/client-nav/scenarios/preload/vue/src/routes/sections.$section.tsx b/benchmarks/client-nav/scenarios/preload/vue/src/routes/sections.$section.tsx new file mode 100644 index 0000000000..aeb617a86f --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/vue/src/routes/sections.$section.tsx @@ -0,0 +1,37 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { sectionItems } from '../../../shared' + +const SectionPage = Vue.defineComponent({ + setup() { + const params = Route.useParams() + const data = Route.useLoaderData() + + return () => ( +
+

+ {`${params.value.section}:${data.value.checksum}`} +

+
    + {data.value.items.map((item) => ( +
  • {`${item.name}=${item.value}`}
  • + ))} +
+
+ ) + }, +}) + +export const Route = createFileRoute('/sections/$section')({ + loader: ({ params }) => { + const items = sectionItems(params.section) + const checksum = items.reduce( + (sum, item) => (sum + item.value) % 1_000_000_007, + 0, + ) + return { items, checksum } + }, + staleTime: 0, + gcTime: 0, + component: SectionPage, +}) diff --git a/benchmarks/client-nav/scenarios/preload/vue/tsconfig.json b/benchmarks/client-nav/scenarios/preload/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/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/preload/vue/vite.config.ts b/benchmarks/client-nav/scenarios/preload/vue/vite.config.ts new file mode 100644 index 0000000000..8d00e66378 --- /dev/null +++ b/benchmarks/client-nav/scenarios/preload/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 preload (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/rewrites/react/project.json b/benchmarks/client-nav/scenarios/rewrites/react/project.json new file mode 100644 index 0000000000..d98c6e1412 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-rewrites-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/rewrites/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/setup.ts b/benchmarks/client-nav/scenarios/rewrites/react/setup.ts new file mode 100644 index 0000000000..0c5df273ed --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/react/setup.ts @@ -0,0 +1,18 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, initialUrl, steps } 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, + assertAfterStep: assertStepResult, + initialUrl, + }) +} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts b/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts new file mode 100644 index 0000000000..dd1b6f3686 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/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-rewrites', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-rewrites 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/rewrites/react/speed.flame.ts b/benchmarks/client-nav/scenarios/rewrites/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/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/rewrites/react/src/main.tsx b/benchmarks/client-nav/scenarios/rewrites/react/src/main.tsx new file mode 100644 index 0000000000..28020ce373 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/react/src/main.tsx @@ -0,0 +1,40 @@ +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(history: RouterHistory) { + return createRouter({ + routeTree, + history, + basepath, + rewrite: localeRewrite, + 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/rewrites/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/rewrites/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..b6ab8c8be4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/react/src/routeTree.gen.ts @@ -0,0 +1,103 @@ +/* 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 PARouteImport } from './routes/p.$a' +import { Route as PABRouteImport } from './routes/p.$a.$b' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const PARoute = PARouteImport.update({ + id: '/p/$a', + path: '/p/$a', + getParentRoute: () => rootRouteImport, +} as any) +const PABRoute = PABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => PARoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/p/$a' | '/p/$a/$b' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/p/$a' | '/p/$a/$b' + id: '__root__' | '/' | '/p/$a' | '/p/$a/$b' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + PARoute: typeof PARouteWithChildren +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/p/$a': { + id: '/p/$a' + path: '/p/$a' + fullPath: '/p/$a' + preLoaderRoute: typeof PARouteImport + parentRoute: typeof rootRouteImport + } + '/p/$a/$b': { + id: '/p/$a/$b' + path: '/$b' + fullPath: '/p/$a/$b' + preLoaderRoute: typeof PABRouteImport + parentRoute: typeof PARoute + } + } +} + +interface PARouteChildren { + PABRoute: typeof PABRoute +} + +const PARouteChildren: PARouteChildren = { + PABRoute: PABRoute, +} + +const PARouteWithChildren = PARoute._addFileChildren(PARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + PARoute: PARouteWithChildren, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/rewrites/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/rewrites/react/src/routes/__root.tsx new file mode 100644 index 0000000000..ad14ff51f1 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/react/src/routes/__root.tsx @@ -0,0 +1,61 @@ +import { + Link, + Outlet, + createRootRoute, + useLocation, +} from '@tanstack/react-router' +import type { SearchSchemaInput } from '@tanstack/react-router' + +export const Route = createRootRoute({ + validateSearch: (search: Record & SearchSchemaInput) => + ({ + _locale: typeof search._locale === 'string' ? search._locale : undefined, + }) as { _locale?: string }, + component: RootComponent, +}) + +function RootComponent() { + const pathname = useLocation({ select: (location) => location.pathname }) + + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/rewrites/react/src/routes/index.tsx new file mode 100644 index 0000000000..821cfe4a7c --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/react/src/routes/index.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return ( +
+

Home

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/src/routes/p.$a.$b.tsx b/benchmarks/client-nav/scenarios/rewrites/react/src/routes/p.$a.$b.tsx new file mode 100644 index 0000000000..ec1163e5c2 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/react/src/routes/p.$a.$b.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/react-router' +import { itemLabel } from '../../../shared' + +export const Route = createFileRoute('/p/$a/$b')({ + component: ItemPage, +}) + +function ItemPage() { + const params = Route.useParams() + + return ( +
+

{itemLabel(params.a, params.b)}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/src/routes/p.$a.tsx b/benchmarks/client-nav/scenarios/rewrites/react/src/routes/p.$a.tsx new file mode 100644 index 0000000000..f4937494f0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/react/src/routes/p.$a.tsx @@ -0,0 +1,17 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' +import { sectionLabel } from '../../../shared' + +export const Route = createFileRoute('/p/$a')({ + component: SectionPage, +}) + +function SectionPage() { + const params = Route.useParams() + + return ( +
+

{sectionLabel(params.a)}

+ +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/rewrites/react/tsconfig.json b/benchmarks/client-nav/scenarios/rewrites/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/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/rewrites/react/vite.config.ts b/benchmarks/client-nav/scenarios/rewrites/react/vite.config.ts new file mode 100644 index 0000000000..e79e8522e9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/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 rewrites (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/rewrites/shared.ts b/benchmarks/client-nav/scenarios/rewrites/shared.ts new file mode 100644 index 0000000000..0ca0a7ceb9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/shared.ts @@ -0,0 +1,106 @@ +/** + * Shared definition of the `rewrites` scenario: composed client-side location + * rewrites — router `basepath` plus a locale input/output rewrite (the client + * analog of the SSR `rewrites` scenario). Externally URLs look like + * `/app/{locale}/p/...`; internally the router sees `/p/...` with the locale + * carried in the `_locale` search param. Every navigation runs the composed + * output rewrite when building hrefs/committing and the input rewrite when + * parsing the committed location. + */ +import type { ScenarioStep } from '../harness' +import type { RouterHistory } from '@tanstack/history' + +export const basepath = '/app' +export const defaultLocale = 'en' + +const localePrefixRe = /^\/(fr|de|es)(\/.*)$/ + +// Framework-agnostic rewrite pair consumed by all three apps' createRouter. +export const localeRewrite = { + input: ({ url }: { url: URL }) => { + const match = url.pathname.match(localePrefixRe) + + if (match) { + url.pathname = match[2]! + url.searchParams.set('_locale', match[1]!) + return url + } + + return undefined + }, + output: ({ url }: { url: URL }) => { + const locale = url.searchParams.get('_locale') + + if (locale) { + url.searchParams.delete('_locale') + url.pathname = `/${locale}${url.pathname}` + } + + return url + }, +} + +export function sectionLabel(a: string) { + return `Section ${a}` +} + +export function itemLabel(a: string, b: string) { + return `Item ${a}/${b}` +} + +interface StepDef { + testId: string + /** Internal router pathname expected after the step. */ + routerPath: string + /** External history pathname expected after the step. */ + windowPath: string +} + +// Circular lap: alternates sections, depths, and locales so every step runs +// the composed rewrites in both directions, then returns to the start. +export const stepDefs: ReadonlyArray = [ + { testId: 'go-x', routerPath: '/p/x', windowPath: '/app/p/x' }, + { testId: 'go-x-1-fr', routerPath: '/p/x/1', windowPath: '/app/fr/p/x/1' }, + { testId: 'go-y-de', routerPath: '/p/y', windowPath: '/app/de/p/y' }, + { testId: 'go-y-2', routerPath: '/p/y/2', windowPath: '/app/p/y/2' }, + { testId: 'go-x-es', routerPath: '/p/x', windowPath: '/app/es/p/x' }, + { testId: 'go-home', routerPath: '/', windowPath: '/app/' }, +] as const + +export const steps: ReadonlyArray = stepDefs.map( + (step) => step.testId, +) + +export function assertStepResult( + stepIndex: number, + container: HTMLElement, + history: RouterHistory, +) { + const expected = stepDefs[stepIndex]! + const marker = container.querySelector('[data-testid="loc"]') + const routerPath = marker?.textContent + + if (routerPath !== expected.routerPath) { + throw new Error( + `Expected router pathname "${expected.routerPath}" after step ${stepIndex}, received "${routerPath}"`, + ) + } + + if (history.location.pathname !== expected.windowPath) { + throw new Error( + `Expected history pathname "${expected.windowPath}" after step ${stepIndex}, received "${history.location.pathname}"`, + ) + } +} + +// The app starts on the external root inside the basepath. +export const initialUrl = '/app' + +// Three laps through the 6-step sequence per benchmark iteration. +export const ticksPerIteration = 18 + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/project.json b/benchmarks/client-nav/scenarios/rewrites/solid/project.json new file mode 100644 index 0000000000..4b2f763032 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-rewrites-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/rewrites/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/setup.ts b/benchmarks/client-nav/scenarios/rewrites/solid/setup.ts new file mode 100644 index 0000000000..5796df712d --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/solid/setup.ts @@ -0,0 +1,18 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, initialUrl, steps } 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, + assertAfterStep: assertStepResult, + initialUrl, + }) +} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts new file mode 100644 index 0000000000..9c4313e2ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/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-rewrites', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-rewrites 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/rewrites/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/rewrites/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/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/rewrites/solid/src/main.tsx b/benchmarks/client-nav/scenarios/rewrites/solid/src/main.tsx new file mode 100644 index 0000000000..31f1d07650 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/solid/src/main.tsx @@ -0,0 +1,37 @@ +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(history: RouterHistory) { + return createRouter({ + routeTree, + history, + basepath, + rewrite: localeRewrite, + 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/rewrites/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/rewrites/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..2d35f899c9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/solid/src/routeTree.gen.ts @@ -0,0 +1,103 @@ +/* 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 PARouteImport } from './routes/p.$a' +import { Route as PABRouteImport } from './routes/p.$a.$b' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const PARoute = PARouteImport.update({ + id: '/p/$a', + path: '/p/$a', + getParentRoute: () => rootRouteImport, +} as any) +const PABRoute = PABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => PARoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/p/$a' | '/p/$a/$b' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/p/$a' | '/p/$a/$b' + id: '__root__' | '/' | '/p/$a' | '/p/$a/$b' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + PARoute: typeof PARouteWithChildren +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/p/$a': { + id: '/p/$a' + path: '/p/$a' + fullPath: '/p/$a' + preLoaderRoute: typeof PARouteImport + parentRoute: typeof rootRouteImport + } + '/p/$a/$b': { + id: '/p/$a/$b' + path: '/$b' + fullPath: '/p/$a/$b' + preLoaderRoute: typeof PABRouteImport + parentRoute: typeof PARoute + } + } +} + +interface PARouteChildren { + PABRoute: typeof PABRoute +} + +const PARouteChildren: PARouteChildren = { + PABRoute: PABRoute, +} + +const PARouteWithChildren = PARoute._addFileChildren(PARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + PARoute: PARouteWithChildren, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..3a78f2c3cf --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/__root.tsx @@ -0,0 +1,61 @@ +import { + Link, + Outlet, + createRootRoute, + useLocation, +} from '@tanstack/solid-router' +import type { SearchSchemaInput } from '@tanstack/solid-router' + +export const Route = createRootRoute({ + validateSearch: (search: Record & SearchSchemaInput) => + ({ + _locale: typeof search._locale === 'string' ? search._locale : undefined, + }) as { _locale?: string }, + component: RootComponent, +}) + +function RootComponent() { + const pathname = useLocation({ select: (location) => location.pathname }) + + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/index.tsx new file mode 100644 index 0000000000..5ee381ff05 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/index.tsx @@ -0,0 +1,13 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return ( +
+

Home

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/p.$a.$b.tsx b/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/p.$a.$b.tsx new file mode 100644 index 0000000000..febcad35e3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/p.$a.$b.tsx @@ -0,0 +1,16 @@ +import { createFileRoute } from '@tanstack/solid-router' +import { itemLabel } from '../../../shared' + +export const Route = createFileRoute('/p/$a/$b')({ + component: ItemPage, +}) + +function ItemPage() { + const params = Route.useParams() + + return ( +
+

{itemLabel(params().a, params().b)}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/p.$a.tsx b/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/p.$a.tsx new file mode 100644 index 0000000000..adfb7bc3b6 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/solid/src/routes/p.$a.tsx @@ -0,0 +1,17 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' +import { sectionLabel } from '../../../shared' + +export const Route = createFileRoute('/p/$a')({ + component: SectionPage, +}) + +function SectionPage() { + const params = Route.useParams() + + return ( +
+

{sectionLabel(params().a)}

+ +
+ ) +} diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/tsconfig.json b/benchmarks/client-nav/scenarios/rewrites/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/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/rewrites/solid/vite.config.ts b/benchmarks/client-nav/scenarios/rewrites/solid/vite.config.ts new file mode 100644 index 0000000000..c9e99b7d60 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/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 rewrites (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/project.json b/benchmarks/client-nav/scenarios/rewrites/vue/project.json new file mode 100644 index 0000000000..9b7cb5d198 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-rewrites-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/rewrites/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/setup.ts b/benchmarks/client-nav/scenarios/rewrites/vue/setup.ts new file mode 100644 index 0000000000..e26b4d05ca --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/vue/setup.ts @@ -0,0 +1,18 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, initialUrl, steps } 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, + assertAfterStep: assertStepResult, + initialUrl, + }) +} diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts new file mode 100644 index 0000000000..e96aff39eb --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/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-rewrites', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-rewrites 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/rewrites/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/rewrites/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/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/rewrites/vue/src/main.tsx b/benchmarks/client-nav/scenarios/rewrites/vue/src/main.tsx new file mode 100644 index 0000000000..6695e82dbb --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/vue/src/main.tsx @@ -0,0 +1,44 @@ +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(history: RouterHistory) { + return createRouter({ + routeTree, + history, + basepath, + rewrite: localeRewrite, + 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/rewrites/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/rewrites/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..6eca4e8ce5 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/vue/src/routeTree.gen.ts @@ -0,0 +1,103 @@ +/* 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 PARouteImport } from './routes/p.$a' +import { Route as PABRouteImport } from './routes/p.$a.$b' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const PARoute = PARouteImport.update({ + id: '/p/$a', + path: '/p/$a', + getParentRoute: () => rootRouteImport, +} as any) +const PABRoute = PABRouteImport.update({ + id: '/$b', + path: '/$b', + getParentRoute: () => PARoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/p/$a': typeof PARouteWithChildren + '/p/$a/$b': typeof PABRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/p/$a' | '/p/$a/$b' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/p/$a' | '/p/$a/$b' + id: '__root__' | '/' | '/p/$a' | '/p/$a/$b' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + PARoute: typeof PARouteWithChildren +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/p/$a': { + id: '/p/$a' + path: '/p/$a' + fullPath: '/p/$a' + preLoaderRoute: typeof PARouteImport + parentRoute: typeof rootRouteImport + } + '/p/$a/$b': { + id: '/p/$a/$b' + path: '/$b' + fullPath: '/p/$a/$b' + preLoaderRoute: typeof PABRouteImport + parentRoute: typeof PARoute + } + } +} + +interface PARouteChildren { + PABRoute: typeof PABRoute +} + +const PARouteChildren: PARouteChildren = { + PABRoute: PABRoute, +} + +const PARouteWithChildren = PARoute._addFileChildren(PARouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + PARoute: PARouteWithChildren, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..ae89645005 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/__root.tsx @@ -0,0 +1,64 @@ +import * as Vue from 'vue' +import { + Link, + Outlet, + createRootRoute, + useLocation, +} from '@tanstack/vue-router' +import type { SearchSchemaInput } from '@tanstack/vue-router' + +const RootComponent = Vue.defineComponent({ + setup() { + const pathname = useLocation({ select: (location) => location.pathname }) + + return () => ( + <> + + + + ) + }, +}) + +export const Route = createRootRoute({ + validateSearch: (search: Record & SearchSchemaInput) => + ({ + _locale: typeof search._locale === 'string' ? search._locale : undefined, + }) as { _locale?: string }, + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/index.tsx new file mode 100644 index 0000000000..d5405b52d2 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/index.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const HomePage = Vue.defineComponent({ + setup() { + return () => ( +
+

Home

+
+ ) + }, +}) + +export const Route = createFileRoute('/')({ + component: HomePage, +}) diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/p.$a.$b.tsx b/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/p.$a.$b.tsx new file mode 100644 index 0000000000..062c0903b9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/p.$a.$b.tsx @@ -0,0 +1,19 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { itemLabel } from '../../../shared' + +const ItemPage = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
+

{itemLabel(params.value.a, params.value.b)}

+
+ ) + }, +}) + +export const Route = createFileRoute('/p/$a/$b')({ + component: ItemPage, +}) diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/p.$a.tsx b/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/p.$a.tsx new file mode 100644 index 0000000000..552700d402 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/vue/src/routes/p.$a.tsx @@ -0,0 +1,20 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' +import { sectionLabel } from '../../../shared' + +const SectionPage = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
+

{sectionLabel(params.value.a)}

+ +
+ ) + }, +}) + +export const Route = createFileRoute('/p/$a')({ + component: SectionPage, +}) diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/tsconfig.json b/benchmarks/client-nav/scenarios/rewrites/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/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/rewrites/vue/vite.config.ts b/benchmarks/client-nav/scenarios/rewrites/vue/vite.config.ts new file mode 100644 index 0000000000..1a795a4e1d --- /dev/null +++ b/benchmarks/client-nav/scenarios/rewrites/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 rewrites (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/project.json b/benchmarks/client-nav/scenarios/route-tree-scale/react/project.json new file mode 100644 index 0000000000..3291738f79 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-route-tree-scale-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/route-tree-scale/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/setup.ts b/benchmarks/client-nav/scenarios/route-tree-scale/react/setup.ts new file mode 100644 index 0000000000..130583b190 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } 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, + assertAfterStep: assertStepResult, + }) +} 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 new file mode 100644 index 0000000000..6f4b448775 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/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-route-tree-scale', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-route-tree-scale 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/route-tree-scale/react/speed.flame.ts b/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/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/route-tree-scale/react/src/main.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/main.tsx new file mode 100644 index 0000000000..5febd6f795 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/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/route-tree-scale/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..f8eeb73dda --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routeTree.gen.ts @@ -0,0 +1,881 @@ +/* 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 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 IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const SecARoute = SecARouteImport.update({ + id: '/sec-a', + path: '/sec-a', + getParentRoute: () => rootRouteImport, +} as any) +const SecBRoute = SecBRouteImport.update({ + id: '/sec-b', + path: '/sec-b', + getParentRoute: () => rootRouteImport, +} as any) +const SecCRoute = SecCRouteImport.update({ + id: '/sec-c', + path: '/sec-c', + getParentRoute: () => rootRouteImport, +} as any) +const SecDRoute = SecDRouteImport.update({ + id: '/sec-d', + path: '/sec-d', + getParentRoute: () => rootRouteImport, +} as any) +const SecERoute = SecERouteImport.update({ + id: '/sec-e', + path: '/sec-e', + getParentRoute: () => rootRouteImport, +} as any) +const SecFRoute = SecFRouteImport.update({ + id: '/sec-f', + path: '/sec-f', + getParentRoute: () => rootRouteImport, +} as any) +const marketingPricingRoute = marketingPricingRouteImport.update({ + id: '/(marketing)/pricing', + path: '/pricing', + getParentRoute: () => rootRouteImport, +} as any) +const marketingPromoRoute = marketingPromoRouteImport.update({ + id: '/(marketing)/promo', + path: '/promo', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ + id: '/alpha', + path: '/alpha', + getParentRoute: () => LayoutRoute, +} as any) +const LayoutBetaRoute = LayoutBetaRouteImport.update({ + id: '/beta', + path: '/beta', + getParentRoute: () => LayoutRoute, +} as any) +const FilesSplatRoute = FilesSplatRouteImport.update({ + id: '/files/$', + path: '/files/$', + getParentRoute: () => rootRouteImport, +} as any) +const ReleaseVChar123versionChar125Route = + ReleaseVChar123versionChar125RouteImport.update({ + id: '/release/v{$version}', + path: '/release/v{$version}', + getParentRoute: () => rootRouteImport, + } as any) +const SecAIndexRoute = SecAIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecARoute, +} as any) +const SecAIdRoute = SecAIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecARoute, +} as any) +const SecAAboutRoute = SecAAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecARoute, +} as any) +const SecASettingsRoute = SecASettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecARoute, +} as any) +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 { + '/': typeof IndexRoute + '/sec-a': typeof SecARouteWithChildren + '/sec-b': typeof SecBRouteWithChildren + '/sec-c': typeof SecCRouteWithChildren + '/sec-d': typeof SecDRouteWithChildren + '/sec-e': typeof SecERouteWithChildren + '/sec-f': typeof SecFRouteWithChildren + '/pricing': typeof marketingPricingRoute + '/promo': typeof marketingPromoRoute + '/alpha': typeof LayoutAlphaRoute + '/beta': typeof LayoutBetaRoute + '/files/$': typeof FilesSplatRoute + '/release/v{$version}': typeof ReleaseVChar123versionChar125Route + '/sec-a/$id': typeof SecAIdRoute + '/sec-a/about': typeof SecAAboutRoute + '/sec-a/settings': typeof SecASettingsRoute + '/sec-b/$id': typeof SecBIdRoute + '/sec-b/about': typeof SecBAboutRoute + '/sec-b/settings': typeof SecBSettingsRoute + '/sec-c/$id': typeof SecCIdRoute + '/sec-c/about': typeof SecCAboutRoute + '/sec-c/settings': typeof SecCSettingsRoute + '/sec-d/$id': typeof SecDIdRoute + '/sec-d/about': typeof SecDAboutRoute + '/sec-d/settings': typeof SecDSettingsRoute + '/sec-e/$id': typeof SecEIdRoute + '/sec-e/about': typeof SecEAboutRoute + '/sec-e/settings': typeof SecESettingsRoute + '/sec-f/$id': typeof SecFIdRoute + '/sec-f/about': typeof SecFAboutRoute + '/sec-f/settings': typeof SecFSettingsRoute + '/sec-a/': typeof SecAIndexRoute + '/sec-b/': typeof SecBIndexRoute + '/sec-c/': typeof SecCIndexRoute + '/sec-d/': typeof SecDIndexRoute + '/sec-e/': typeof SecEIndexRoute + '/sec-f/': typeof SecFIndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/pricing': typeof marketingPricingRoute + '/promo': typeof marketingPromoRoute + '/alpha': typeof LayoutAlphaRoute + '/beta': typeof LayoutBetaRoute + '/files/$': typeof FilesSplatRoute + '/release/v{$version}': typeof ReleaseVChar123versionChar125Route + '/sec-a/$id': typeof SecAIdRoute + '/sec-a/about': typeof SecAAboutRoute + '/sec-a/settings': typeof SecASettingsRoute + '/sec-b/$id': typeof SecBIdRoute + '/sec-b/about': typeof SecBAboutRoute + '/sec-b/settings': typeof SecBSettingsRoute + '/sec-c/$id': typeof SecCIdRoute + '/sec-c/about': typeof SecCAboutRoute + '/sec-c/settings': typeof SecCSettingsRoute + '/sec-d/$id': typeof SecDIdRoute + '/sec-d/about': typeof SecDAboutRoute + '/sec-d/settings': typeof SecDSettingsRoute + '/sec-e/$id': typeof SecEIdRoute + '/sec-e/about': typeof SecEAboutRoute + '/sec-e/settings': typeof SecESettingsRoute + '/sec-f/$id': typeof SecFIdRoute + '/sec-f/about': typeof SecFAboutRoute + '/sec-f/settings': typeof SecFSettingsRoute + '/sec-a': typeof SecAIndexRoute + '/sec-b': typeof SecBIndexRoute + '/sec-c': typeof SecCIndexRoute + '/sec-d': typeof SecDIndexRoute + '/sec-e': typeof SecEIndexRoute + '/sec-f': typeof SecFIndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/_layout': typeof LayoutRouteWithChildren + '/sec-a': typeof SecARouteWithChildren + '/sec-b': typeof SecBRouteWithChildren + '/sec-c': typeof SecCRouteWithChildren + '/sec-d': typeof SecDRouteWithChildren + '/sec-e': typeof SecERouteWithChildren + '/sec-f': typeof SecFRouteWithChildren + '/(marketing)/pricing': typeof marketingPricingRoute + '/(marketing)/promo': typeof marketingPromoRoute + '/_layout/alpha': typeof LayoutAlphaRoute + '/_layout/beta': typeof LayoutBetaRoute + '/files/$': typeof FilesSplatRoute + '/release/v{$version}': typeof ReleaseVChar123versionChar125Route + '/sec-a/$id': typeof SecAIdRoute + '/sec-a/about': typeof SecAAboutRoute + '/sec-a/settings': typeof SecASettingsRoute + '/sec-b/$id': typeof SecBIdRoute + '/sec-b/about': typeof SecBAboutRoute + '/sec-b/settings': typeof SecBSettingsRoute + '/sec-c/$id': typeof SecCIdRoute + '/sec-c/about': typeof SecCAboutRoute + '/sec-c/settings': typeof SecCSettingsRoute + '/sec-d/$id': typeof SecDIdRoute + '/sec-d/about': typeof SecDAboutRoute + '/sec-d/settings': typeof SecDSettingsRoute + '/sec-e/$id': typeof SecEIdRoute + '/sec-e/about': typeof SecEAboutRoute + '/sec-e/settings': typeof SecESettingsRoute + '/sec-f/$id': typeof SecFIdRoute + '/sec-f/about': typeof SecFAboutRoute + '/sec-f/settings': typeof SecFSettingsRoute + '/sec-a/': typeof SecAIndexRoute + '/sec-b/': typeof SecBIndexRoute + '/sec-c/': typeof SecCIndexRoute + '/sec-d/': typeof SecDIndexRoute + '/sec-e/': typeof SecEIndexRoute + '/sec-f/': typeof SecFIndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/sec-a' + | '/sec-b' + | '/sec-c' + | '/sec-d' + | '/sec-e' + | '/sec-f' + | '/pricing' + | '/promo' + | '/alpha' + | '/beta' + | '/files/$' + | '/release/v{$version}' + | '/sec-a/$id' + | '/sec-a/about' + | '/sec-a/settings' + | '/sec-b/$id' + | '/sec-b/about' + | '/sec-b/settings' + | '/sec-c/$id' + | '/sec-c/about' + | '/sec-c/settings' + | '/sec-d/$id' + | '/sec-d/about' + | '/sec-d/settings' + | '/sec-e/$id' + | '/sec-e/about' + | '/sec-e/settings' + | '/sec-f/$id' + | '/sec-f/about' + | '/sec-f/settings' + | '/sec-a/' + | '/sec-b/' + | '/sec-c/' + | '/sec-d/' + | '/sec-e/' + | '/sec-f/' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/pricing' + | '/promo' + | '/alpha' + | '/beta' + | '/files/$' + | '/release/v{$version}' + | '/sec-a/$id' + | '/sec-a/about' + | '/sec-a/settings' + | '/sec-b/$id' + | '/sec-b/about' + | '/sec-b/settings' + | '/sec-c/$id' + | '/sec-c/about' + | '/sec-c/settings' + | '/sec-d/$id' + | '/sec-d/about' + | '/sec-d/settings' + | '/sec-e/$id' + | '/sec-e/about' + | '/sec-e/settings' + | '/sec-f/$id' + | '/sec-f/about' + | '/sec-f/settings' + | '/sec-a' + | '/sec-b' + | '/sec-c' + | '/sec-d' + | '/sec-e' + | '/sec-f' + id: + | '__root__' + | '/' + | '/_layout' + | '/sec-a' + | '/sec-b' + | '/sec-c' + | '/sec-d' + | '/sec-e' + | '/sec-f' + | '/(marketing)/pricing' + | '/(marketing)/promo' + | '/_layout/alpha' + | '/_layout/beta' + | '/files/$' + | '/release/v{$version}' + | '/sec-a/$id' + | '/sec-a/about' + | '/sec-a/settings' + | '/sec-b/$id' + | '/sec-b/about' + | '/sec-b/settings' + | '/sec-c/$id' + | '/sec-c/about' + | '/sec-c/settings' + | '/sec-d/$id' + | '/sec-d/about' + | '/sec-d/settings' + | '/sec-e/$id' + | '/sec-e/about' + | '/sec-e/settings' + | '/sec-f/$id' + | '/sec-f/about' + | '/sec-f/settings' + | '/sec-a/' + | '/sec-b/' + | '/sec-c/' + | '/sec-d/' + | '/sec-e/' + | '/sec-f/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + LayoutRoute: typeof LayoutRouteWithChildren + SecARoute: typeof SecARouteWithChildren + SecBRoute: typeof SecBRouteWithChildren + SecCRoute: typeof SecCRouteWithChildren + SecDRoute: typeof SecDRouteWithChildren + SecERoute: typeof SecERouteWithChildren + SecFRoute: typeof SecFRouteWithChildren + marketingPricingRoute: typeof marketingPricingRoute + marketingPromoRoute: typeof marketingPromoRoute + FilesSplatRoute: typeof FilesSplatRoute + ReleaseVChar123versionChar125Route: typeof ReleaseVChar123versionChar125Route +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout': { + id: '/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-a': { + id: '/sec-a' + path: '/sec-a' + fullPath: '/sec-a' + preLoaderRoute: typeof SecARouteImport + parentRoute: typeof rootRouteImport + } + '/sec-b': { + id: '/sec-b' + path: '/sec-b' + fullPath: '/sec-b' + preLoaderRoute: typeof SecBRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-c': { + id: '/sec-c' + path: '/sec-c' + fullPath: '/sec-c' + preLoaderRoute: typeof SecCRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-d': { + id: '/sec-d' + path: '/sec-d' + fullPath: '/sec-d' + preLoaderRoute: typeof SecDRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-e': { + id: '/sec-e' + path: '/sec-e' + fullPath: '/sec-e' + preLoaderRoute: typeof SecERouteImport + parentRoute: typeof rootRouteImport + } + '/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/' + path: '/' + fullPath: '/sec-a/' + preLoaderRoute: typeof SecAIndexRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/$id': { + id: '/sec-a/$id' + path: '/$id' + fullPath: '/sec-a/$id' + preLoaderRoute: typeof SecAIdRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/about': { + id: '/sec-a/about' + path: '/about' + fullPath: '/sec-a/about' + preLoaderRoute: typeof SecAAboutRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/settings': { + id: '/sec-a/settings' + path: '/settings' + fullPath: '/sec-a/settings' + preLoaderRoute: typeof SecASettingsRouteImport + parentRoute: typeof SecARoute + } + '/sec-b/': { + id: '/sec-b/' + path: '/' + fullPath: '/sec-b/' + preLoaderRoute: typeof SecBIndexRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/$id': { + id: '/sec-b/$id' + path: '/$id' + fullPath: '/sec-b/$id' + preLoaderRoute: typeof SecBIdRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/about': { + id: '/sec-b/about' + path: '/about' + fullPath: '/sec-b/about' + preLoaderRoute: typeof SecBAboutRouteImport + parentRoute: typeof SecBRoute + } + '/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 + } + } +} + +interface LayoutRouteChildren { + LayoutAlphaRoute: typeof LayoutAlphaRoute + LayoutBetaRoute: typeof LayoutBetaRoute +} + +const LayoutRouteChildren: LayoutRouteChildren = { + LayoutAlphaRoute: LayoutAlphaRoute, + LayoutBetaRoute: LayoutBetaRoute, +} + +const LayoutRouteWithChildren = + LayoutRoute._addFileChildren(LayoutRouteChildren) + +interface SecARouteChildren { + SecAIdRoute: typeof SecAIdRoute + SecAAboutRoute: typeof SecAAboutRoute + SecASettingsRoute: typeof SecASettingsRoute + SecAIndexRoute: typeof SecAIndexRoute +} + +const SecARouteChildren: SecARouteChildren = { + SecAIdRoute: SecAIdRoute, + SecAAboutRoute: SecAAboutRoute, + SecASettingsRoute: SecASettingsRoute, + SecAIndexRoute: SecAIndexRoute, +} + +const SecARouteWithChildren = SecARoute._addFileChildren(SecARouteChildren) + +interface SecBRouteChildren { + SecBIdRoute: typeof SecBIdRoute + SecBAboutRoute: typeof SecBAboutRoute + SecBSettingsRoute: typeof SecBSettingsRoute + SecBIndexRoute: typeof SecBIndexRoute +} + +const SecBRouteChildren: SecBRouteChildren = { + SecBIdRoute: SecBIdRoute, + SecBAboutRoute: SecBAboutRoute, + SecBSettingsRoute: SecBSettingsRoute, + SecBIndexRoute: SecBIndexRoute, +} + +const SecBRouteWithChildren = SecBRoute._addFileChildren(SecBRouteChildren) + +interface SecCRouteChildren { + SecCIdRoute: typeof SecCIdRoute + SecCAboutRoute: typeof SecCAboutRoute + SecCSettingsRoute: typeof SecCSettingsRoute + SecCIndexRoute: typeof SecCIndexRoute +} + +const SecCRouteChildren: SecCRouteChildren = { + SecCIdRoute: SecCIdRoute, + SecCAboutRoute: SecCAboutRoute, + SecCSettingsRoute: SecCSettingsRoute, + SecCIndexRoute: SecCIndexRoute, +} + +const SecCRouteWithChildren = SecCRoute._addFileChildren(SecCRouteChildren) + +interface SecDRouteChildren { + SecDIdRoute: typeof SecDIdRoute + SecDAboutRoute: typeof SecDAboutRoute + SecDSettingsRoute: typeof SecDSettingsRoute + SecDIndexRoute: typeof SecDIndexRoute +} + +const SecDRouteChildren: SecDRouteChildren = { + SecDIdRoute: SecDIdRoute, + SecDAboutRoute: SecDAboutRoute, + SecDSettingsRoute: SecDSettingsRoute, + SecDIndexRoute: SecDIndexRoute, +} + +const SecDRouteWithChildren = SecDRoute._addFileChildren(SecDRouteChildren) + +interface SecERouteChildren { + SecEIdRoute: typeof SecEIdRoute + SecEAboutRoute: typeof SecEAboutRoute + SecESettingsRoute: typeof SecESettingsRoute + SecEIndexRoute: typeof SecEIndexRoute +} + +const SecERouteChildren: SecERouteChildren = { + SecEIdRoute: SecEIdRoute, + SecEAboutRoute: SecEAboutRoute, + SecESettingsRoute: SecESettingsRoute, + SecEIndexRoute: SecEIndexRoute, +} + +const SecERouteWithChildren = SecERoute._addFileChildren(SecERouteChildren) + +interface SecFRouteChildren { + SecFIdRoute: typeof SecFIdRoute + SecFAboutRoute: typeof SecFAboutRoute + SecFSettingsRoute: typeof SecFSettingsRoute + SecFIndexRoute: typeof SecFIndexRoute +} + +const SecFRouteChildren: SecFRouteChildren = { + SecFIdRoute: SecFIdRoute, + SecFAboutRoute: SecFAboutRoute, + SecFSettingsRoute: SecFSettingsRoute, + SecFIndexRoute: SecFIndexRoute, +} + +const SecFRouteWithChildren = SecFRoute._addFileChildren(SecFRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + LayoutRoute: LayoutRouteWithChildren, + SecARoute: SecARouteWithChildren, + SecBRoute: SecBRouteWithChildren, + SecCRoute: SecCRouteWithChildren, + SecDRoute: SecDRouteWithChildren, + SecERoute: SecERouteWithChildren, + SecFRoute: SecFRouteWithChildren, + marketingPricingRoute: marketingPricingRoute, + marketingPromoRoute: marketingPromoRoute, + FilesSplatRoute: FilesSplatRoute, + ReleaseVChar123versionChar125Route: ReleaseVChar123versionChar125Route, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/(marketing)/pricing.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/(marketing)/pricing.tsx new file mode 100644 index 0000000000..ac2a376549 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/(marketing)/pricing.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/(marketing)/pricing')({ + component: Page, +}) + +function Page() { + return
pricing
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/(marketing)/promo.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/(marketing)/promo.tsx new file mode 100644 index 0000000000..b71962254e --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/(marketing)/promo.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/(marketing)/promo')({ + component: Page, +}) + +function Page() { + return
promo
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/__root.tsx new file mode 100644 index 0000000000..7ed47da924 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/__root.tsx @@ -0,0 +1,58 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/react-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.alpha.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.alpha.tsx new file mode 100644 index 0000000000..893419cef5 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.alpha.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/_layout/alpha')({ + component: Page, +}) + +function Page() { + return
alpha
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.beta.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.beta.tsx new file mode 100644 index 0000000000..d20c6007ee --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.beta.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/_layout/beta')({ + component: Page, +}) + +function Page() { + return
beta
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.tsx new file mode 100644 index 0000000000..961feb50f1 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/_layout.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/_layout')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/files.$.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/files.$.tsx new file mode 100644 index 0000000000..028aa43d5a --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/files.$.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/files/$')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`files:${params._splat}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/index.tsx new file mode 100644 index 0000000000..8a7ffca9e7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: Page, +}) + +function Page() { + return
home
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/release.v{$version}.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/release.v{$version}.tsx new file mode 100644 index 0000000000..dfe8e31905 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/release.v{$version}.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/release/v{$version}')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`release:${params.version}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.$id.tsx new file mode 100644 index 0000000000..8be053a040 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-a/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-a:${params.id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.about.tsx new file mode 100644 index 0000000000..54c1b28618 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-a/about')({ + component: Page, +}) + +function Page() { + return
sec-a:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.index.tsx new file mode 100644 index 0000000000..3c793a94f5 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-a/')({ + component: Page, +}) + +function Page() { + return
sec-a:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.settings.tsx new file mode 100644 index 0000000000..0037f6463d --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-a/settings')({ + component: Page, +}) + +function Page() { + return
sec-a:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.tsx new file mode 100644 index 0000000000..846f96b67b --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-a.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-a')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.$id.tsx new file mode 100644 index 0000000000..0dd7f94feb --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-b/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-b:${params.id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.about.tsx new file mode 100644 index 0000000000..fde4647472 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-b/about')({ + component: Page, +}) + +function Page() { + return
sec-b:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.index.tsx new file mode 100644 index 0000000000..51b69cf664 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-b/')({ + component: Page, +}) + +function Page() { + return
sec-b:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.settings.tsx new file mode 100644 index 0000000000..977b7438b1 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-b/settings')({ + component: Page, +}) + +function Page() { + return
sec-b:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.tsx new file mode 100644 index 0000000000..77d7e6475d --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-b.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-b')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.$id.tsx new file mode 100644 index 0000000000..eb3be796c0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-c/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-c:${params.id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.about.tsx new file mode 100644 index 0000000000..7910acf332 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-c/about')({ + component: Page, +}) + +function Page() { + return
sec-c:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.index.tsx new file mode 100644 index 0000000000..f6ae102f2d --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-c/')({ + component: Page, +}) + +function Page() { + return
sec-c:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.settings.tsx new file mode 100644 index 0000000000..bf2be30788 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-c/settings')({ + component: Page, +}) + +function Page() { + return
sec-c:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.tsx new file mode 100644 index 0000000000..77ac5644c6 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-c.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-c')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.$id.tsx new file mode 100644 index 0000000000..d34aee8972 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-d/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-d:${params.id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.about.tsx new file mode 100644 index 0000000000..1f095cb2ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-d/about')({ + component: Page, +}) + +function Page() { + return
sec-d:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.index.tsx new file mode 100644 index 0000000000..8fc698a4d4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-d/')({ + component: Page, +}) + +function Page() { + return
sec-d:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.settings.tsx new file mode 100644 index 0000000000..76c7a178ea --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-d/settings')({ + component: Page, +}) + +function Page() { + return
sec-d:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.tsx new file mode 100644 index 0000000000..5f3d281b5e --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-d.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-d')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.$id.tsx new file mode 100644 index 0000000000..6e31d0c5d1 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-e/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-e:${params.id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.about.tsx new file mode 100644 index 0000000000..5a2835917b --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-e/about')({ + component: Page, +}) + +function Page() { + return
sec-e:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.index.tsx new file mode 100644 index 0000000000..0f23b8d484 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-e/')({ + component: Page, +}) + +function Page() { + return
sec-e:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.settings.tsx new file mode 100644 index 0000000000..b566a1ffaa --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-e/settings')({ + component: Page, +}) + +function Page() { + return
sec-e:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.tsx new file mode 100644 index 0000000000..e573a71d98 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-e.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-e')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.$id.tsx new file mode 100644 index 0000000000..a71c17f96e --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-f/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-f:${params.id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.about.tsx new file mode 100644 index 0000000000..06831063ad --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-f/about')({ + component: Page, +}) + +function Page() { + return
sec-f:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.index.tsx new file mode 100644 index 0000000000..4cd54b6a7f --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-f/')({ + component: Page, +}) + +function Page() { + return
sec-f:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.settings.tsx new file mode 100644 index 0000000000..92bdca5e44 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-f/settings')({ + component: Page, +}) + +function Page() { + return
sec-f:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.tsx new file mode 100644 index 0000000000..2fa27873e8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/src/routes/sec-f.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/sec-f')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/tsconfig.json b/benchmarks/client-nav/scenarios/route-tree-scale/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/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/route-tree-scale/react/vite.config.ts b/benchmarks/client-nav/scenarios/route-tree-scale/react/vite.config.ts new file mode 100644 index 0000000000..0f588fda53 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/vite.config.ts @@ -0,0 +1,45 @@ +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', + // Real file-based apps code-split by default; this scenario keeps it on + // so navigations also exercise lazy route-chunk resolution. + autoCodeSplitting: true, + 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 route-tree-scale (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/shared.ts b/benchmarks/client-nav/scenarios/route-tree-scale/shared.ts new file mode 100644 index 0000000000..8af5996804 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/shared.ts @@ -0,0 +1,64 @@ +/** + * Shared definition of the `route-tree-scale` scenario: route matching, + * location building, and link-target resolution over a wide route tree + * (~40 routes) mixing static segments, dynamic params, prefixed params, + * splats, pathless layouts, and route groups. Navigations jump between + * distant branches so matching cannot reuse the previous branch. + */ + +export const sections = [ + 'sec-a', + 'sec-b', + 'sec-c', + 'sec-d', + 'sec-e', + 'sec-f', +] as const + +export const steps = [ + 'go-sec-a-id', + 'go-sec-f-settings', + 'go-files', + 'go-release', + 'go-alpha', + 'go-promo', + 'go-sec-c-id', + 'go-sec-d-about', + 'go-home', +] as const + +// The dynamic ids and the splat carry characters that need percent-encoding +// (spaces, `&`, `%`, `+`, unicode) so matching also exercises the segment +// encode/decode paths. +const expectedMarkers = [ + 'sec-a:item 11%', + 'sec-f:settings', + 'files:x/ü y/z', + 'release:9', + 'alpha', + 'promo', + 'sec-c:q&a+42', + 'sec-d:about', + 'home', +] as const + +export function assertStepResult(stepIndex: number) { + const expected = expectedMarkers[stepIndex]! + const actual = document.querySelector( + '[data-testid="scale-state"]', + )?.textContent + if (actual !== expected) { + throw new Error( + `Expected scale-state marker "${expected}" after step ${stepIndex}, received "${actual}"`, + ) + } +} + +// Three laps through the 9-step sequence per benchmark iteration. +export const ticksPerIteration = 27 + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/project.json b/benchmarks/client-nav/scenarios/route-tree-scale/solid/project.json new file mode 100644 index 0000000000..c568e41196 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-route-tree-scale-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/route-tree-scale/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/setup.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/setup.ts new file mode 100644 index 0000000000..6a46971603 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } 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, + assertAfterStep: assertStepResult, + }) +} 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 new file mode 100644 index 0000000000..9244ef1350 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/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-route-tree-scale', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-route-tree-scale 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/route-tree-scale/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/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/route-tree-scale/solid/src/main.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/main.tsx new file mode 100644 index 0000000000..fa9d239418 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/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/route-tree-scale/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..e6f3596562 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts @@ -0,0 +1,881 @@ +/* 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 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 IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const SecARoute = SecARouteImport.update({ + id: '/sec-a', + path: '/sec-a', + getParentRoute: () => rootRouteImport, +} as any) +const SecBRoute = SecBRouteImport.update({ + id: '/sec-b', + path: '/sec-b', + getParentRoute: () => rootRouteImport, +} as any) +const SecCRoute = SecCRouteImport.update({ + id: '/sec-c', + path: '/sec-c', + getParentRoute: () => rootRouteImport, +} as any) +const SecDRoute = SecDRouteImport.update({ + id: '/sec-d', + path: '/sec-d', + getParentRoute: () => rootRouteImport, +} as any) +const SecERoute = SecERouteImport.update({ + id: '/sec-e', + path: '/sec-e', + getParentRoute: () => rootRouteImport, +} as any) +const SecFRoute = SecFRouteImport.update({ + id: '/sec-f', + path: '/sec-f', + getParentRoute: () => rootRouteImport, +} as any) +const marketingPricingRoute = marketingPricingRouteImport.update({ + id: '/(marketing)/pricing', + path: '/pricing', + getParentRoute: () => rootRouteImport, +} as any) +const marketingPromoRoute = marketingPromoRouteImport.update({ + id: '/(marketing)/promo', + path: '/promo', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ + id: '/alpha', + path: '/alpha', + getParentRoute: () => LayoutRoute, +} as any) +const LayoutBetaRoute = LayoutBetaRouteImport.update({ + id: '/beta', + path: '/beta', + getParentRoute: () => LayoutRoute, +} as any) +const FilesSplatRoute = FilesSplatRouteImport.update({ + id: '/files/$', + path: '/files/$', + getParentRoute: () => rootRouteImport, +} as any) +const ReleaseVChar123versionChar125Route = + ReleaseVChar123versionChar125RouteImport.update({ + id: '/release/v{$version}', + path: '/release/v{$version}', + getParentRoute: () => rootRouteImport, + } as any) +const SecAIndexRoute = SecAIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecARoute, +} as any) +const SecAIdRoute = SecAIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecARoute, +} as any) +const SecAAboutRoute = SecAAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecARoute, +} as any) +const SecASettingsRoute = SecASettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecARoute, +} as any) +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 { + '/': typeof IndexRoute + '/sec-a': typeof SecARouteWithChildren + '/sec-b': typeof SecBRouteWithChildren + '/sec-c': typeof SecCRouteWithChildren + '/sec-d': typeof SecDRouteWithChildren + '/sec-e': typeof SecERouteWithChildren + '/sec-f': typeof SecFRouteWithChildren + '/pricing': typeof marketingPricingRoute + '/promo': typeof marketingPromoRoute + '/alpha': typeof LayoutAlphaRoute + '/beta': typeof LayoutBetaRoute + '/files/$': typeof FilesSplatRoute + '/release/v{$version}': typeof ReleaseVChar123versionChar125Route + '/sec-a/$id': typeof SecAIdRoute + '/sec-a/about': typeof SecAAboutRoute + '/sec-a/settings': typeof SecASettingsRoute + '/sec-b/$id': typeof SecBIdRoute + '/sec-b/about': typeof SecBAboutRoute + '/sec-b/settings': typeof SecBSettingsRoute + '/sec-c/$id': typeof SecCIdRoute + '/sec-c/about': typeof SecCAboutRoute + '/sec-c/settings': typeof SecCSettingsRoute + '/sec-d/$id': typeof SecDIdRoute + '/sec-d/about': typeof SecDAboutRoute + '/sec-d/settings': typeof SecDSettingsRoute + '/sec-e/$id': typeof SecEIdRoute + '/sec-e/about': typeof SecEAboutRoute + '/sec-e/settings': typeof SecESettingsRoute + '/sec-f/$id': typeof SecFIdRoute + '/sec-f/about': typeof SecFAboutRoute + '/sec-f/settings': typeof SecFSettingsRoute + '/sec-a/': typeof SecAIndexRoute + '/sec-b/': typeof SecBIndexRoute + '/sec-c/': typeof SecCIndexRoute + '/sec-d/': typeof SecDIndexRoute + '/sec-e/': typeof SecEIndexRoute + '/sec-f/': typeof SecFIndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/pricing': typeof marketingPricingRoute + '/promo': typeof marketingPromoRoute + '/alpha': typeof LayoutAlphaRoute + '/beta': typeof LayoutBetaRoute + '/files/$': typeof FilesSplatRoute + '/release/v{$version}': typeof ReleaseVChar123versionChar125Route + '/sec-a/$id': typeof SecAIdRoute + '/sec-a/about': typeof SecAAboutRoute + '/sec-a/settings': typeof SecASettingsRoute + '/sec-b/$id': typeof SecBIdRoute + '/sec-b/about': typeof SecBAboutRoute + '/sec-b/settings': typeof SecBSettingsRoute + '/sec-c/$id': typeof SecCIdRoute + '/sec-c/about': typeof SecCAboutRoute + '/sec-c/settings': typeof SecCSettingsRoute + '/sec-d/$id': typeof SecDIdRoute + '/sec-d/about': typeof SecDAboutRoute + '/sec-d/settings': typeof SecDSettingsRoute + '/sec-e/$id': typeof SecEIdRoute + '/sec-e/about': typeof SecEAboutRoute + '/sec-e/settings': typeof SecESettingsRoute + '/sec-f/$id': typeof SecFIdRoute + '/sec-f/about': typeof SecFAboutRoute + '/sec-f/settings': typeof SecFSettingsRoute + '/sec-a': typeof SecAIndexRoute + '/sec-b': typeof SecBIndexRoute + '/sec-c': typeof SecCIndexRoute + '/sec-d': typeof SecDIndexRoute + '/sec-e': typeof SecEIndexRoute + '/sec-f': typeof SecFIndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/_layout': typeof LayoutRouteWithChildren + '/sec-a': typeof SecARouteWithChildren + '/sec-b': typeof SecBRouteWithChildren + '/sec-c': typeof SecCRouteWithChildren + '/sec-d': typeof SecDRouteWithChildren + '/sec-e': typeof SecERouteWithChildren + '/sec-f': typeof SecFRouteWithChildren + '/(marketing)/pricing': typeof marketingPricingRoute + '/(marketing)/promo': typeof marketingPromoRoute + '/_layout/alpha': typeof LayoutAlphaRoute + '/_layout/beta': typeof LayoutBetaRoute + '/files/$': typeof FilesSplatRoute + '/release/v{$version}': typeof ReleaseVChar123versionChar125Route + '/sec-a/$id': typeof SecAIdRoute + '/sec-a/about': typeof SecAAboutRoute + '/sec-a/settings': typeof SecASettingsRoute + '/sec-b/$id': typeof SecBIdRoute + '/sec-b/about': typeof SecBAboutRoute + '/sec-b/settings': typeof SecBSettingsRoute + '/sec-c/$id': typeof SecCIdRoute + '/sec-c/about': typeof SecCAboutRoute + '/sec-c/settings': typeof SecCSettingsRoute + '/sec-d/$id': typeof SecDIdRoute + '/sec-d/about': typeof SecDAboutRoute + '/sec-d/settings': typeof SecDSettingsRoute + '/sec-e/$id': typeof SecEIdRoute + '/sec-e/about': typeof SecEAboutRoute + '/sec-e/settings': typeof SecESettingsRoute + '/sec-f/$id': typeof SecFIdRoute + '/sec-f/about': typeof SecFAboutRoute + '/sec-f/settings': typeof SecFSettingsRoute + '/sec-a/': typeof SecAIndexRoute + '/sec-b/': typeof SecBIndexRoute + '/sec-c/': typeof SecCIndexRoute + '/sec-d/': typeof SecDIndexRoute + '/sec-e/': typeof SecEIndexRoute + '/sec-f/': typeof SecFIndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/sec-a' + | '/sec-b' + | '/sec-c' + | '/sec-d' + | '/sec-e' + | '/sec-f' + | '/pricing' + | '/promo' + | '/alpha' + | '/beta' + | '/files/$' + | '/release/v{$version}' + | '/sec-a/$id' + | '/sec-a/about' + | '/sec-a/settings' + | '/sec-b/$id' + | '/sec-b/about' + | '/sec-b/settings' + | '/sec-c/$id' + | '/sec-c/about' + | '/sec-c/settings' + | '/sec-d/$id' + | '/sec-d/about' + | '/sec-d/settings' + | '/sec-e/$id' + | '/sec-e/about' + | '/sec-e/settings' + | '/sec-f/$id' + | '/sec-f/about' + | '/sec-f/settings' + | '/sec-a/' + | '/sec-b/' + | '/sec-c/' + | '/sec-d/' + | '/sec-e/' + | '/sec-f/' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/pricing' + | '/promo' + | '/alpha' + | '/beta' + | '/files/$' + | '/release/v{$version}' + | '/sec-a/$id' + | '/sec-a/about' + | '/sec-a/settings' + | '/sec-b/$id' + | '/sec-b/about' + | '/sec-b/settings' + | '/sec-c/$id' + | '/sec-c/about' + | '/sec-c/settings' + | '/sec-d/$id' + | '/sec-d/about' + | '/sec-d/settings' + | '/sec-e/$id' + | '/sec-e/about' + | '/sec-e/settings' + | '/sec-f/$id' + | '/sec-f/about' + | '/sec-f/settings' + | '/sec-a' + | '/sec-b' + | '/sec-c' + | '/sec-d' + | '/sec-e' + | '/sec-f' + id: + | '__root__' + | '/' + | '/_layout' + | '/sec-a' + | '/sec-b' + | '/sec-c' + | '/sec-d' + | '/sec-e' + | '/sec-f' + | '/(marketing)/pricing' + | '/(marketing)/promo' + | '/_layout/alpha' + | '/_layout/beta' + | '/files/$' + | '/release/v{$version}' + | '/sec-a/$id' + | '/sec-a/about' + | '/sec-a/settings' + | '/sec-b/$id' + | '/sec-b/about' + | '/sec-b/settings' + | '/sec-c/$id' + | '/sec-c/about' + | '/sec-c/settings' + | '/sec-d/$id' + | '/sec-d/about' + | '/sec-d/settings' + | '/sec-e/$id' + | '/sec-e/about' + | '/sec-e/settings' + | '/sec-f/$id' + | '/sec-f/about' + | '/sec-f/settings' + | '/sec-a/' + | '/sec-b/' + | '/sec-c/' + | '/sec-d/' + | '/sec-e/' + | '/sec-f/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + LayoutRoute: typeof LayoutRouteWithChildren + SecARoute: typeof SecARouteWithChildren + SecBRoute: typeof SecBRouteWithChildren + SecCRoute: typeof SecCRouteWithChildren + SecDRoute: typeof SecDRouteWithChildren + SecERoute: typeof SecERouteWithChildren + SecFRoute: typeof SecFRouteWithChildren + marketingPricingRoute: typeof marketingPricingRoute + marketingPromoRoute: typeof marketingPromoRoute + FilesSplatRoute: typeof FilesSplatRoute + ReleaseVChar123versionChar125Route: typeof ReleaseVChar123versionChar125Route +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout': { + id: '/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-a': { + id: '/sec-a' + path: '/sec-a' + fullPath: '/sec-a' + preLoaderRoute: typeof SecARouteImport + parentRoute: typeof rootRouteImport + } + '/sec-b': { + id: '/sec-b' + path: '/sec-b' + fullPath: '/sec-b' + preLoaderRoute: typeof SecBRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-c': { + id: '/sec-c' + path: '/sec-c' + fullPath: '/sec-c' + preLoaderRoute: typeof SecCRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-d': { + id: '/sec-d' + path: '/sec-d' + fullPath: '/sec-d' + preLoaderRoute: typeof SecDRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-e': { + id: '/sec-e' + path: '/sec-e' + fullPath: '/sec-e' + preLoaderRoute: typeof SecERouteImport + parentRoute: typeof rootRouteImport + } + '/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/' + path: '/' + fullPath: '/sec-a/' + preLoaderRoute: typeof SecAIndexRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/$id': { + id: '/sec-a/$id' + path: '/$id' + fullPath: '/sec-a/$id' + preLoaderRoute: typeof SecAIdRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/about': { + id: '/sec-a/about' + path: '/about' + fullPath: '/sec-a/about' + preLoaderRoute: typeof SecAAboutRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/settings': { + id: '/sec-a/settings' + path: '/settings' + fullPath: '/sec-a/settings' + preLoaderRoute: typeof SecASettingsRouteImport + parentRoute: typeof SecARoute + } + '/sec-b/': { + id: '/sec-b/' + path: '/' + fullPath: '/sec-b/' + preLoaderRoute: typeof SecBIndexRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/$id': { + id: '/sec-b/$id' + path: '/$id' + fullPath: '/sec-b/$id' + preLoaderRoute: typeof SecBIdRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/about': { + id: '/sec-b/about' + path: '/about' + fullPath: '/sec-b/about' + preLoaderRoute: typeof SecBAboutRouteImport + parentRoute: typeof SecBRoute + } + '/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 + } + } +} + +interface LayoutRouteChildren { + LayoutAlphaRoute: typeof LayoutAlphaRoute + LayoutBetaRoute: typeof LayoutBetaRoute +} + +const LayoutRouteChildren: LayoutRouteChildren = { + LayoutAlphaRoute: LayoutAlphaRoute, + LayoutBetaRoute: LayoutBetaRoute, +} + +const LayoutRouteWithChildren = + LayoutRoute._addFileChildren(LayoutRouteChildren) + +interface SecARouteChildren { + SecAIdRoute: typeof SecAIdRoute + SecAAboutRoute: typeof SecAAboutRoute + SecASettingsRoute: typeof SecASettingsRoute + SecAIndexRoute: typeof SecAIndexRoute +} + +const SecARouteChildren: SecARouteChildren = { + SecAIdRoute: SecAIdRoute, + SecAAboutRoute: SecAAboutRoute, + SecASettingsRoute: SecASettingsRoute, + SecAIndexRoute: SecAIndexRoute, +} + +const SecARouteWithChildren = SecARoute._addFileChildren(SecARouteChildren) + +interface SecBRouteChildren { + SecBIdRoute: typeof SecBIdRoute + SecBAboutRoute: typeof SecBAboutRoute + SecBSettingsRoute: typeof SecBSettingsRoute + SecBIndexRoute: typeof SecBIndexRoute +} + +const SecBRouteChildren: SecBRouteChildren = { + SecBIdRoute: SecBIdRoute, + SecBAboutRoute: SecBAboutRoute, + SecBSettingsRoute: SecBSettingsRoute, + SecBIndexRoute: SecBIndexRoute, +} + +const SecBRouteWithChildren = SecBRoute._addFileChildren(SecBRouteChildren) + +interface SecCRouteChildren { + SecCIdRoute: typeof SecCIdRoute + SecCAboutRoute: typeof SecCAboutRoute + SecCSettingsRoute: typeof SecCSettingsRoute + SecCIndexRoute: typeof SecCIndexRoute +} + +const SecCRouteChildren: SecCRouteChildren = { + SecCIdRoute: SecCIdRoute, + SecCAboutRoute: SecCAboutRoute, + SecCSettingsRoute: SecCSettingsRoute, + SecCIndexRoute: SecCIndexRoute, +} + +const SecCRouteWithChildren = SecCRoute._addFileChildren(SecCRouteChildren) + +interface SecDRouteChildren { + SecDIdRoute: typeof SecDIdRoute + SecDAboutRoute: typeof SecDAboutRoute + SecDSettingsRoute: typeof SecDSettingsRoute + SecDIndexRoute: typeof SecDIndexRoute +} + +const SecDRouteChildren: SecDRouteChildren = { + SecDIdRoute: SecDIdRoute, + SecDAboutRoute: SecDAboutRoute, + SecDSettingsRoute: SecDSettingsRoute, + SecDIndexRoute: SecDIndexRoute, +} + +const SecDRouteWithChildren = SecDRoute._addFileChildren(SecDRouteChildren) + +interface SecERouteChildren { + SecEIdRoute: typeof SecEIdRoute + SecEAboutRoute: typeof SecEAboutRoute + SecESettingsRoute: typeof SecESettingsRoute + SecEIndexRoute: typeof SecEIndexRoute +} + +const SecERouteChildren: SecERouteChildren = { + SecEIdRoute: SecEIdRoute, + SecEAboutRoute: SecEAboutRoute, + SecESettingsRoute: SecESettingsRoute, + SecEIndexRoute: SecEIndexRoute, +} + +const SecERouteWithChildren = SecERoute._addFileChildren(SecERouteChildren) + +interface SecFRouteChildren { + SecFIdRoute: typeof SecFIdRoute + SecFAboutRoute: typeof SecFAboutRoute + SecFSettingsRoute: typeof SecFSettingsRoute + SecFIndexRoute: typeof SecFIndexRoute +} + +const SecFRouteChildren: SecFRouteChildren = { + SecFIdRoute: SecFIdRoute, + SecFAboutRoute: SecFAboutRoute, + SecFSettingsRoute: SecFSettingsRoute, + SecFIndexRoute: SecFIndexRoute, +} + +const SecFRouteWithChildren = SecFRoute._addFileChildren(SecFRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + LayoutRoute: LayoutRouteWithChildren, + SecARoute: SecARouteWithChildren, + SecBRoute: SecBRouteWithChildren, + SecCRoute: SecCRouteWithChildren, + SecDRoute: SecDRouteWithChildren, + SecERoute: SecERouteWithChildren, + SecFRoute: SecFRouteWithChildren, + marketingPricingRoute: marketingPricingRoute, + marketingPromoRoute: marketingPromoRoute, + FilesSplatRoute: FilesSplatRoute, + ReleaseVChar123versionChar125Route: ReleaseVChar123versionChar125Route, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/(marketing)/pricing.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/(marketing)/pricing.tsx new file mode 100644 index 0000000000..0965507de6 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/(marketing)/pricing.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/(marketing)/pricing')({ + component: Page, +}) + +function Page() { + return
pricing
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/(marketing)/promo.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/(marketing)/promo.tsx new file mode 100644 index 0000000000..220bd06a68 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/(marketing)/promo.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/(marketing)/promo')({ + component: Page, +}) + +function Page() { + return
promo
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..a4e4113d9a --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/__root.tsx @@ -0,0 +1,58 @@ +import { Link, Outlet, createRootRoute } from '@tanstack/solid-router' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.alpha.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.alpha.tsx new file mode 100644 index 0000000000..234b8488a9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.alpha.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/_layout/alpha')({ + component: Page, +}) + +function Page() { + return
alpha
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.beta.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.beta.tsx new file mode 100644 index 0000000000..39bc716efa --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.beta.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/_layout/beta')({ + component: Page, +}) + +function Page() { + return
beta
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.tsx new file mode 100644 index 0000000000..f1e499d3b3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/_layout.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/_layout')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/files.$.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/files.$.tsx new file mode 100644 index 0000000000..47b1a5eea9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/files.$.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/files/$')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`files:${params()._splat}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/index.tsx new file mode 100644 index 0000000000..25b1c03c1a --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: Page, +}) + +function Page() { + return
home
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/release.v{$version}.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/release.v{$version}.tsx new file mode 100644 index 0000000000..0dbcee35ca --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/release.v{$version}.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/release/v{$version}')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`release:${params().version}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.$id.tsx new file mode 100644 index 0000000000..18731a2844 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-a/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-a:${params().id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.about.tsx new file mode 100644 index 0000000000..1699360a1c --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-a/about')({ + component: Page, +}) + +function Page() { + return
sec-a:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.index.tsx new file mode 100644 index 0000000000..e71e525d07 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-a/')({ + component: Page, +}) + +function Page() { + return
sec-a:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.settings.tsx new file mode 100644 index 0000000000..49d470190e --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-a/settings')({ + component: Page, +}) + +function Page() { + return
sec-a:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.tsx new file mode 100644 index 0000000000..2861169fb9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-a.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-a')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.$id.tsx new file mode 100644 index 0000000000..86fe71d7c0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-b/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-b:${params().id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.about.tsx new file mode 100644 index 0000000000..586b829cd0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-b/about')({ + component: Page, +}) + +function Page() { + return
sec-b:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.index.tsx new file mode 100644 index 0000000000..7098416658 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-b/')({ + component: Page, +}) + +function Page() { + return
sec-b:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.settings.tsx new file mode 100644 index 0000000000..c2e0f47650 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-b/settings')({ + component: Page, +}) + +function Page() { + return
sec-b:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.tsx new file mode 100644 index 0000000000..f2905da9ca --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-b.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-b')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.$id.tsx new file mode 100644 index 0000000000..3e07e8033a --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-c/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-c:${params().id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.about.tsx new file mode 100644 index 0000000000..86ed5043a3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-c/about')({ + component: Page, +}) + +function Page() { + return
sec-c:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.index.tsx new file mode 100644 index 0000000000..aa9ed2dc6c --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-c/')({ + component: Page, +}) + +function Page() { + return
sec-c:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.settings.tsx new file mode 100644 index 0000000000..d0dd3e952c --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-c/settings')({ + component: Page, +}) + +function Page() { + return
sec-c:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.tsx new file mode 100644 index 0000000000..fa53825238 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-c.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-c')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.$id.tsx new file mode 100644 index 0000000000..3722012d7c --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-d/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-d:${params().id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.about.tsx new file mode 100644 index 0000000000..860d2b9e5b --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-d/about')({ + component: Page, +}) + +function Page() { + return
sec-d:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.index.tsx new file mode 100644 index 0000000000..ec7b8eaf2c --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-d/')({ + component: Page, +}) + +function Page() { + return
sec-d:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.settings.tsx new file mode 100644 index 0000000000..d83e3885fd --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-d/settings')({ + component: Page, +}) + +function Page() { + return
sec-d:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.tsx new file mode 100644 index 0000000000..e71391e2a3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-d.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-d')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.$id.tsx new file mode 100644 index 0000000000..e58d9d77ac --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-e/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-e:${params().id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.about.tsx new file mode 100644 index 0000000000..3ef4d2c763 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-e/about')({ + component: Page, +}) + +function Page() { + return
sec-e:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.index.tsx new file mode 100644 index 0000000000..88bf7ca271 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-e/')({ + component: Page, +}) + +function Page() { + return
sec-e:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.settings.tsx new file mode 100644 index 0000000000..8a9945926d --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-e/settings')({ + component: Page, +}) + +function Page() { + return
sec-e:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.tsx new file mode 100644 index 0000000000..8b5ef24519 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-e.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-e')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.$id.tsx new file mode 100644 index 0000000000..2b81ef96ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.$id.tsx @@ -0,0 +1,11 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-f/$id')({ + component: Page, +}) + +function Page() { + const params = Route.useParams() + + return
{`sec-f:${params().id}`}
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.about.tsx new file mode 100644 index 0000000000..1c4e3a5474 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.about.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-f/about')({ + component: Page, +}) + +function Page() { + return
sec-f:about
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.index.tsx new file mode 100644 index 0000000000..65803ee848 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.index.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-f/')({ + component: Page, +}) + +function Page() { + return
sec-f:index
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.settings.tsx new file mode 100644 index 0000000000..5761138262 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.settings.tsx @@ -0,0 +1,9 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-f/settings')({ + component: Page, +}) + +function Page() { + return
sec-f:settings
+} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.tsx new file mode 100644 index 0000000000..c7f25eecdd --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routes/sec-f.tsx @@ -0,0 +1,9 @@ +import { Outlet, createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/sec-f')({ + component: Layout, +}) + +function Layout() { + return +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/tsconfig.json b/benchmarks/client-nav/scenarios/route-tree-scale/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/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/route-tree-scale/solid/vite.config.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/vite.config.ts new file mode 100644 index 0000000000..542ede131b --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/vite.config.ts @@ -0,0 +1,53 @@ +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', + // Real file-based apps code-split by default; this scenario keeps it on + // so navigations also exercise lazy route-chunk resolution. + autoCodeSplitting: true, + 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 route-tree-scale (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/project.json b/benchmarks/client-nav/scenarios/route-tree-scale/vue/project.json new file mode 100644 index 0000000000..f613070038 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-route-tree-scale-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/route-tree-scale/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/setup.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/setup.ts new file mode 100644 index 0000000000..97b74b3892 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } 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, + assertAfterStep: assertStepResult, + }) +} 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 new file mode 100644 index 0000000000..331e8e008f --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/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-route-tree-scale', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-route-tree-scale 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/route-tree-scale/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/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/route-tree-scale/vue/src/main.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/main.tsx new file mode 100644 index 0000000000..cae9b54f1d --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/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/route-tree-scale/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..a12f981bb4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts @@ -0,0 +1,881 @@ +/* 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 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 IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const SecARoute = SecARouteImport.update({ + id: '/sec-a', + path: '/sec-a', + getParentRoute: () => rootRouteImport, +} as any) +const SecBRoute = SecBRouteImport.update({ + id: '/sec-b', + path: '/sec-b', + getParentRoute: () => rootRouteImport, +} as any) +const SecCRoute = SecCRouteImport.update({ + id: '/sec-c', + path: '/sec-c', + getParentRoute: () => rootRouteImport, +} as any) +const SecDRoute = SecDRouteImport.update({ + id: '/sec-d', + path: '/sec-d', + getParentRoute: () => rootRouteImport, +} as any) +const SecERoute = SecERouteImport.update({ + id: '/sec-e', + path: '/sec-e', + getParentRoute: () => rootRouteImport, +} as any) +const SecFRoute = SecFRouteImport.update({ + id: '/sec-f', + path: '/sec-f', + getParentRoute: () => rootRouteImport, +} as any) +const marketingPricingRoute = marketingPricingRouteImport.update({ + id: '/(marketing)/pricing', + path: '/pricing', + getParentRoute: () => rootRouteImport, +} as any) +const marketingPromoRoute = marketingPromoRouteImport.update({ + id: '/(marketing)/promo', + path: '/promo', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ + id: '/alpha', + path: '/alpha', + getParentRoute: () => LayoutRoute, +} as any) +const LayoutBetaRoute = LayoutBetaRouteImport.update({ + id: '/beta', + path: '/beta', + getParentRoute: () => LayoutRoute, +} as any) +const FilesSplatRoute = FilesSplatRouteImport.update({ + id: '/files/$', + path: '/files/$', + getParentRoute: () => rootRouteImport, +} as any) +const ReleaseVChar123versionChar125Route = + ReleaseVChar123versionChar125RouteImport.update({ + id: '/release/v{$version}', + path: '/release/v{$version}', + getParentRoute: () => rootRouteImport, + } as any) +const SecAIndexRoute = SecAIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecARoute, +} as any) +const SecAIdRoute = SecAIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecARoute, +} as any) +const SecAAboutRoute = SecAAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecARoute, +} as any) +const SecASettingsRoute = SecASettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecARoute, +} as any) +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 { + '/': typeof IndexRoute + '/sec-a': typeof SecARouteWithChildren + '/sec-b': typeof SecBRouteWithChildren + '/sec-c': typeof SecCRouteWithChildren + '/sec-d': typeof SecDRouteWithChildren + '/sec-e': typeof SecERouteWithChildren + '/sec-f': typeof SecFRouteWithChildren + '/pricing': typeof marketingPricingRoute + '/promo': typeof marketingPromoRoute + '/alpha': typeof LayoutAlphaRoute + '/beta': typeof LayoutBetaRoute + '/files/$': typeof FilesSplatRoute + '/release/v{$version}': typeof ReleaseVChar123versionChar125Route + '/sec-a/$id': typeof SecAIdRoute + '/sec-a/about': typeof SecAAboutRoute + '/sec-a/settings': typeof SecASettingsRoute + '/sec-b/$id': typeof SecBIdRoute + '/sec-b/about': typeof SecBAboutRoute + '/sec-b/settings': typeof SecBSettingsRoute + '/sec-c/$id': typeof SecCIdRoute + '/sec-c/about': typeof SecCAboutRoute + '/sec-c/settings': typeof SecCSettingsRoute + '/sec-d/$id': typeof SecDIdRoute + '/sec-d/about': typeof SecDAboutRoute + '/sec-d/settings': typeof SecDSettingsRoute + '/sec-e/$id': typeof SecEIdRoute + '/sec-e/about': typeof SecEAboutRoute + '/sec-e/settings': typeof SecESettingsRoute + '/sec-f/$id': typeof SecFIdRoute + '/sec-f/about': typeof SecFAboutRoute + '/sec-f/settings': typeof SecFSettingsRoute + '/sec-a/': typeof SecAIndexRoute + '/sec-b/': typeof SecBIndexRoute + '/sec-c/': typeof SecCIndexRoute + '/sec-d/': typeof SecDIndexRoute + '/sec-e/': typeof SecEIndexRoute + '/sec-f/': typeof SecFIndexRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/pricing': typeof marketingPricingRoute + '/promo': typeof marketingPromoRoute + '/alpha': typeof LayoutAlphaRoute + '/beta': typeof LayoutBetaRoute + '/files/$': typeof FilesSplatRoute + '/release/v{$version}': typeof ReleaseVChar123versionChar125Route + '/sec-a/$id': typeof SecAIdRoute + '/sec-a/about': typeof SecAAboutRoute + '/sec-a/settings': typeof SecASettingsRoute + '/sec-b/$id': typeof SecBIdRoute + '/sec-b/about': typeof SecBAboutRoute + '/sec-b/settings': typeof SecBSettingsRoute + '/sec-c/$id': typeof SecCIdRoute + '/sec-c/about': typeof SecCAboutRoute + '/sec-c/settings': typeof SecCSettingsRoute + '/sec-d/$id': typeof SecDIdRoute + '/sec-d/about': typeof SecDAboutRoute + '/sec-d/settings': typeof SecDSettingsRoute + '/sec-e/$id': typeof SecEIdRoute + '/sec-e/about': typeof SecEAboutRoute + '/sec-e/settings': typeof SecESettingsRoute + '/sec-f/$id': typeof SecFIdRoute + '/sec-f/about': typeof SecFAboutRoute + '/sec-f/settings': typeof SecFSettingsRoute + '/sec-a': typeof SecAIndexRoute + '/sec-b': typeof SecBIndexRoute + '/sec-c': typeof SecCIndexRoute + '/sec-d': typeof SecDIndexRoute + '/sec-e': typeof SecEIndexRoute + '/sec-f': typeof SecFIndexRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/_layout': typeof LayoutRouteWithChildren + '/sec-a': typeof SecARouteWithChildren + '/sec-b': typeof SecBRouteWithChildren + '/sec-c': typeof SecCRouteWithChildren + '/sec-d': typeof SecDRouteWithChildren + '/sec-e': typeof SecERouteWithChildren + '/sec-f': typeof SecFRouteWithChildren + '/(marketing)/pricing': typeof marketingPricingRoute + '/(marketing)/promo': typeof marketingPromoRoute + '/_layout/alpha': typeof LayoutAlphaRoute + '/_layout/beta': typeof LayoutBetaRoute + '/files/$': typeof FilesSplatRoute + '/release/v{$version}': typeof ReleaseVChar123versionChar125Route + '/sec-a/$id': typeof SecAIdRoute + '/sec-a/about': typeof SecAAboutRoute + '/sec-a/settings': typeof SecASettingsRoute + '/sec-b/$id': typeof SecBIdRoute + '/sec-b/about': typeof SecBAboutRoute + '/sec-b/settings': typeof SecBSettingsRoute + '/sec-c/$id': typeof SecCIdRoute + '/sec-c/about': typeof SecCAboutRoute + '/sec-c/settings': typeof SecCSettingsRoute + '/sec-d/$id': typeof SecDIdRoute + '/sec-d/about': typeof SecDAboutRoute + '/sec-d/settings': typeof SecDSettingsRoute + '/sec-e/$id': typeof SecEIdRoute + '/sec-e/about': typeof SecEAboutRoute + '/sec-e/settings': typeof SecESettingsRoute + '/sec-f/$id': typeof SecFIdRoute + '/sec-f/about': typeof SecFAboutRoute + '/sec-f/settings': typeof SecFSettingsRoute + '/sec-a/': typeof SecAIndexRoute + '/sec-b/': typeof SecBIndexRoute + '/sec-c/': typeof SecCIndexRoute + '/sec-d/': typeof SecDIndexRoute + '/sec-e/': typeof SecEIndexRoute + '/sec-f/': typeof SecFIndexRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: + | '/' + | '/sec-a' + | '/sec-b' + | '/sec-c' + | '/sec-d' + | '/sec-e' + | '/sec-f' + | '/pricing' + | '/promo' + | '/alpha' + | '/beta' + | '/files/$' + | '/release/v{$version}' + | '/sec-a/$id' + | '/sec-a/about' + | '/sec-a/settings' + | '/sec-b/$id' + | '/sec-b/about' + | '/sec-b/settings' + | '/sec-c/$id' + | '/sec-c/about' + | '/sec-c/settings' + | '/sec-d/$id' + | '/sec-d/about' + | '/sec-d/settings' + | '/sec-e/$id' + | '/sec-e/about' + | '/sec-e/settings' + | '/sec-f/$id' + | '/sec-f/about' + | '/sec-f/settings' + | '/sec-a/' + | '/sec-b/' + | '/sec-c/' + | '/sec-d/' + | '/sec-e/' + | '/sec-f/' + fileRoutesByTo: FileRoutesByTo + to: + | '/' + | '/pricing' + | '/promo' + | '/alpha' + | '/beta' + | '/files/$' + | '/release/v{$version}' + | '/sec-a/$id' + | '/sec-a/about' + | '/sec-a/settings' + | '/sec-b/$id' + | '/sec-b/about' + | '/sec-b/settings' + | '/sec-c/$id' + | '/sec-c/about' + | '/sec-c/settings' + | '/sec-d/$id' + | '/sec-d/about' + | '/sec-d/settings' + | '/sec-e/$id' + | '/sec-e/about' + | '/sec-e/settings' + | '/sec-f/$id' + | '/sec-f/about' + | '/sec-f/settings' + | '/sec-a' + | '/sec-b' + | '/sec-c' + | '/sec-d' + | '/sec-e' + | '/sec-f' + id: + | '__root__' + | '/' + | '/_layout' + | '/sec-a' + | '/sec-b' + | '/sec-c' + | '/sec-d' + | '/sec-e' + | '/sec-f' + | '/(marketing)/pricing' + | '/(marketing)/promo' + | '/_layout/alpha' + | '/_layout/beta' + | '/files/$' + | '/release/v{$version}' + | '/sec-a/$id' + | '/sec-a/about' + | '/sec-a/settings' + | '/sec-b/$id' + | '/sec-b/about' + | '/sec-b/settings' + | '/sec-c/$id' + | '/sec-c/about' + | '/sec-c/settings' + | '/sec-d/$id' + | '/sec-d/about' + | '/sec-d/settings' + | '/sec-e/$id' + | '/sec-e/about' + | '/sec-e/settings' + | '/sec-f/$id' + | '/sec-f/about' + | '/sec-f/settings' + | '/sec-a/' + | '/sec-b/' + | '/sec-c/' + | '/sec-d/' + | '/sec-e/' + | '/sec-f/' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + LayoutRoute: typeof LayoutRouteWithChildren + SecARoute: typeof SecARouteWithChildren + SecBRoute: typeof SecBRouteWithChildren + SecCRoute: typeof SecCRouteWithChildren + SecDRoute: typeof SecDRouteWithChildren + SecERoute: typeof SecERouteWithChildren + SecFRoute: typeof SecFRouteWithChildren + marketingPricingRoute: typeof marketingPricingRoute + marketingPromoRoute: typeof marketingPromoRoute + FilesSplatRoute: typeof FilesSplatRoute + ReleaseVChar123versionChar125Route: typeof ReleaseVChar123versionChar125Route +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout': { + id: '/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-a': { + id: '/sec-a' + path: '/sec-a' + fullPath: '/sec-a' + preLoaderRoute: typeof SecARouteImport + parentRoute: typeof rootRouteImport + } + '/sec-b': { + id: '/sec-b' + path: '/sec-b' + fullPath: '/sec-b' + preLoaderRoute: typeof SecBRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-c': { + id: '/sec-c' + path: '/sec-c' + fullPath: '/sec-c' + preLoaderRoute: typeof SecCRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-d': { + id: '/sec-d' + path: '/sec-d' + fullPath: '/sec-d' + preLoaderRoute: typeof SecDRouteImport + parentRoute: typeof rootRouteImport + } + '/sec-e': { + id: '/sec-e' + path: '/sec-e' + fullPath: '/sec-e' + preLoaderRoute: typeof SecERouteImport + parentRoute: typeof rootRouteImport + } + '/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/' + path: '/' + fullPath: '/sec-a/' + preLoaderRoute: typeof SecAIndexRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/$id': { + id: '/sec-a/$id' + path: '/$id' + fullPath: '/sec-a/$id' + preLoaderRoute: typeof SecAIdRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/about': { + id: '/sec-a/about' + path: '/about' + fullPath: '/sec-a/about' + preLoaderRoute: typeof SecAAboutRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/settings': { + id: '/sec-a/settings' + path: '/settings' + fullPath: '/sec-a/settings' + preLoaderRoute: typeof SecASettingsRouteImport + parentRoute: typeof SecARoute + } + '/sec-b/': { + id: '/sec-b/' + path: '/' + fullPath: '/sec-b/' + preLoaderRoute: typeof SecBIndexRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/$id': { + id: '/sec-b/$id' + path: '/$id' + fullPath: '/sec-b/$id' + preLoaderRoute: typeof SecBIdRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/about': { + id: '/sec-b/about' + path: '/about' + fullPath: '/sec-b/about' + preLoaderRoute: typeof SecBAboutRouteImport + parentRoute: typeof SecBRoute + } + '/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 + } + } +} + +interface LayoutRouteChildren { + LayoutAlphaRoute: typeof LayoutAlphaRoute + LayoutBetaRoute: typeof LayoutBetaRoute +} + +const LayoutRouteChildren: LayoutRouteChildren = { + LayoutAlphaRoute: LayoutAlphaRoute, + LayoutBetaRoute: LayoutBetaRoute, +} + +const LayoutRouteWithChildren = + LayoutRoute._addFileChildren(LayoutRouteChildren) + +interface SecARouteChildren { + SecAIdRoute: typeof SecAIdRoute + SecAAboutRoute: typeof SecAAboutRoute + SecASettingsRoute: typeof SecASettingsRoute + SecAIndexRoute: typeof SecAIndexRoute +} + +const SecARouteChildren: SecARouteChildren = { + SecAIdRoute: SecAIdRoute, + SecAAboutRoute: SecAAboutRoute, + SecASettingsRoute: SecASettingsRoute, + SecAIndexRoute: SecAIndexRoute, +} + +const SecARouteWithChildren = SecARoute._addFileChildren(SecARouteChildren) + +interface SecBRouteChildren { + SecBIdRoute: typeof SecBIdRoute + SecBAboutRoute: typeof SecBAboutRoute + SecBSettingsRoute: typeof SecBSettingsRoute + SecBIndexRoute: typeof SecBIndexRoute +} + +const SecBRouteChildren: SecBRouteChildren = { + SecBIdRoute: SecBIdRoute, + SecBAboutRoute: SecBAboutRoute, + SecBSettingsRoute: SecBSettingsRoute, + SecBIndexRoute: SecBIndexRoute, +} + +const SecBRouteWithChildren = SecBRoute._addFileChildren(SecBRouteChildren) + +interface SecCRouteChildren { + SecCIdRoute: typeof SecCIdRoute + SecCAboutRoute: typeof SecCAboutRoute + SecCSettingsRoute: typeof SecCSettingsRoute + SecCIndexRoute: typeof SecCIndexRoute +} + +const SecCRouteChildren: SecCRouteChildren = { + SecCIdRoute: SecCIdRoute, + SecCAboutRoute: SecCAboutRoute, + SecCSettingsRoute: SecCSettingsRoute, + SecCIndexRoute: SecCIndexRoute, +} + +const SecCRouteWithChildren = SecCRoute._addFileChildren(SecCRouteChildren) + +interface SecDRouteChildren { + SecDIdRoute: typeof SecDIdRoute + SecDAboutRoute: typeof SecDAboutRoute + SecDSettingsRoute: typeof SecDSettingsRoute + SecDIndexRoute: typeof SecDIndexRoute +} + +const SecDRouteChildren: SecDRouteChildren = { + SecDIdRoute: SecDIdRoute, + SecDAboutRoute: SecDAboutRoute, + SecDSettingsRoute: SecDSettingsRoute, + SecDIndexRoute: SecDIndexRoute, +} + +const SecDRouteWithChildren = SecDRoute._addFileChildren(SecDRouteChildren) + +interface SecERouteChildren { + SecEIdRoute: typeof SecEIdRoute + SecEAboutRoute: typeof SecEAboutRoute + SecESettingsRoute: typeof SecESettingsRoute + SecEIndexRoute: typeof SecEIndexRoute +} + +const SecERouteChildren: SecERouteChildren = { + SecEIdRoute: SecEIdRoute, + SecEAboutRoute: SecEAboutRoute, + SecESettingsRoute: SecESettingsRoute, + SecEIndexRoute: SecEIndexRoute, +} + +const SecERouteWithChildren = SecERoute._addFileChildren(SecERouteChildren) + +interface SecFRouteChildren { + SecFIdRoute: typeof SecFIdRoute + SecFAboutRoute: typeof SecFAboutRoute + SecFSettingsRoute: typeof SecFSettingsRoute + SecFIndexRoute: typeof SecFIndexRoute +} + +const SecFRouteChildren: SecFRouteChildren = { + SecFIdRoute: SecFIdRoute, + SecFAboutRoute: SecFAboutRoute, + SecFSettingsRoute: SecFSettingsRoute, + SecFIndexRoute: SecFIndexRoute, +} + +const SecFRouteWithChildren = SecFRoute._addFileChildren(SecFRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + LayoutRoute: LayoutRouteWithChildren, + SecARoute: SecARouteWithChildren, + SecBRoute: SecBRouteWithChildren, + SecCRoute: SecCRouteWithChildren, + SecDRoute: SecDRouteWithChildren, + SecERoute: SecERouteWithChildren, + SecFRoute: SecFRouteWithChildren, + marketingPricingRoute: marketingPricingRoute, + marketingPromoRoute: marketingPromoRoute, + FilesSplatRoute: FilesSplatRoute, + ReleaseVChar123versionChar125Route: ReleaseVChar123versionChar125Route, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/(marketing)/pricing.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/(marketing)/pricing.tsx new file mode 100644 index 0000000000..f606c10b4b --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/(marketing)/pricing.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
pricing
+ }, +}) + +export const Route = createFileRoute('/(marketing)/pricing')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/(marketing)/promo.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/(marketing)/promo.tsx new file mode 100644 index 0000000000..61c3eb3ec9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/(marketing)/promo.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
promo
+ }, +}) + +export const Route = createFileRoute('/(marketing)/promo')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..d2e1483106 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/__root.tsx @@ -0,0 +1,61 @@ +import * as Vue from 'vue' +import { Link, Outlet, createRootRoute } from '@tanstack/vue-router' + +const RootComponent = Vue.defineComponent({ + setup() { + return () => ( + <> + + + + ) + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.alpha.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.alpha.tsx new file mode 100644 index 0000000000..ff6ad5350e --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.alpha.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
alpha
+ }, +}) + +export const Route = createFileRoute('/_layout/alpha')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.beta.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.beta.tsx new file mode 100644 index 0000000000..2f7cab6c0a --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.beta.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
beta
+ }, +}) + +export const Route = createFileRoute('/_layout/beta')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.tsx new file mode 100644 index 0000000000..e8221f0f65 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/_layout.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' + +const Layout = Vue.defineComponent({ + setup() { + return () => + }, +}) + +export const Route = createFileRoute('/_layout')({ + component: Layout, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/files.$.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/files.$.tsx new file mode 100644 index 0000000000..221fae01be --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/files.$.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
{`files:${params.value._splat}`}
+ ) + }, +}) + +export const Route = createFileRoute('/files/$')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/index.tsx new file mode 100644 index 0000000000..b3e94f37c4 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/index.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
home
+ }, +}) + +export const Route = createFileRoute('/')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/release.v{$version}.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/release.v{$version}.tsx new file mode 100644 index 0000000000..86b1a2c8f0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/release.v{$version}.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
{`release:${params.value.version}`}
+ ) + }, +}) + +export const Route = createFileRoute('/release/v{$version}')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.$id.tsx new file mode 100644 index 0000000000..864074940d --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.$id.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
{`sec-a:${params.value.id}`}
+ ) + }, +}) + +export const Route = createFileRoute('/sec-a/$id')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.about.tsx new file mode 100644 index 0000000000..715ab9548c --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.about.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-a:about
+ }, +}) + +export const Route = createFileRoute('/sec-a/about')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.index.tsx new file mode 100644 index 0000000000..baef08547c --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.index.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-a:index
+ }, +}) + +export const Route = createFileRoute('/sec-a/')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.settings.tsx new file mode 100644 index 0000000000..9e6a56b913 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.settings.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-a:settings
+ }, +}) + +export const Route = createFileRoute('/sec-a/settings')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.tsx new file mode 100644 index 0000000000..a9fb557aea --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-a.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' + +const Layout = Vue.defineComponent({ + setup() { + return () => + }, +}) + +export const Route = createFileRoute('/sec-a')({ + component: Layout, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.$id.tsx new file mode 100644 index 0000000000..9a03a8fe01 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.$id.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
{`sec-b:${params.value.id}`}
+ ) + }, +}) + +export const Route = createFileRoute('/sec-b/$id')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.about.tsx new file mode 100644 index 0000000000..2ef1100995 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.about.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-b:about
+ }, +}) + +export const Route = createFileRoute('/sec-b/about')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.index.tsx new file mode 100644 index 0000000000..652e5f895c --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.index.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-b:index
+ }, +}) + +export const Route = createFileRoute('/sec-b/')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.settings.tsx new file mode 100644 index 0000000000..e8fa36377e --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.settings.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-b:settings
+ }, +}) + +export const Route = createFileRoute('/sec-b/settings')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.tsx new file mode 100644 index 0000000000..ba31612633 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-b.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' + +const Layout = Vue.defineComponent({ + setup() { + return () => + }, +}) + +export const Route = createFileRoute('/sec-b')({ + component: Layout, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.$id.tsx new file mode 100644 index 0000000000..7f0407d84e --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.$id.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
{`sec-c:${params.value.id}`}
+ ) + }, +}) + +export const Route = createFileRoute('/sec-c/$id')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.about.tsx new file mode 100644 index 0000000000..d26776d439 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.about.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-c:about
+ }, +}) + +export const Route = createFileRoute('/sec-c/about')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.index.tsx new file mode 100644 index 0000000000..1835eff9b7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.index.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-c:index
+ }, +}) + +export const Route = createFileRoute('/sec-c/')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.settings.tsx new file mode 100644 index 0000000000..1bf85fd6d9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.settings.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-c:settings
+ }, +}) + +export const Route = createFileRoute('/sec-c/settings')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.tsx new file mode 100644 index 0000000000..009f814b93 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-c.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' + +const Layout = Vue.defineComponent({ + setup() { + return () => + }, +}) + +export const Route = createFileRoute('/sec-c')({ + component: Layout, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.$id.tsx new file mode 100644 index 0000000000..ff5aab05e3 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.$id.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
{`sec-d:${params.value.id}`}
+ ) + }, +}) + +export const Route = createFileRoute('/sec-d/$id')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.about.tsx new file mode 100644 index 0000000000..25a8078626 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.about.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-d:about
+ }, +}) + +export const Route = createFileRoute('/sec-d/about')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.index.tsx new file mode 100644 index 0000000000..cd9b89664a --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.index.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-d:index
+ }, +}) + +export const Route = createFileRoute('/sec-d/')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.settings.tsx new file mode 100644 index 0000000000..8e4309de32 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.settings.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-d:settings
+ }, +}) + +export const Route = createFileRoute('/sec-d/settings')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.tsx new file mode 100644 index 0000000000..6b12b514da --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-d.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' + +const Layout = Vue.defineComponent({ + setup() { + return () => + }, +}) + +export const Route = createFileRoute('/sec-d')({ + component: Layout, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.$id.tsx new file mode 100644 index 0000000000..4525051967 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.$id.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
{`sec-e:${params.value.id}`}
+ ) + }, +}) + +export const Route = createFileRoute('/sec-e/$id')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.about.tsx new file mode 100644 index 0000000000..71a32bd36b --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.about.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-e:about
+ }, +}) + +export const Route = createFileRoute('/sec-e/about')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.index.tsx new file mode 100644 index 0000000000..9b467ca53e --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.index.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-e:index
+ }, +}) + +export const Route = createFileRoute('/sec-e/')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.settings.tsx new file mode 100644 index 0000000000..a01066488c --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.settings.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-e:settings
+ }, +}) + +export const Route = createFileRoute('/sec-e/settings')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.tsx new file mode 100644 index 0000000000..38f4da91fb --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-e.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' + +const Layout = Vue.defineComponent({ + setup() { + return () => + }, +}) + +export const Route = createFileRoute('/sec-e')({ + component: Layout, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.$id.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.$id.tsx new file mode 100644 index 0000000000..c740f9d223 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.$id.tsx @@ -0,0 +1,16 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + const params = Route.useParams() + + return () => ( +
{`sec-f:${params.value.id}`}
+ ) + }, +}) + +export const Route = createFileRoute('/sec-f/$id')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.about.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.about.tsx new file mode 100644 index 0000000000..229dab22a2 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.about.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-f:about
+ }, +}) + +export const Route = createFileRoute('/sec-f/about')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.index.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.index.tsx new file mode 100644 index 0000000000..14e3f46a13 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.index.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-f:index
+ }, +}) + +export const Route = createFileRoute('/sec-f/')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.settings.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.settings.tsx new file mode 100644 index 0000000000..da2c7483b9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.settings.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const Page = Vue.defineComponent({ + setup() { + return () =>
sec-f:settings
+ }, +}) + +export const Route = createFileRoute('/sec-f/settings')({ + component: Page, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.tsx b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.tsx new file mode 100644 index 0000000000..3b389c8144 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routes/sec-f.tsx @@ -0,0 +1,12 @@ +import * as Vue from 'vue' +import { Outlet, createFileRoute } from '@tanstack/vue-router' + +const Layout = Vue.defineComponent({ + setup() { + return () => + }, +}) + +export const Route = createFileRoute('/sec-f')({ + component: Layout, +}) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/tsconfig.json b/benchmarks/client-nav/scenarios/route-tree-scale/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/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/route-tree-scale/vue/vite.config.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/vite.config.ts new file mode 100644 index 0000000000..189ba1de99 --- /dev/null +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/vite.config.ts @@ -0,0 +1,47 @@ +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', + // Real file-based apps code-split by default; this scenario keeps it on + // so navigations also exercise lazy route-chunk resolution. + autoCodeSplitting: true, + 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 route-tree-scale (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/search-params/react/project.json b/benchmarks/client-nav/scenarios/search-params/react/project.json new file mode 100644 index 0000000000..f2d743f5f9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/react/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-search-params-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/search-params/react/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/search-params/react/setup.ts b/benchmarks/client-nav/scenarios/search-params/react/setup.ts new file mode 100644 index 0000000000..130583b190 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/react/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } 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, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts b/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts new file mode 100644 index 0000000000..0b38f7bddb --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/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-search-params', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-search-params 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/search-params/react/speed.flame.ts b/benchmarks/client-nav/scenarios/search-params/react/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/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/search-params/react/src/main.tsx b/benchmarks/client-nav/scenarios/search-params/react/src/main.tsx new file mode 100644 index 0000000000..b10d53554b --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/react/src/main.tsx @@ -0,0 +1,38 @@ +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, + defaultStructuralSharing: true, + }) +} + +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/search-params/react/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/search-params/react/src/routeTree.gen.ts new file mode 100644 index 0000000000..cff9dca167 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/react/src/routeTree.gen.ts @@ -0,0 +1,95 @@ +/* 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 CatalogRouteImport } from './routes/catalog' +import { Route as ProductsRouteImport } from './routes/products' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const CatalogRoute = CatalogRouteImport.update({ + id: '/catalog', + path: '/catalog', + getParentRoute: () => rootRouteImport, +} as any) +const ProductsRoute = ProductsRouteImport.update({ + id: '/products', + path: '/products', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/catalog': typeof CatalogRoute + '/products': typeof ProductsRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/catalog': typeof CatalogRoute + '/products': typeof ProductsRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/catalog': typeof CatalogRoute + '/products': typeof ProductsRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/catalog' | '/products' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/catalog' | '/products' + id: '__root__' | '/' | '/catalog' | '/products' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + CatalogRoute: typeof CatalogRoute + ProductsRoute: typeof ProductsRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/catalog': { + id: '/catalog' + path: '/catalog' + fullPath: '/catalog' + preLoaderRoute: typeof CatalogRouteImport + parentRoute: typeof rootRouteImport + } + '/products': { + id: '/products' + path: '/products' + fullPath: '/products' + preLoaderRoute: typeof ProductsRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + CatalogRoute: CatalogRoute, + ProductsRoute: ProductsRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/search-params/react/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/search-params/react/src/routes/__root.tsx new file mode 100644 index 0000000000..86399d0175 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/react/src/routes/__root.tsx @@ -0,0 +1,116 @@ +import { + Link, + Outlet, + createRootRoute, + useSearch, +} from '@tanstack/react-router' +import { + changedCategories, + computeChecksum, + initialProductsSearch, +} from '../../../shared' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +const rootSubscribers = Array.from({ length: 4 }, (_, index) => index) + +function RootSearchSubscriber() { + const value = useSearch({ + strict: false, + select: (search) => computeChecksum(Number(search.page ?? 0)), + }) + + void computeChecksum(value) + return null +} + +function RootComponent() { + return ( + <> + {rootSubscribers.map((index) => ( + + ))} + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/search-params/react/src/routes/catalog.tsx b/benchmarks/client-nav/scenarios/search-params/react/src/routes/catalog.tsx new file mode 100644 index 0000000000..73f59c13b0 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/react/src/routes/catalog.tsx @@ -0,0 +1,42 @@ +import { createFileRoute, retainSearchParams } from '@tanstack/react-router' +import type { SearchSchemaInput } from '@tanstack/react-router' +import { + catalogMarkerText, + computeChecksum, + normalizeCatalogSearch, +} from '../../../shared' + +export const Route = createFileRoute('/catalog')({ + validateSearch: (search: Record & SearchSchemaInput) => + normalizeCatalogSearch(search), + search: { + middlewares: [retainSearchParams(['perPage', 'sort'])], + }, + component: CatalogPage, +}) + +const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) + +function ViewSubscriber() { + const value = Route.useSearch({ + select: (search) => + computeChecksum(search.view.length * 5 + search.page * 11), + }) + + void computeChecksum(value) + return null +} + +function CatalogPage() { + const search = Route.useSearch() + + return ( +
+ {subscriberIndexes.map((index) => ( + + ))} +

Catalog

+
{catalogMarkerText(search)}
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/search-params/react/src/routes/index.tsx b/benchmarks/client-nav/scenarios/search-params/react/src/routes/index.tsx new file mode 100644 index 0000000000..5879ad518d --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/react/src/routes/index.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return ( +
+

Search Params Bench

+
home
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/search-params/react/src/routes/products.tsx b/benchmarks/client-nav/scenarios/search-params/react/src/routes/products.tsx new file mode 100644 index 0000000000..d22e99c4bf --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/react/src/routes/products.tsx @@ -0,0 +1,91 @@ +import { + createFileRoute, + retainSearchParams, + stripSearchParams, +} from '@tanstack/react-router' +import type { SearchSchemaInput } from '@tanstack/react-router' +import { + computeChecksum, + normalizeProductsSearch, + productsLoaderChecksum, + productsMarkerText, +} from '../../../shared' + +export const Route = createFileRoute('/products')({ + validateSearch: (search: Record & SearchSchemaInput) => + normalizeProductsSearch(search), + search: { + middlewares: [ + retainSearchParams(['perPage', 'sort']), + stripSearchParams({ page: 1 }), + ], + }, + loaderDeps: ({ search }) => ({ + page: search.page, + sort: search.sort, + filters: search.filters, + }), + loader: ({ deps }) => ({ + checksum: productsLoaderChecksum(deps), + }), + staleTime: 1e9, + gcTime: 1e9, + component: ProductsPage, +}) + +const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) + +function PageSubscriber() { + const value = Route.useSearch({ + select: (search) => computeChecksum(search.page * 31 + search.perPage), + }) + + void computeChecksum(value) + return null +} + +function FiltersSubscriber() { + const value = Route.useSearch({ + select: (search) => + computeChecksum( + search.filters.categories.length * 7 + + (search.filters.price.max - search.filters.price.min) + + search.filters.tags.length * 3, + ), + }) + + void computeChecksum(value) + return null +} + +function QuerySubscriber() { + const value = Route.useSearch({ + select: (search) => + computeChecksum(search.q.length * 13 + search.sort.length), + }) + + void computeChecksum(value) + return null +} + +function ProductsPage() { + const search = Route.useSearch() + const loaderData = Route.useLoaderData() + + return ( +
+ {subscriberIndexes.map((index) => ( + + ))} + {subscriberIndexes.map((index) => ( + + ))} + {subscriberIndexes.map((index) => ( + + ))} +

Products

+
{productsMarkerText(search)}
+

{`checksum ${loaderData.checksum}`}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/search-params/react/tsconfig.json b/benchmarks/client-nav/scenarios/search-params/react/tsconfig.json new file mode 100644 index 0000000000..1d59cbb450 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/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/search-params/react/vite.config.ts b/benchmarks/client-nav/scenarios/search-params/react/vite.config.ts new file mode 100644 index 0000000000..0318a10815 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/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 search-params (react)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) diff --git a/benchmarks/client-nav/scenarios/search-params/shared.ts b/benchmarks/client-nav/scenarios/search-params/shared.ts new file mode 100644 index 0000000000..343e319ded --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/shared.ts @@ -0,0 +1,200 @@ +/** + * Shared definition of the `search-params` scenario: search schema + * normalizers, the click sequence, and per-step sanity assertions. The three + * framework apps consume these builders so the workload is identical modulo + * the rendering layer. + * + * Isolates: validateSearch execution, search middlewares + * (retainSearchParams/stripSearchParams), parse/stringify of medium-complex + * search objects, functional search updaters, structural sharing, and + * useSearch selector subscriptions. + */ + +import type { ScenarioStep } from '../harness' + +export function computeChecksum(seed: number) { + let value = Math.trunc(seed) | 0 + + for (let index = 0; index < 40; index++) { + value = (value * 1664525 + 1013904223 + index) >>> 0 + } + + return value +} + +export interface ProductsSearch { + page: number + perPage: number + sort: 'asc' | 'desc' + q: string + filters: { + categories: Array + price: { min: number; max: number } + tags: Array + } +} + +export interface CatalogSearch { + view: 'grid' | 'list' + page: number + perPage: number + sort: 'asc' | 'desc' +} + +function normalizeNumber(value: unknown, fallback: number) { + const num = Number(value) + return Number.isFinite(num) && num >= 0 ? Math.trunc(num) : fallback +} + +function normalizeString(value: unknown, fallback: string) { + return typeof value === 'string' ? value : fallback +} + +function normalizeSort(value: unknown): 'asc' | 'desc' { + return value === 'desc' ? 'desc' : 'asc' +} + +function normalizeStringArray(value: unknown): Array { + if (!Array.isArray(value)) { + return [] + } + return value.filter((entry): entry is string => typeof entry === 'string') +} + +export function normalizeProductsSearch( + search: Record, +): ProductsSearch { + const filters = + typeof search.filters === 'object' && search.filters !== null + ? (search.filters as Record) + : {} + const price = + typeof filters.price === 'object' && filters.price !== null + ? (filters.price as Record) + : {} + + return { + page: Math.max(1, normalizeNumber(search.page, 1)), + perPage: Math.max(1, normalizeNumber(search.perPage, 20)), + sort: normalizeSort(search.sort), + q: normalizeString(search.q, ''), + filters: { + categories: normalizeStringArray(filters.categories), + price: { + min: normalizeNumber(price.min, 0), + max: normalizeNumber(price.max, 1000), + }, + tags: normalizeStringArray(filters.tags), + }, + } +} + +export function normalizeCatalogSearch( + search: Record, +): CatalogSearch { + return { + view: search.view === 'list' ? 'list' : 'grid', + page: Math.max(1, normalizeNumber(search.page, 1)), + perPage: Math.max(1, normalizeNumber(search.perPage, 20)), + sort: normalizeSort(search.sort), + } +} + +export const initialProductsSearch = { + page: 2, + perPage: 50, + sort: 'desc', + q: 'gadget', + filters: { + categories: ['audio', 'video'], + price: { min: 10, max: 200 }, + tags: ['new', 'sale'], + }, +} satisfies ProductsSearch + +export const changedCategories = ['x-ray', 'yield', 'zeta'] + +export function productsMarkerText(search: ProductsSearch) { + return `${search.page}|${search.sort}|${search.filters.categories.join(',')}` +} + +export function catalogMarkerText(search: CatalogSearch) { + return `${search.view}|${search.page}|${search.perPage}|${search.sort}` +} + +export function productsLoaderChecksum(deps: { + page: number + sort: string + filters: ProductsSearch['filters'] +}) { + return computeChecksum( + deps.page * 31 + + deps.sort.length * 7 + + deps.filters.categories.join('').length * 13 + + deps.filters.tags.length * 3 + + (deps.filters.price.max - deps.filters.price.min), + ) +} + +export const steps: ReadonlyArray = [ + 'go-products', + 'products-next-page', + 'products-categories', + 'products-sort', + 'products-reset', + 'go-catalog', + 'catalog-next-page', + 'products-partial', + 'go-home', +] + +interface ExpectedState { + testId: string + text?: string +} + +const expectedStates: ReadonlyArray = [ + // Full search literal from home. + { testId: 'products-state', text: '2|desc|audio,video' }, + // Functional updater bumping the page. + { testId: 'products-state', text: '3|desc|audio,video' }, + // Functional updater replacing filters.categories. + { testId: 'products-state', text: '3|desc|x-ray,yield,zeta' }, + // Functional updater flipping sort desc -> asc. + { testId: 'products-state', text: '3|asc|x-ray,yield,zeta' }, + // Functional updater resetting page to 1 (stripSearchParams removes it). + { testId: 'products-state', text: '1|asc|x-ray,yield,zeta' }, + // search: true carries the current products search into catalog. + { testId: 'catalog-state', text: 'grid|1|50|asc' }, + // Functional updater bumping the catalog page. + { testId: 'catalog-state', text: 'grid|2|50|asc' }, + // Partial search literal; retainSearchParams fills perPage/sort from catalog. + { testId: 'products-state', text: '1|asc|' }, + { testId: 'home-state' }, +] + +export function assertStepResult(stepIndex: number, container: HTMLElement) { + const expected = expectedStates[stepIndex]! + const element = container.querySelector(`[data-testid="${expected.testId}"]`) + + if (!element) { + throw new Error( + `Expected marker "${expected.testId}" to exist after step ${stepIndex}`, + ) + } + + if (expected.text !== undefined && element.textContent !== expected.text) { + throw new Error( + `Expected marker "${expected.testId}" to read "${expected.text}" after step ${stepIndex}, received "${element.textContent}"`, + ) + } +} + +// Two laps through the 9-step sequence per benchmark iteration. +export const ticksPerIteration = 18 + +export const benchOptions = { + warmupIterations: 100, + time: 10_000, + throws: true, +} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/project.json b/benchmarks/client-nav/scenarios/search-params/solid/project.json new file mode 100644 index 0000000000..af48217e03 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/solid/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-search-params-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/search-params/solid/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/setup.ts b/benchmarks/client-nav/scenarios/search-params/solid/setup.ts new file mode 100644 index 0000000000..6a46971603 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/solid/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } 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, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts new file mode 100644 index 0000000000..caa626c596 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/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-search-params', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-search-params 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/search-params/solid/speed.flame.ts b/benchmarks/client-nav/scenarios/search-params/solid/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/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/search-params/solid/src/main.tsx b/benchmarks/client-nav/scenarios/search-params/solid/src/main.tsx new file mode 100644 index 0000000000..25071f7979 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/solid/src/main.tsx @@ -0,0 +1,35 @@ +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, + defaultStructuralSharing: true, + }) +} + +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/search-params/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/search-params/solid/src/routeTree.gen.ts new file mode 100644 index 0000000000..b15beed09b --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/solid/src/routeTree.gen.ts @@ -0,0 +1,95 @@ +/* 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 CatalogRouteImport } from './routes/catalog' +import { Route as ProductsRouteImport } from './routes/products' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const CatalogRoute = CatalogRouteImport.update({ + id: '/catalog', + path: '/catalog', + getParentRoute: () => rootRouteImport, +} as any) +const ProductsRoute = ProductsRouteImport.update({ + id: '/products', + path: '/products', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/catalog': typeof CatalogRoute + '/products': typeof ProductsRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/catalog': typeof CatalogRoute + '/products': typeof ProductsRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/catalog': typeof CatalogRoute + '/products': typeof ProductsRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/catalog' | '/products' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/catalog' | '/products' + id: '__root__' | '/' | '/catalog' | '/products' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + CatalogRoute: typeof CatalogRoute + ProductsRoute: typeof ProductsRoute +} + +declare module '@tanstack/solid-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/catalog': { + id: '/catalog' + path: '/catalog' + fullPath: '/catalog' + preLoaderRoute: typeof CatalogRouteImport + parentRoute: typeof rootRouteImport + } + '/products': { + id: '/products' + path: '/products' + fullPath: '/products' + preLoaderRoute: typeof ProductsRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + CatalogRoute: CatalogRoute, + ProductsRoute: ProductsRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/search-params/solid/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/search-params/solid/src/routes/__root.tsx new file mode 100644 index 0000000000..30c042f9c5 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/solid/src/routes/__root.tsx @@ -0,0 +1,120 @@ +import { createRenderEffect } from 'solid-js' +import { + Link, + Outlet, + createRootRoute, + useSearch, +} from '@tanstack/solid-router' +import { + changedCategories, + computeChecksum, + initialProductsSearch, +} from '../../../shared' + +export const Route = createRootRoute({ + component: RootComponent, +}) + +const rootSubscribers = Array.from({ length: 4 }, (_, index) => index) + +function PerfValue(props: { value: () => number }) { + createRenderEffect(() => { + void props.value() + }) + + return null +} + +function RootSearchSubscriber() { + const value = useSearch({ + strict: false, + select: (search) => computeChecksum(Number(search.page ?? 0)), + }) + + return computeChecksum(value())} /> +} + +function RootComponent() { + return ( + <> + {rootSubscribers.map(() => ( + + ))} + + + + ) +} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/src/routes/catalog.tsx b/benchmarks/client-nav/scenarios/search-params/solid/src/routes/catalog.tsx new file mode 100644 index 0000000000..60cf8e7896 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/solid/src/routes/catalog.tsx @@ -0,0 +1,50 @@ +import { createRenderEffect } from 'solid-js' +import { createFileRoute, retainSearchParams } from '@tanstack/solid-router' +import type { SearchSchemaInput } from '@tanstack/solid-router' +import { + catalogMarkerText, + computeChecksum, + normalizeCatalogSearch, +} from '../../../shared' + +export const Route = createFileRoute('/catalog')({ + validateSearch: (search: Record & SearchSchemaInput) => + normalizeCatalogSearch(search), + search: { + middlewares: [retainSearchParams(['perPage', 'sort'])], + }, + component: CatalogPage, +}) + +const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) + +function PerfValue(props: { value: () => number }) { + createRenderEffect(() => { + void props.value() + }) + + return null +} + +function ViewSubscriber() { + const value = Route.useSearch({ + select: (search) => + computeChecksum(search.view.length * 5 + search.page * 11), + }) + + return computeChecksum(value())} /> +} + +function CatalogPage() { + const search = Route.useSearch() + + return ( +
+ {subscriberIndexes.map(() => ( + + ))} +

Catalog

+
{catalogMarkerText(search())}
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/src/routes/index.tsx b/benchmarks/client-nav/scenarios/search-params/solid/src/routes/index.tsx new file mode 100644 index 0000000000..0bbb913d83 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/solid/src/routes/index.tsx @@ -0,0 +1,14 @@ +import { createFileRoute } from '@tanstack/solid-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return ( +
+

Search Params Bench

+
home
+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/src/routes/products.tsx b/benchmarks/client-nav/scenarios/search-params/solid/src/routes/products.tsx new file mode 100644 index 0000000000..8b2a252155 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/solid/src/routes/products.tsx @@ -0,0 +1,97 @@ +import { createRenderEffect } from 'solid-js' +import { + createFileRoute, + retainSearchParams, + stripSearchParams, +} from '@tanstack/solid-router' +import type { SearchSchemaInput } from '@tanstack/solid-router' +import { + computeChecksum, + normalizeProductsSearch, + productsLoaderChecksum, + productsMarkerText, +} from '../../../shared' + +export const Route = createFileRoute('/products')({ + validateSearch: (search: Record & SearchSchemaInput) => + normalizeProductsSearch(search), + search: { + middlewares: [ + retainSearchParams(['perPage', 'sort']), + stripSearchParams({ page: 1 }), + ], + }, + loaderDeps: ({ search }) => ({ + page: search.page, + sort: search.sort, + filters: search.filters, + }), + loader: ({ deps }) => ({ + checksum: productsLoaderChecksum(deps), + }), + staleTime: 1e9, + gcTime: 1e9, + component: ProductsPage, +}) + +const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) + +function PerfValue(props: { value: () => number }) { + createRenderEffect(() => { + void props.value() + }) + + return null +} + +function PageSubscriber() { + const value = Route.useSearch({ + select: (search) => computeChecksum(search.page * 31 + search.perPage), + }) + + return computeChecksum(value())} /> +} + +function FiltersSubscriber() { + const value = Route.useSearch({ + select: (search) => + computeChecksum( + search.filters.categories.length * 7 + + (search.filters.price.max - search.filters.price.min) + + search.filters.tags.length * 3, + ), + }) + + return computeChecksum(value())} /> +} + +function QuerySubscriber() { + const value = Route.useSearch({ + select: (search) => + computeChecksum(search.q.length * 13 + search.sort.length), + }) + + return computeChecksum(value())} /> +} + +function ProductsPage() { + const search = Route.useSearch() + const loaderData = Route.useLoaderData() + + return ( +
+ {subscriberIndexes.map(() => ( + + ))} + {subscriberIndexes.map(() => ( + + ))} + {subscriberIndexes.map(() => ( + + ))} +

Products

+
{productsMarkerText(search())}
+

{`checksum ${loaderData().checksum}`}

+
+ ) +} diff --git a/benchmarks/client-nav/scenarios/search-params/solid/tsconfig.json b/benchmarks/client-nav/scenarios/search-params/solid/tsconfig.json new file mode 100644 index 0000000000..98d76ad6b8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/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/search-params/solid/vite.config.ts b/benchmarks/client-nav/scenarios/search-params/solid/vite.config.ts new file mode 100644 index 0000000000..511fd49466 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/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 search-params (solid)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + server: { + deps: { + inline: [/@solidjs/, /@tanstack\/solid-store/], + }, + }, + }, +}) diff --git a/benchmarks/client-nav/scenarios/search-params/vue/project.json b/benchmarks/client-nav/scenarios/search-params/vue/project.json new file mode 100644 index 0000000000..47b9712a2c --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/vue/project.json @@ -0,0 +1,40 @@ +{ + "name": "@benchmarks/client-nav-search-params-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/search-params/vue/speed.flame.ts", + "cwd": "benchmarks/client-nav" + } + } + } +} diff --git a/benchmarks/client-nav/scenarios/search-params/vue/setup.ts b/benchmarks/client-nav/scenarios/search-params/vue/setup.ts new file mode 100644 index 0000000000..97b74b3892 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/vue/setup.ts @@ -0,0 +1,17 @@ +import { createScenarioSetup } from '../../harness' +import { assertStepResult, steps } 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, + assertAfterStep: assertStepResult, + }) +} diff --git a/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts new file mode 100644 index 0000000000..728d2779e8 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/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-search-params', async ({ bench }) => { + const scenario = setup() + + await bench( + 'client-search-params 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/search-params/vue/speed.flame.ts b/benchmarks/client-nav/scenarios/search-params/vue/speed.flame.ts new file mode 100644 index 0000000000..f4a0b4e6ff --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/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/search-params/vue/src/main.tsx b/benchmarks/client-nav/scenarios/search-params/vue/src/main.tsx new file mode 100644 index 0000000000..65bade775c --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/vue/src/main.tsx @@ -0,0 +1,42 @@ +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, + defaultStructuralSharing: true, + }) +} + +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/search-params/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/search-params/vue/src/routeTree.gen.ts new file mode 100644 index 0000000000..f73b84ebe7 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/vue/src/routeTree.gen.ts @@ -0,0 +1,95 @@ +/* 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 CatalogRouteImport } from './routes/catalog' +import { Route as ProductsRouteImport } from './routes/products' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const CatalogRoute = CatalogRouteImport.update({ + id: '/catalog', + path: '/catalog', + getParentRoute: () => rootRouteImport, +} as any) +const ProductsRoute = ProductsRouteImport.update({ + id: '/products', + path: '/products', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/catalog': typeof CatalogRoute + '/products': typeof ProductsRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/catalog': typeof CatalogRoute + '/products': typeof ProductsRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/catalog': typeof CatalogRoute + '/products': typeof ProductsRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/catalog' | '/products' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/catalog' | '/products' + id: '__root__' | '/' | '/catalog' | '/products' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + CatalogRoute: typeof CatalogRoute + ProductsRoute: typeof ProductsRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/catalog': { + id: '/catalog' + path: '/catalog' + fullPath: '/catalog' + preLoaderRoute: typeof CatalogRouteImport + parentRoute: typeof rootRouteImport + } + '/products': { + id: '/products' + path: '/products' + fullPath: '/products' + preLoaderRoute: typeof ProductsRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + CatalogRoute: CatalogRoute, + ProductsRoute: ProductsRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/benchmarks/client-nav/scenarios/search-params/vue/src/routes/__root.tsx b/benchmarks/client-nav/scenarios/search-params/vue/src/routes/__root.tsx new file mode 100644 index 0000000000..b4cb07f2ae --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/vue/src/routes/__root.tsx @@ -0,0 +1,114 @@ +import * as Vue from 'vue' +import { Link, Outlet, createRootRoute, useSearch } from '@tanstack/vue-router' +import { + changedCategories, + computeChecksum, + initialProductsSearch, +} from '../../../shared' + +const rootSubscribers = Array.from({ length: 4 }, (_, index) => index) + +const RootSearchSubscriber = Vue.defineComponent({ + setup() { + const value = useSearch({ + strict: false, + select: (search) => computeChecksum(Number(search.page ?? 0)), + }) + + return () => { + void computeChecksum(value.value) + return null + } + }, +}) + +const RootComponent = Vue.defineComponent({ + setup() { + return () => ( + <> + {rootSubscribers.map((index) => ( + + ))} + + + + ) + }, +}) + +export const Route = createRootRoute({ + component: RootComponent, +}) diff --git a/benchmarks/client-nav/scenarios/search-params/vue/src/routes/catalog.tsx b/benchmarks/client-nav/scenarios/search-params/vue/src/routes/catalog.tsx new file mode 100644 index 0000000000..6a09efdd4a --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/vue/src/routes/catalog.tsx @@ -0,0 +1,49 @@ +import * as Vue from 'vue' +import { createFileRoute, retainSearchParams } from '@tanstack/vue-router' +import type { SearchSchemaInput } from '@tanstack/vue-router' +import { + catalogMarkerText, + computeChecksum, + normalizeCatalogSearch, +} from '../../../shared' + +const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) + +const ViewSubscriber = Vue.defineComponent({ + setup() { + const value = Route.useSearch({ + select: (search) => + computeChecksum(search.view.length * 5 + search.page * 11), + }) + + return () => { + void computeChecksum(value.value) + return null + } + }, +}) + +const CatalogPage = Vue.defineComponent({ + setup() { + const search = Route.useSearch() + + return () => ( +
+ {subscriberIndexes.map((index) => ( + + ))} +

Catalog

+
{catalogMarkerText(search.value)}
+
+ ) + }, +}) + +export const Route = createFileRoute('/catalog')({ + validateSearch: (search: Record & SearchSchemaInput) => + normalizeCatalogSearch(search), + search: { + middlewares: [retainSearchParams(['perPage', 'sort'])], + }, + component: CatalogPage, +}) diff --git a/benchmarks/client-nav/scenarios/search-params/vue/src/routes/index.tsx b/benchmarks/client-nav/scenarios/search-params/vue/src/routes/index.tsx new file mode 100644 index 0000000000..081aa7b4fd --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/vue/src/routes/index.tsx @@ -0,0 +1,17 @@ +import * as Vue from 'vue' +import { createFileRoute } from '@tanstack/vue-router' + +const HomePage = Vue.defineComponent({ + setup() { + return () => ( +
+

Search Params Bench

+
home
+
+ ) + }, +}) + +export const Route = createFileRoute('/')({ + component: HomePage, +}) diff --git a/benchmarks/client-nav/scenarios/search-params/vue/src/routes/products.tsx b/benchmarks/client-nav/scenarios/search-params/vue/src/routes/products.tsx new file mode 100644 index 0000000000..8be1683e14 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/vue/src/routes/products.tsx @@ -0,0 +1,108 @@ +import * as Vue from 'vue' +import { + createFileRoute, + retainSearchParams, + stripSearchParams, +} from '@tanstack/vue-router' +import type { SearchSchemaInput } from '@tanstack/vue-router' +import { + computeChecksum, + normalizeProductsSearch, + productsLoaderChecksum, + productsMarkerText, +} from '../../../shared' + +const subscriberIndexes = Array.from({ length: 2 }, (_, index) => index) + +const PageSubscriber = Vue.defineComponent({ + setup() { + const value = Route.useSearch({ + select: (search) => computeChecksum(search.page * 31 + search.perPage), + }) + + return () => { + void computeChecksum(value.value) + return null + } + }, +}) + +const FiltersSubscriber = Vue.defineComponent({ + setup() { + const value = Route.useSearch({ + select: (search) => + computeChecksum( + search.filters.categories.length * 7 + + (search.filters.price.max - search.filters.price.min) + + search.filters.tags.length * 3, + ), + }) + + return () => { + void computeChecksum(value.value) + return null + } + }, +}) + +const QuerySubscriber = Vue.defineComponent({ + setup() { + const value = Route.useSearch({ + select: (search) => + computeChecksum(search.q.length * 13 + search.sort.length), + }) + + return () => { + void computeChecksum(value.value) + return null + } + }, +}) + +const ProductsPage = Vue.defineComponent({ + setup() { + const search = Route.useSearch() + const loaderData = Route.useLoaderData() + + return () => ( +
+ {subscriberIndexes.map((index) => ( + + ))} + {subscriberIndexes.map((index) => ( + + ))} + {subscriberIndexes.map((index) => ( + + ))} +

Products

+
+ {productsMarkerText(search.value)} +
+

{`checksum ${loaderData.value.checksum}`}

+
+ ) + }, +}) + +export const Route = createFileRoute('/products')({ + validateSearch: (search: Record & SearchSchemaInput) => + normalizeProductsSearch(search), + search: { + middlewares: [ + retainSearchParams(['perPage', 'sort']), + stripSearchParams({ page: 1 }), + ], + }, + loaderDeps: ({ search }) => ({ + page: search.page, + sort: search.sort, + filters: search.filters, + }), + loader: ({ deps }) => ({ + checksum: productsLoaderChecksum(deps), + }), + staleTime: 1e9, + gcTime: 1e9, + component: ProductsPage, +}) diff --git a/benchmarks/client-nav/scenarios/search-params/vue/tsconfig.json b/benchmarks/client-nav/scenarios/search-params/vue/tsconfig.json new file mode 100644 index 0000000000..7786fc3da9 --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/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/search-params/vue/vite.config.ts b/benchmarks/client-nav/scenarios/search-params/vue/vite.config.ts new file mode 100644 index 0000000000..27490b276a --- /dev/null +++ b/benchmarks/client-nav/scenarios/search-params/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 search-params (vue)', + watch: false, + environment: 'jsdom', + setupFiles: ['../../../vitest.setup.ts'], + }, +}) 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 24db8fe745..0c26b32f5f 100644 --- a/benchmarks/client-nav/solid/vite.config.ts +++ b/benchmarks/client-nav/solid/vite.config.ts @@ -1,8 +1,15 @@ +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. +const rootDir = fileURLToPath(new URL('..', import.meta.url)) export default defineConfig({ + root: rootDir, define: { 'process.env.NODE_ENV': JSON.stringify('production'), }, @@ -25,10 +32,12 @@ export default defineConfig({ conditions: ['solid', 'browser'], }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav (solid)', watch: false, environment: 'jsdom', - setupFiles: ['./vitest.setup.ts'], + setupFiles: [`${rootDir}vitest.setup.ts`], + benchmark: { include: ['solid/speed.bench.ts'] }, server: { deps: { inline: [/@solidjs/, /@tanstack\/solid-store/], diff --git a/benchmarks/client-nav/vitest.config.ts b/benchmarks/client-nav/vitest.config.ts index 14776452ed..808e7fc724 100644 --- a/benchmarks/client-nav/vitest.config.ts +++ b/benchmarks/client-nav/vitest.config.ts @@ -7,6 +7,9 @@ export default defineConfig({ './react/vite.config.ts', './solid/vite.config.ts', './vue/vite.config.ts', + './scenarios/*/react/vite.config.ts', + './scenarios/*/solid/vite.config.ts', + './scenarios/*/vue/vite.config.ts', ], }, }) diff --git a/benchmarks/client-nav/vitest.react.config.ts b/benchmarks/client-nav/vitest.react.config.ts new file mode 100644 index 0000000000..a397ad929e --- /dev/null +++ b/benchmarks/client-nav/vitest.react.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + watch: false, + projects: ['./react/vite.config.ts', './scenarios/*/react/vite.config.ts'], + }, +}) diff --git a/benchmarks/client-nav/vitest.solid.config.ts b/benchmarks/client-nav/vitest.solid.config.ts new file mode 100644 index 0000000000..b8827b86aa --- /dev/null +++ b/benchmarks/client-nav/vitest.solid.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + watch: false, + projects: ['./solid/vite.config.ts', './scenarios/*/solid/vite.config.ts'], + }, +}) diff --git a/benchmarks/client-nav/vitest.vue.config.ts b/benchmarks/client-nav/vitest.vue.config.ts new file mode 100644 index 0000000000..17960d7569 --- /dev/null +++ b/benchmarks/client-nav/vitest.vue.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + watch: false, + projects: ['./vue/vite.config.ts', './scenarios/*/vue/vite.config.ts'], + }, +}) 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 d917c82e2d..78d8ae5638 100644 --- a/benchmarks/client-nav/vue/vite.config.ts +++ b/benchmarks/client-nav/vue/vite.config.ts @@ -1,9 +1,16 @@ +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 { 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. +const rootDir = fileURLToPath(new URL('..', import.meta.url)) export default defineConfig({ + root: rootDir, define: { 'process.env.NODE_ENV': JSON.stringify('production'), }, @@ -24,9 +31,11 @@ export default defineConfig({ }, }, test: { + execArgv: cpuSimulationExecArgv(), name: '@benchmarks/client-nav (vue)', watch: false, environment: 'jsdom', - setupFiles: ['./vitest.setup.ts'], + 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 d9fb24f752..18b68768f9 100644 --- a/benchmarks/memory/README.md +++ b/benchmarks/memory/README.md @@ -2,7 +2,13 @@ Dedicated memory benchmarks for TanStack Router / Start, measured with the CodSpeed **memory instrument** (`mode: memory` in -`.github/workflows/client-nav-benchmarks.yml`). Two separate benchmarks: +`.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 +flags phantom regressions on every PR until the next run lands. (Falling back +across a docs-only commit is safe: the previous run's benchmark-relevant code +is identical.) Two separate benchmarks: - `server/` (`@benchmarks/memory-server`) — React/Solid/Vue Start apps, requests against the built server handler (`handler.fetch`), Node environment. @@ -28,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 @@ -37,34 +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. 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 | @@ -76,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) | @@ -91,10 +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 one documented exception: `streaming-peak`'s - deferred sections use small `setTimeout` delays so deferred stream chunks are - observable across framework renderers. +- 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 @@ -168,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. @@ -184,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/shared.ts b/benchmarks/memory/client/scenarios/interrupted-navigations/shared.ts index 0e01e92e08..80f234f0c8 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/shared.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/shared.ts @@ -35,7 +35,6 @@ type RenderedEvent = { } type InterruptedNavigationRouter = { - latestLoadPromise: Promise | undefined load: () => Promise navigate: (options: { to: '/fast/$id' | '/slow/$id' @@ -104,18 +103,6 @@ function assertSlowNavigationSettlement(settlement: NavigationSettlement) { ) } -async function awaitExpectedLoadSettlement(loadPromise: Promise) { - try { - await loadPromise - } catch (reason) { - if (reasonHasAbortShape(reason) || reasonHasCancellationShape(reason)) { - return - } - - throw reason - } -} - function reasonHasAbortShape(reason: unknown) { return reason instanceof DOMException && reason.name === 'AbortError' } @@ -144,7 +131,6 @@ export function createWorkload( let navigateFast: (id: string) => Promise = uninitialized let startSlowNavigation: (id: string) => Promise = uninitializedSettlement - let getLatestLoadPromise: () => Promise | undefined = () => undefined function assertRenderedPage(page: 'shell' | 'fast', id?: string) { const element = container?.querySelector('[data-bench-page]') @@ -203,7 +189,6 @@ export function createWorkload( const mounted = mountTestApp(container) const router = mounted.router as InterruptedNavigationRouter unmount = mounted.unmount - getLatestLoadPromise = () => router.latestLoadPromise unsub = router.subscribe('onRendered', (event) => { if ( @@ -265,7 +250,6 @@ export function createWorkload( expectedRenderedPath = undefined navigateFast = uninitialized startSlowNavigation = uninitializedSettlement - getLatestLoadPromise = () => undefined } async function interrupt( @@ -276,12 +260,6 @@ export function createWorkload( const slowNavigation = startSlowNavigation(slowId) await waitForSlowLoader(slowId) - const slowLoadPromise = getLatestLoadPromise() - - if (!slowLoadPromise) { - throw new Error(`Slow navigation did not start a load for id: ${slowId}`) - } - await navigateFast(fastId) resolveSlowLoader(slowId) @@ -291,12 +269,11 @@ export function createWorkload( assertSlowNavigationSettlement(settlement) } - await awaitExpectedLoadSettlement(slowLoadPromise) await drainMicrotasks() } return { - name: `mem interrupted-navigations (${framework})`, + name: `mem client interrupted-navigations (${framework})`, before, interrupt, async run() { 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/shared.ts b/benchmarks/memory/client/scenarios/loader-data-retention/shared.ts index a5c496cb81..bd90c023f0 100644 --- a/benchmarks/memory/client/scenarios/loader-data-retention/shared.ts +++ b/benchmarks/memory/client/scenarios/loader-data-retention/shared.ts @@ -163,7 +163,7 @@ export function createWorkload( } return { - name: `mem loader-data-retention (${framework})`, + name: `mem client loader-data-retention (${framework})`, before, navigate: (id: string) => navigateTo(id), async run() { 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/shared.ts b/benchmarks/memory/client/scenarios/mount-unmount/shared.ts index 4f9b9f430f..01cfe8c46a 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/shared.ts +++ b/benchmarks/memory/client/scenarios/mount-unmount/shared.ts @@ -58,7 +58,7 @@ export function createWorkload( } return { - name: `mem mount-unmount (${framework})`, + name: `mem client mount-unmount (${framework})`, cycle, async run() { for (let index = 0; index < mountUnmountIterations; index++) { 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/shared.ts b/benchmarks/memory/client/scenarios/navigation-churn/shared.ts index 0745de2116..7eaf1a8b66 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/shared.ts +++ b/benchmarks/memory/client/scenarios/navigation-churn/shared.ts @@ -105,7 +105,7 @@ export function createWorkload( } return { - name: `mem navigation-churn (${framework})`, + name: `mem client navigation-churn (${framework})`, before, navigate: (target: Target) => navigateTo(target), async run() { 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 78e35c42ad..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 @@ -180,7 +176,7 @@ export function createWorkload( } return { - name: `mem preload-churn (${framework})`, + name: `mem client preload-churn (${framework})`, before, preload: (id: string) => preloadItem(id), evictPreloads, 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/shared.ts b/benchmarks/memory/client/scenarios/unique-location-churn/shared.ts index 95b382269d..3b36c7811e 100644 --- a/benchmarks/memory/client/scenarios/unique-location-churn/shared.ts +++ b/benchmarks/memory/client/scenarios/unique-location-churn/shared.ts @@ -123,7 +123,7 @@ export function createWorkload( } return { - name: `mem unique-location-churn (${framework})`, + name: `mem client unique-location-churn (${framework})`, before, navigate: (location: ItemLocation) => navigateTo(location), async run() { 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 f1f5dadea0..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 } @@ -48,7 +50,7 @@ export async function drainResponse(response: Response) { } try { - while (true) { + for (;;) { const result = await reader.read() if (result.done) { @@ -88,3 +90,10 @@ export async function runSequentialRequestLoop( await drainResponse(response) } } + +// 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)) + } +} 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 a3f4836091..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,6 +23,7 @@ export default defineConfig({ minify: false, }, test: { + ...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 9b71c37617..29eca99e00 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/shared.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/shared.ts @@ -1,3 +1,4 @@ +import { settle } from '#memory-server/bench-utils' import type { StartRequestHandler } from '#memory-server/bench-utils' export type { StartRequestHandler } @@ -5,16 +6,7 @@ export type { StartRequestHandler } type Framework = 'react' | 'solid' | 'vue' type AbortedRequestReadMode = 'first-chunk' | 'shell-before-deferred' -type AbortedRequestCancelMode = 'plain' | 'swallow-abort-error' -type AbortedRequestDrainMode = 'microtasks' | 'tasks' - -type AbortedRequestMode = { - readMode: AbortedRequestReadMode - cancelMode: AbortedRequestCancelMode - drainMode: AbortedRequestDrainMode -} - -const abortedRequestIterations = 100 +const abortedRequestIterations = 40 let abortedRequestCounter = 0 const eagerMarker = 'data-bench="aborted-requests-eager"' const alphaFallbackMarker = 'data-bench="aborted-requests-alpha-fallback"' @@ -25,22 +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', - drainMode: 'microtasks', - }, - solid: { - readMode: 'first-chunk', - cancelMode: 'plain', - drainMode: 'tasks', - }, - vue: { - readMode: 'shell-before-deferred', - cancelMode: 'swallow-abort-error', - drainMode: 'tasks', - }, +const abortedRequestModes: Record = { + react: 'first-chunk', + solid: 'first-chunk', + vue: 'shell-before-deferred', } const documentRequestInit = { @@ -100,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 @@ -141,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) } @@ -169,37 +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() -} - -async function drainCancellation(mode: AbortedRequestDrainMode) { - await Promise.resolve() - await Promise.resolve() - - if (mode === 'tasks') { - await new Promise((resolve) => setTimeout(resolve, 0)) } } async function assertAbortedRequestsSanity( handler: StartRequestHandler, - mode: AbortedRequestMode, + mode: AbortedRequestReadMode, ) { const fullId = 'sanity-full' const fullRequest = buildStreamRequest(fullId) @@ -232,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(mode.drainMode) + 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() @@ -247,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(mode.drainMode) + await cancelReader(reader) + await settle() } } @@ -264,13 +221,13 @@ 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), workloads: [ { - name: `mem aborted-requests (${framework})`, + name: `mem server aborted-requests (${framework})`, run, }, ], 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 95d69ad91d..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,74 +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 alphaDelayMs = 50 -const betaDelayMs = 75 -const abortProbeAlphaDelayMs = 500 -const abortProbeBetaDelayMs = 750 - -function isAbortProbeId(id: string) { - return id === 'sanity-mid-stream' || id.startsWith('abort-') -} - -function getDelay(id: string, group: RecordGroup) { - if (isAbortProbeId(id)) { - return group === 'alpha' ? abortProbeAlphaDelayMs : abortProbeBetaDelayMs - } - - return group === 'alpha' ? alphaDelayMs : betaDelayMs -} - -function resolveAfterDelay( - delayMs: number, - signal: AbortSignal, - value: () => T, - abortedValue: () => T, -) { - return new Promise((resolve) => { - if (signal.aborted) { - resolve(abortedValue()) - return - } - - const timeoutId = setTimeout(() => { - signal.removeEventListener('abort', onAbort) - resolve(value()) - }, delayMs) - - const onAbort = () => { - clearTimeout(timeoutId) - resolve(abortedValue()) - } - - signal.addEventListener('abort', onAbort, { once: true }) - }) -} - -function makeDeferredRecords( - id: string, - group: RecordGroup, - signal: AbortSignal, -) { - const delayMs = getDelay(id, group) - - return resolveAfterDelay( - delayMs, - 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 d3a374cab7..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,6 +23,7 @@ export default defineConfig({ minify: false, }, test: { + ...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 d064bf75e9..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,120 +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 alphaDelayMs = 50 -const betaDelayMs = 75 -const abortProbeAlphaDelayMs = 500 -const abortProbeBetaDelayMs = 750 +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 getDelay(id: string, group: RecordGroup) { - if (isAbortProbeId(id)) { - return group === 'alpha' ? abortProbeAlphaDelayMs : abortProbeBetaDelayMs - } - - return group === 'alpha' ? alphaDelayMs : betaDelayMs -} - -function resolveAfterDelay( - delayMs: number, - signal: AbortSignal, - value: () => T, - abortedValue: () => T, -) { - return new Promise((resolve) => { - if (signal.aborted) { - resolve(abortedValue()) - return - } - - const timeoutId = setTimeout(() => { - signal.removeEventListener('abort', onAbort) - resolve(value()) - }, delayMs) - - const onAbort = () => { - clearTimeout(timeoutId) - resolve(abortedValue()) - } - - signal.addEventListener('abort', onAbort, { once: true }) - }) -} - -function makeDeferredRecords( - id: string, - group: RecordGroup, - signal: AbortSignal, -) { - const delayMs = getDelay(id, group) - - return resolveAfterDelay( - delayMs, - 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 2b42e2be39..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,6 +23,7 @@ export default defineConfig({ minify: false, }, test: { + ...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 2a4fd9818a..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,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + 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 d4c1877465..11ed293d22 100644 --- a/benchmarks/memory/server/scenarios/error-paths/shared.ts +++ b/benchmarks/memory/server/scenarios/error-paths/shared.ts @@ -9,7 +9,7 @@ export type { StartRequestHandler } type Framework = 'react' | 'solid' | 'vue' -const errorPathsIterations = 50 +const errorPathsIterations = 18 const redirectSeed = 0xdecafbad const notFoundSeed = 0xdecafb0d const errorSeed = 0xdecafbed @@ -136,7 +136,7 @@ export function createWorkloadGroup( framework: Framework, handler: StartRequestHandler, ) { - const runRedirect = () => + const runRedirect = async () => runSequentialRequestLoop(handler, { random: redirectRandom, iterations: errorPathsIterations, @@ -144,7 +144,7 @@ export function createWorkloadGroup( validateResponse: validateRedirectResponse, }) - const runNotFound = () => + const runNotFound = async () => runSequentialRequestLoop(handler, { random: notFoundRandom, iterations: errorPathsIterations, @@ -152,7 +152,7 @@ export function createWorkloadGroup( validateResponse: validateNotFoundResponse, }) - const runError = () => + const runError = async () => runSequentialRequestLoop(handler, { random: errorRandom, iterations: errorPathsIterations, @@ -160,7 +160,7 @@ export function createWorkloadGroup( validateResponse: validateErrorResponse, }) - const runUnmatched = () => + const runUnmatched = async () => runSequentialRequestLoop(handler, { random: unmatchedRandom, iterations: errorPathsIterations, @@ -172,19 +172,19 @@ export function createWorkloadGroup( sanity: () => assertErrorPathsSanity(handler), workloads: [ { - name: `mem error-paths redirect (${framework})`, + name: `mem server error-paths redirect (${framework})`, run: runRedirect, }, { - name: `mem error-paths not-found (${framework})`, + name: `mem server error-paths not-found (${framework})`, run: runNotFound, }, { - name: `mem error-paths error (${framework})`, + name: `mem server error-paths error (${framework})`, run: runError, }, { - name: `mem error-paths unmatched (${framework})`, + name: `mem server error-paths unmatched (${framework})`, run: runUnmatched, }, ], 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 7f89abb099..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,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + 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 b5cf79924a..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,6 +23,8 @@ export default defineConfig({ minify: false, }, test: { + 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 7d4fa70196..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,6 +23,7 @@ export default defineConfig({ minify: false, }, test: { + ...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 36a91fa49d..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,7 +48,7 @@ export function createWorkloadGroup( framework: Framework, handler: StartRequestHandler, ) { - const run = () => + const run = async () => runSequentialRequestLoop(handler, { seed: benchmarkSeed, iterations: peakLargePageIterations, @@ -60,7 +60,7 @@ export function createWorkloadGroup( sanity: () => assertPeakLargePageSanity(handler), workloads: [ { - name: `mem peak-large-page (${framework})`, + name: `mem server peak-large-page (${framework})`, run, }, ], 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 ffc80b43aa..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,6 +23,7 @@ export default defineConfig({ minify: false, }, test: { + ...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 67bdf9b79d..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,6 +23,7 @@ export default defineConfig({ minify: false, }, test: { + ...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 4b75255eb1..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,6 +23,7 @@ export default defineConfig({ minify: false, }, test: { + ...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 1739e4cc59..b200c96ed6 100644 --- a/benchmarks/memory/server/scenarios/request-churn/shared.ts +++ b/benchmarks/memory/server/scenarios/request-churn/shared.ts @@ -10,7 +10,7 @@ export type { StartRequestHandler } type Framework = 'react' | 'solid' | 'vue' const benchmarkSeed = 0xdecafbad -const requestChurnIterations = 200 +const requestChurnIterations = 40 const itemPageMarker = 'data-bench="request-churn-item"' // Module-level so CodSpeed warmups and measurement never replay URLs. const benchmarkRandom = createDeterministicRandom(benchmarkSeed) @@ -62,7 +62,7 @@ export function createWorkloadGroup( return new Request(`http://localhost/items/${id}?q=${q}`, requestInit) } - const run = () => + const run = async () => runSequentialRequestLoop(handler, { random: benchmarkRandom, iterations: requestChurnIterations, @@ -74,7 +74,7 @@ export function createWorkloadGroup( sanity: () => assertRequestChurnSanity(handler), workloads: [ { - name: `mem request-churn (${framework})`, + name: `mem server request-churn (${framework})`, run, }, ], 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 8ff879e9e0..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,6 +23,7 @@ export default defineConfig({ minify: false, }, test: { + ...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 bcfa82b0ca..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,6 +23,7 @@ export default defineConfig({ minify: false, }, test: { + ...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 cfcc305c1a..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,6 +23,7 @@ export default defineConfig({ minify: false, }, test: { + ...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 c02990bbf9..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 = 20 +const serializationPayloadIterations = 1 const payloadPageMarker = 'data-bench="serialization-payload"' const requestInit = { @@ -55,7 +55,7 @@ export function createWorkloadGroup( framework: Framework, handler: StartRequestHandler, ) { - const run = () => + const run = async () => runSequentialRequestLoop(handler, { seed: benchmarkSeed, iterations: serializationPayloadIterations, @@ -67,7 +67,7 @@ export function createWorkloadGroup( sanity: () => assertSerializationPayloadSanity(handler), workloads: [ { - name: `mem serialization-payload (${framework})`, + name: `mem server serialization-payload (${framework})`, run, }, ], 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 26f57c9baa..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,6 +23,7 @@ export default defineConfig({ minify: false, }, test: { + ...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 b67693e559..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,6 +23,7 @@ export default defineConfig({ minify: false, }, test: { + ...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 8a3eea0d36..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,6 +23,7 @@ export default defineConfig({ minify: false, }, test: { + ...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 ad1022c836..167b24d3b6 100644 --- a/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts +++ b/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts @@ -38,7 +38,7 @@ type SerovalNode = const benchmarkSeed = 0xdecafbad const payloadSeed = 0x51f0cafe const fixtureCount = 16 -const serverFnChurnIterations = 150 +const serverFnChurnIterations = 30 const origin = 'http://localhost' const tssContentTypeFramed = 'application/x-tss-framed' const acceptHeader = `${tssContentTypeFramed}, application/x-ndjson, application/json` @@ -202,7 +202,7 @@ export async function createWorkloadGroup( handler: StartRequestHandler, ) { const urls = await discoverUrls(handler) - const run = () => + const run = async () => runSequentialRequestLoop(handler, { seed: benchmarkSeed, iterations: serverFnChurnIterations, @@ -224,7 +224,7 @@ export async function createWorkloadGroup( sanity: () => assertServerFnChurnSanity(handler, urls), workloads: [ { - name: `mem server-fn-churn (${framework})`, + name: `mem server server-fn-churn (${framework})`, run, }, ], 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 8ffdc48227..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,6 +23,7 @@ export default defineConfig({ minify: false, }, test: { + ...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 02b404808e..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,6 +23,7 @@ export default defineConfig({ minify: false, }, test: { + ...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/src/routes/stream.$id.tsx b/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/stream.$id.tsx index aa8ba5e865..886cb64d45 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/stream.$id.tsx +++ b/benchmarks/memory/server/scenarios/streaming-peak/react/src/routes/stream.$id.tsx @@ -5,7 +5,7 @@ import { type DeferredSectionPayload, } from '../../../deferred-section-data' -const fallbackFlushDelayMs = 1 +const fallbackFlushTicks = 4 export const Route = createFileRoute('/stream/$id')({ loader: ({ params }) => ({ @@ -23,13 +23,28 @@ export const Route = createFileRoute('/stream/$id')({ // router load (sections resolve before the Suspense boundaries are even // reached) and setImmediate chains registered at loader time win the race // against React's flush — either way no fallback ever streams and the bench -// stops exercising multi-flush streaming. Timer-phase callbacks reliably lose -// that race, so this is the documented exception to the no-timers convention: -// the few ms of wall-clock are irrelevant to memory metrics, and distinct -// delays keep section ordering deterministic. +// stops exercising multi-flush streaming. Timers-phase callbacks reliably +// lose that race, but a millisecond delay makes the loss margin wall-clock +// dependent, so this chains 0ms hops instead: each hop yields one full +// event-loop turn (immediates and microtasks included), making the flush +// ordering a function of turn count, not runner speed. Distinct hop counts +// keep section ordering deterministic. function afterFallbackFlush(sectionIndex: number) { return new Promise((resolve) => { - setTimeout(resolve, fallbackFlushDelayMs + sectionIndex) + let remaining = fallbackFlushTicks + sectionIndex + + const step = () => { + remaining -= 1 + + if (remaining <= 0) { + resolve() + return + } + + setTimeout(step, 0) + } + + setTimeout(step, 0) }) } 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 733aabb76d..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,6 +23,7 @@ export default defineConfig({ minify: false, }, test: { + ...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 a82c43b5b4..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,7 +92,7 @@ export function createWorkloadGroup( framework: Framework, handler: StartRequestHandler, ) { - const run = () => + const run = async () => runSequentialRequestLoop(handler, { seed: benchmarkSeed, iterations: streamingPeakIterations, @@ -101,10 +101,15 @@ export function createWorkloadGroup( }) 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 streaming-peak chunked (${framework})`, + name: `mem server streaming-peak chunked (${framework})`, run, }, ], 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/src/routes/stream.$id.tsx b/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/stream.$id.tsx index 0a3f64ffd4..977f43061e 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/stream.$id.tsx +++ b/benchmarks/memory/server/scenarios/streaming-peak/solid/src/routes/stream.$id.tsx @@ -5,7 +5,7 @@ import { type DeferredSectionPayload, } from '../../../deferred-section-data' -const fallbackFlushDelayMs = 25 +const fallbackFlushTicks = 12 export const Route = createFileRoute('/stream/$id')({ loader: ({ params }) => ({ @@ -20,9 +20,25 @@ export const Route = createFileRoute('/stream/$id')({ // Deferred sections must settle after the framework shell flush so the bench // continues exercising multi-flush streaming with visible fallback chunks. +// Chained 0ms timers-phase hops give the renderer a deterministic number of +// full event-loop turns to flush, instead of a wall-clock delay whose margin +// varies with runner load; distinct hop counts keep section ordering stable. function afterFallbackFlush(sectionIndex: number) { return new Promise((resolve) => { - setTimeout(resolve, fallbackFlushDelayMs + sectionIndex) + let remaining = fallbackFlushTicks + sectionIndex + + const step = () => { + remaining -= 1 + + if (remaining <= 0) { + resolve() + return + } + + setTimeout(step, 0) + } + + setTimeout(step, 0) }) } 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 b7d98e709c..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,6 +23,7 @@ export default defineConfig({ minify: false, }, test: { + ...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 963782403b..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,11 +1,52 @@ import { Await, createFileRoute } from '@tanstack/vue-router' -import { Suspense } from 'vue' +import { Suspense, defineComponent } from 'vue' import { makeDeferredSectionPayload, type DeferredSectionPayload, } from '../../../deferred-section-data' -const fallbackFlushDelayMs = 1 +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 }) => ({ @@ -20,9 +61,25 @@ export const Route = createFileRoute('/stream/$id')({ // Deferred sections must settle strictly AFTER Vue's shell has a chance to // flush, so fallbacks are emitted before deferred section content. +// Chained 0ms timers-phase hops give the renderer a deterministic number of +// full event-loop turns to flush, instead of a wall-clock delay whose margin +// varies with runner load; distinct hop counts keep section ordering stable. function afterFallbackFlush(sectionIndex: number) { return new Promise((resolve) => { - setTimeout(resolve, fallbackFlushDelayMs + sectionIndex) + let remaining = fallbackFlushTicks + sectionIndex + + const step = () => { + remaining -= 1 + + if (remaining <= 0) { + resolve() + return + } + + setTimeout(step, 0) + } + + setTimeout(step, 0) }) } @@ -32,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 9634031b31..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,6 +23,7 @@ export default defineConfig({ minify: false, }, test: { + ...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 67fe4f17f6..b5009ebe68 100644 --- a/docs/router/api/router/RouteMatchType.md +++ b/docs/router/api/router/RouteMatchType.md @@ -13,7 +13,6 @@ interface RouteMatch { params: Route['allParams'] 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 f49ccb1a7c..4da9cd9bb6 100644 --- a/docs/router/api/router/RouterStateType.md +++ b/docs/router/api/router/RouterStateType.md @@ -3,7 +3,9 @@ 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 = { @@ -11,7 +13,7 @@ type RouterState = { isLoading: boolean matches: Array location: ParsedLocation - resolvedLocation: ParsedLocation + resolvedLocation?: ParsedLocation } ``` @@ -22,17 +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. +- `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 @@ -41,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 453294ab6e..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,16 +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 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: @@ -168,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 } } @@ -200,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 068cbfed1a..27dadd361f 100644 --- a/docs/router/how-to/debug-router-issues.md +++ b/docs/router/how-to/debug-router-issues.md @@ -322,10 +322,16 @@ const route = createRoute({ ```tsx function DataLoadingDebug() { - const location = useLocation() + const state = useRouterState() console.log('Route status:', { - isLoading: location.isLoading, + 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 23fdd63226..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_
@@ -298,7 +325,7 @@ npm install srvx ```json "build": "rsbuild build", - "start": "srvx --prod -s dist/client dist/server/index.js" + "start": "srvx --prod -s ../client dist/server/index.js" ``` Express or any other custom Node.js server works too, as long as it serves the client assets and calls the server entry's `fetch` handler for dynamic requests. @@ -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 dd0956e96f..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:^", @@ -18,7 +18,7 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", 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 93e1263d11..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,11 +15,11 @@ "@tanstack/router-plugin": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "zod": "^4.4.3" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", 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 14a8f0373f..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,11 +17,12 @@ "@tanstack/router-plugin": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", + "redaxios": "catalog:", "tailwindcss": "^4.2.2", "zod": "^4.4.3" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.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 da2df215af..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,12 +18,12 @@ "@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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.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 62ae2cfb73..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 }) => { @@ -246,7 +247,7 @@ async function getRenderCount(page: Page) { return renderCount } async function structuralSharingTest(page: Page, enabled: boolean) { - await page.goto(`/structural-sharing/${enabled}/?foo=f1&bar=b1`) + page.goto(`/structural-sharing/${enabled}/?foo=f1&bar=b1`) await expect(page.getByTestId('enabled')).toHaveText(JSON.stringify(enabled)) async function checkSearch({ foo, bar }: { foo: string; bar: string }) { @@ -268,9 +269,9 @@ async function structuralSharingTest(page: Page, enabled: boolean) { test('structural sharing disabled', async ({ page }) => { await structuralSharingTest(page, false) - expect(await getRenderCount(page)).toBe(3) + expect(await getRenderCount(page)).toBe(2) await page.getByTestId('link').click() - expect(await getRenderCount(page)).toBeGreaterThan(3) + expect(await getRenderCount(page)).toBeGreaterThan(2) }) test('structural sharing enabled', 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 3ad83fb455..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', () => { @@ -69,10 +70,7 @@ test.describe('Open redirect prevention', () => { page, baseURL, }) => { - // When control characters are stripped from paths like /%0d/evil.com/ - // the result could be //evil.com/ which is a protocol-relative URL - // Our fix collapses these to /evil.com/ to prevent external redirects - // This is already tested above, but we verify the collapsed path works + // %0d is kept encoded, so /%0d/test-path/ stays as-is and won't become //test-path/ await page.goto('/%0d/test-path/') await page.waitForLoadState('networkidle') @@ -80,8 +78,6 @@ test.describe('Open redirect prevention', () => { expect(page.url().startsWith(baseURL!)).toBe(true) const url = new URL(page.url()) expect(url.origin).toBe(new URL(baseURL!).origin) - // Path should be collapsed to /test-path (not //test-path/) - expect(url.pathname).toMatch(/^\/test-path\/?$/) }) }) 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 dd6c71afdd..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,12 +19,12 @@ "@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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.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 b66abda5fb..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,11 +18,11 @@ "@tanstack/router-devtools": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", 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 ab00360d48..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,11 +17,11 @@ "@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": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", 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 7b9c5945ee..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,12 +18,12 @@ "@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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.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 f3dbf81ce0..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,12 +18,12 @@ "@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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.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 c7c1661933..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,11 +16,12 @@ "@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.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", 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 961d2423cd..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:^", @@ -18,7 +18,7 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", 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 9fbe253126..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,11 +17,11 @@ "@tanstack/router-cli": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1", + "redaxios": "catalog:", "tailwindcss": "^4.2.2" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", 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 94a36498ed..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", @@ -19,14 +19,33 @@ }, "devDependencies": { "@inlang/paraglide-js": "^2.4.0", - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@tanstack/router-plugin": "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": { + "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-7120/vite.config.js b/e2e/react-router/issue-4759/vite.config.ts similarity index 100% rename from e2e/react-router/issue-7120/vite.config.js rename to e2e/react-router/issue-4759/vite.config.ts diff --git a/e2e/react-router/issue-7120/index.html b/e2e/react-router/issue-7120/index.html index de92cad2a3..04a3530c9d 100644 --- a/e2e/react-router/issue-7120/index.html +++ b/e2e/react-router/issue-7120/index.html @@ -3,10 +3,8 @@ - Issue 7120 - - -
+ Issues 7120 and 7367 - + + diff --git a/e2e/react-router/issue-7120/package.json b/e2e/react-router/issue-7120/package.json index da30014471..979b32556c 100644 --- a/e2e/react-router/issue-7120/package.json +++ b/e2e/react-router/issue-7120/package.json @@ -8,15 +8,16 @@ "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:^", + "@tanstack/router-plugin": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", diff --git a/e2e/react-router/issue-7120/playwright.config.ts b/e2e/react-router/issue-7120/playwright.config.ts index 6ba60eaff1..a8ba116fb4 100644 --- a/e2e/react-router/issue-7120/playwright.config.ts +++ b/e2e/react-router/issue-7120/playwright.config.ts @@ -1,21 +1,18 @@ 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({ testDir: './tests', workers: 1, reporter: [['line']], - use: { - baseURL, - }, + use: { baseURL }, webServer: { - command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, projects: [ diff --git a/e2e/react-router/issue-7120/src/main.tsx b/e2e/react-router/issue-7120/src/main.tsx index 08c46f529a..0c983251af 100644 --- a/e2e/react-router/issue-7120/src/main.tsx +++ b/e2e/react-router/issue-7120/src/main.tsx @@ -1,57 +1,7 @@ -import ReactDOM from 'react-dom/client' -import { - Outlet, - RouterProvider, - createRootRoute, - createRoute, - createRouter, - redirect, -} from '@tanstack/react-router' - -const posts = [ - { - id: '1', - title: 'sunt aut facere repellat provident occaecati', - }, -] - -const rootRoute = createRootRoute({ - component: RootComponent, - pendingMs: 0, - pendingComponent: () => { - ;(globalThis as any).__pendingSeen = true - return
loading
- }, - beforeLoad: async ({ matches }) => { - if (matches.find((match) => match.routeId === '/posts')) { - return - } - - await new Promise((resolve) => setTimeout(resolve, 1000)) - throw redirect({ to: '/posts' }) - }, -}) - -function RootComponent() { - return -} - -const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () =>
Home
, -}) - -const postsRoute = createRoute({ - getParentRoute: () => rootRoute, - path: 'posts', - loader: async () => { - await new Promise((resolve) => setTimeout(resolve, 10)) - return posts - }, -}).lazy(() => import('./posts.lazy').then((d) => d.Route)) - -const routeTree = rootRoute.addChildren([indexRoute, postsRoute]) +import { StrictMode } from 'react' +import { createRoot } from 'react-dom/client' +import { RouterProvider, createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' const router = createRouter({ routeTree, @@ -64,9 +14,8 @@ declare module '@tanstack/react-router' { } } -const rootElement = document.getElementById('app')! - -if (!rootElement.innerHTML) { - const root = ReactDOM.createRoot(rootElement) - root.render() -} +createRoot(document.getElementById('root')!).render( + + + , +) diff --git a/e2e/react-router/issue-7120/src/posts.lazy.tsx b/e2e/react-router/issue-7120/src/posts.lazy.tsx deleted file mode 100644 index f2635f2e08..0000000000 --- a/e2e/react-router/issue-7120/src/posts.lazy.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { Link, createLazyRoute } from '@tanstack/react-router' - -export const Route = createLazyRoute('/posts')({ - component: PostsComponent, -}) - -function PostsComponent() { - const posts = Route.useLoaderData() - - return ( -
-
    - {posts.map((post) => { - return ( -
  • - -
    {post.title.substring(0, 20)}
    - -
  • - ) - })} -
-
- ) -} diff --git a/e2e/react-router/issue-7120/src/redirectGate.ts b/e2e/react-router/issue-7120/src/redirectGate.ts new file mode 100644 index 0000000000..399d303aac --- /dev/null +++ b/e2e/react-router/issue-7120/src/redirectGate.ts @@ -0,0 +1,35 @@ +type RedirectGate = { + waiting: boolean + released: boolean + release: () => void +} + +declare global { + interface Window { + redirectGate: RedirectGate + } +} + +let releasePromise!: () => void +const promise = new Promise((resolve) => { + releasePromise = resolve +}) + +const redirectGate: RedirectGate = { + waiting: false, + released: false, + release: () => { + if (!redirectGate.released) { + redirectGate.released = true + releasePromise() + } + }, +} + +window.redirectGate = redirectGate + +export async function waitForRedirectGate() { + redirectGate.waiting = true + await promise + redirectGate.waiting = false +} diff --git a/e2e/react-router/issue-7120/src/routeTree.gen.ts b/e2e/react-router/issue-7120/src/routeTree.gen.ts new file mode 100644 index 0000000000..e8c6d92110 --- /dev/null +++ b/e2e/react-router/issue-7120/src/routeTree.gen.ts @@ -0,0 +1,77 @@ +/* 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 PostsRouteImport } from './routes/posts' + +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 + '/posts': typeof PostsRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/posts': typeof PostsRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/posts': typeof PostsRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/posts' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/posts' + id: '__root__' | '/' | '/posts' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + PostsRoute: typeof PostsRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/posts': { + id: '/posts' + path: '/posts' + fullPath: '/posts' + preLoaderRoute: typeof PostsRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + PostsRoute: PostsRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/e2e/react-router/issue-7120/src/routes/__root.tsx b/e2e/react-router/issue-7120/src/routes/__root.tsx new file mode 100644 index 0000000000..2f01516a55 --- /dev/null +++ b/e2e/react-router/issue-7120/src/routes/__root.tsx @@ -0,0 +1,33 @@ +import { Outlet, createRootRoute, redirect } from '@tanstack/react-router' +import { waitForRedirectGate } from '../redirectGate' + +let shouldRedirect = true + +export const Route = createRootRoute({ + pendingMs: 0, + pendingMinMs: 500, + pendingComponent: RootPendingComponent, + beforeLoad: async ({ location }) => { + if (location.pathname !== '/' || !shouldRedirect) { + return + } + + await waitForRedirectGate() + + if (!shouldRedirect) { + return + } + + shouldRedirect = false + throw redirect({ to: '/posts', replace: true }) + }, + component: () => , +}) + +function RootPendingComponent() { + return ( +
+ Loading route +
+ ) +} diff --git a/e2e/react-router/issue-7120/src/routes/index.tsx b/e2e/react-router/issue-7120/src/routes/index.tsx new file mode 100644 index 0000000000..1626ce706b --- /dev/null +++ b/e2e/react-router/issue-7120/src/routes/index.tsx @@ -0,0 +1,5 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: () =>
Home
, +}) diff --git a/e2e/react-router/issue-7120/src/routes/posts.lazy.tsx b/e2e/react-router/issue-7120/src/routes/posts.lazy.tsx new file mode 100644 index 0000000000..dc0b0cfd7f --- /dev/null +++ b/e2e/react-router/issue-7120/src/routes/posts.lazy.tsx @@ -0,0 +1,14 @@ +import { createLazyFileRoute } from '@tanstack/react-router' + +export const Route = createLazyFileRoute('/posts')({ + component: PostsComponent, +}) + +function PostsComponent() { + return ( +
+

Posts loaded

+

The redirected lazy route rendered.

+
+ ) +} diff --git a/e2e/react-router/issue-7120/src/routes/posts.tsx b/e2e/react-router/issue-7120/src/routes/posts.tsx new file mode 100644 index 0000000000..cc0519b74e --- /dev/null +++ b/e2e/react-router/issue-7120/src/routes/posts.tsx @@ -0,0 +1,3 @@ +import { createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/posts')({}) diff --git a/e2e/react-router/issue-7120/src/vite-env.d.ts b/e2e/react-router/issue-7120/src/vite-env.d.ts new file mode 100644 index 0000000000..11f02fe2a0 --- /dev/null +++ b/e2e/react-router/issue-7120/src/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/e2e/react-router/issue-7120/tests/issue-7120.repro.spec.ts b/e2e/react-router/issue-7120/tests/issue-7120.repro.spec.ts index 3b4d9a65cb..081ae73691 100644 --- a/e2e/react-router/issue-7120/tests/issue-7120.repro.spec.ts +++ b/e2e/react-router/issue-7120/tests/issue-7120.repro.spec.ts @@ -1,13 +1,13 @@ import { expect, test } from '@playwright/test' -test('root beforeLoad redirect does not blank when pending UI and view transitions are enabled (https://github.com/TanStack/router/issues/7120)', async ({ +test('#7120 / #7367: a root redirect cannot commit a stale match during a view transition', async ({ page, }) => { const pageErrors: Array = [] const consoleErrors: Array = [] page.on('pageerror', (error) => { - pageErrors.push(error.message) + pageErrors.push(error.message || String(error)) }) page.on('console', (message) => { if (message.type() === 'error') { @@ -17,12 +17,17 @@ test('root beforeLoad redirect does not blank when pending UI and view transitio await page.goto('/') + const pending = page.getByTestId('root-pending') + await expect(pending).toBeVisible() + expect(await page.evaluate(() => window.redirectGate.waiting)).toBe(true) + + await page.evaluate(() => window.redirectGate.release()) + await expect(page).toHaveURL(/\/posts$/) - await expect(page.getByText('sunt aut facere repe')).toBeVisible() - await expect - .poll(() => page.evaluate(() => (globalThis as any).__pendingSeen)) - .toBe(true) - await expect(page.getByTestId('root-pending')).not.toBeVisible() + await expect( + page.getByRole('heading', { name: 'Posts loaded' }), + ).toBeVisible() + await expect(pending).not.toBeVisible() expect(pageErrors).toEqual([]) expect(consoleErrors).toEqual([]) }) diff --git a/e2e/react-router/issue-7120/vite.config.ts b/e2e/react-router/issue-7120/vite.config.ts new file mode 100644 index 0000000000..5b1c613906 --- /dev/null +++ b/e2e/react-router/issue-7120/vite.config.ts @@ -0,0 +1,7 @@ +import { defineConfig } from 'vite' +import react from '@vitejs/plugin-react' +import { tanstackRouter } from '@tanstack/router-plugin/vite' + +export default defineConfig({ + plugins: [tanstackRouter({ target: 'react' }), react()], +}) diff --git a/e2e/react-router/issue-7457/package.json b/e2e/react-router/issue-7457/package.json index 9d9413e213..838f5173e2 100644 --- a/e2e/react-router/issue-7457/package.json +++ b/e2e/react-router/issue-7457/package.json @@ -8,16 +8,17 @@ "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", "@tanstack/react-router": "workspace:^", "@tanstack/router-plugin": "workspace:^", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", diff --git a/e2e/react-router/issue-7457/playwright.config.ts b/e2e/react-router/issue-7457/playwright.config.ts index 6ba60eaff1..a8ba116fb4 100644 --- a/e2e/react-router/issue-7457/playwright.config.ts +++ b/e2e/react-router/issue-7457/playwright.config.ts @@ -1,21 +1,18 @@ 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({ testDir: './tests', workers: 1, reporter: [['line']], - use: { - baseURL, - }, + use: { baseURL }, webServer: { - command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, - url: baseURL, - reuseExistingServer: !process.env.CI, + command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, + wait: appServerReady, + reuseExistingServer: false, stdout: 'pipe', }, projects: [ diff --git a/e2e/react-router/issue-7457/src/main.tsx b/e2e/react-router/issue-7457/src/main.tsx index ccf8ec77b2..1b6805edc0 100644 --- a/e2e/react-router/issue-7457/src/main.tsx +++ b/e2e/react-router/issue-7457/src/main.tsx @@ -1,10 +1,13 @@ -import { StrictMode } from 'react' +import { StrictMode, useEffect } from 'react' import { createRoot } from 'react-dom/client' +import { QueryClient } from '@tanstack/react-query' import { RouterProvider, createRouter } from '@tanstack/react-router' import { routeTree } from './routeTree.gen' +const queryClient = new QueryClient() const router = createRouter({ routeTree, + context: { queryClient }, defaultPendingComponent: DefaultPendingComponent, defaultPreloadStaleTime: 0, }) @@ -16,8 +19,9 @@ declare module '@tanstack/react-router' { } function DefaultPendingComponent() { - ;(globalThis as any).__pendingSeen = true - + useEffect(() => { + ;(globalThis as any).__pendingSeen = true + }, []) return
loading
} 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/issue-7457/src/routes/__root.tsx b/e2e/react-router/issue-7457/src/routes/__root.tsx index d3dced6736..988ba76263 100644 --- a/e2e/react-router/issue-7457/src/routes/__root.tsx +++ b/e2e/react-router/issue-7457/src/routes/__root.tsx @@ -1,8 +1,17 @@ -import { Outlet, createRootRoute } from '@tanstack/react-router' +import { Outlet, createRootRouteWithContext } from '@tanstack/react-router' +import type { QueryClient } from '@tanstack/react-query' -export const Route = createRootRoute({ - beforeLoad: async () => { - await new Promise((resolve) => setTimeout(resolve, 1500)) +export const Route = createRootRouteWithContext<{ + queryClient: QueryClient +}>()({ + beforeLoad: async ({ context }) => { + await context.queryClient.ensureQueryData({ + queryKey: ['issue-7457-root'], + queryFn: async () => { + await new Promise((resolve) => setTimeout(resolve, 1_500)) + return true + }, + }) }, component: RootComponent, }) diff --git a/e2e/react-router/issue-7457/src/routes/another.tsx b/e2e/react-router/issue-7457/src/routes/another.tsx index 2274ee634b..6b6caa55b3 100644 --- a/e2e/react-router/issue-7457/src/routes/another.tsx +++ b/e2e/react-router/issue-7457/src/routes/another.tsx @@ -1,9 +1,5 @@ import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/another')({ - component: RouteComponent, + component: () =>
Hello "/another"!
, }) - -function RouteComponent() { - return
Hello "/another"!
-} diff --git a/e2e/react-router/issue-7457/src/routes/index.tsx b/e2e/react-router/issue-7457/src/routes/index.tsx index 91f9a1c4eb..daaae2aeed 100644 --- a/e2e/react-router/issue-7457/src/routes/index.tsx +++ b/e2e/react-router/issue-7457/src/routes/index.tsx @@ -2,14 +2,7 @@ import { createFileRoute, redirect } from '@tanstack/react-router' export const Route = createFileRoute('/')({ beforeLoad: () => { - throw redirect({ - to: '/another', - replace: true, - }) + throw redirect({ to: '/another', replace: true }) }, - component: RouteComponent, + component: () =>
You should never see this!
, }) - -function RouteComponent() { - return
You should never see this!
-} diff --git a/e2e/react-router/issue-7457/tests/issue-7457.repro.spec.ts b/e2e/react-router/issue-7457/tests/issue-7457.repro.spec.ts index fd1c582bcf..8b20fac1eb 100644 --- a/e2e/react-router/issue-7457/tests/issue-7457.repro.spec.ts +++ b/e2e/react-router/issue-7457/tests/issue-7457.repro.spec.ts @@ -1,14 +1,13 @@ import { expect, test } from '@playwright/test' -test('initial child beforeLoad redirect after async root beforeLoad does not blank (https://github.com/TanStack/router/issues/7457)', async ({ +test('#7457: initial child redirect after async root beforeLoad does not blank', async ({ page, }) => { const pageErrors: Array = [] const consoleErrors: Array = [] - - page.on('pageerror', (error) => { - pageErrors.push(error.message || String(error)) - }) + page.on('pageerror', (error) => + pageErrors.push(error.message || String(error)), + ) page.on('console', (message) => { if (message.type() === 'error') { consoleErrors.push(message.text()) @@ -18,7 +17,15 @@ test('initial child beforeLoad redirect after async root beforeLoad does not bla await page.goto('/') await expect(page).toHaveURL(/\/another$/) - await expect(page.getByText('Hello "/another"!')).toBeVisible() + const target = page.getByText('Hello "/another"!') + await expect + .poll(async () => ({ + targetCount: await target.count(), + pageErrors: [...pageErrors], + consoleErrors: [...consoleErrors], + })) + .toEqual({ targetCount: 1, pageErrors: [], consoleErrors: [] }) + await expect(target).toBeVisible() await expect .poll(() => page.evaluate(() => (globalThis as any).__pendingSeen)) .toBe(true) diff --git a/e2e/react-router/js-only-file-based/package.json b/e2e/react-router/js-only-file-based/package.json index 6505c4a1e4..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,11 +16,11 @@ "@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": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@tanstack/router-plugin": "workspace:^", "@types/react": "^19.0.8", 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 033a1bb5fe..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:^", @@ -14,7 +14,7 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", 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 74659b51e1..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.50.1", - "@rsbuild/core": "^2.0.11", + "@playwright/test": "^1.61.0", + "@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 a7b9eb58d4..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.50.1", - "@rsbuild/core": "^2.0.11", + "@playwright/test": "^1.61.0", + "@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 215de36a70..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,16 +20,26 @@ "@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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@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" + }, + "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 f72d2d06ab..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,7 +1,23 @@ -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' +type ScrollPaintTestState = { + sourceFrameScrollYs: Array + sourceWasReset: boolean + destinationMounted: boolean + destinationCommitScrollY: number | null + destinationFrameScrollYs: Array + cleanup: () => void +} + +declare global { + interface Window { + __scrollPaintTestState?: ScrollPaintTestState + } +} + test('Smoke - Renders home', async ({ page }) => { await page.goto(toRuntimePath('/')) await expect( @@ -9,6 +25,175 @@ test('Smoke - Renders home', async ({ page }) => { ).toBeVisible() }) +test('PUSH resets scroll before the destination can render a frame (#7815)', async ({ + page, +}) => { + await page.goto(toRuntimePath('/issue-7040-source')) + await expect(page.getByTestId('issue-7040-source-top')).toBeVisible() + + const sourceScrollY = await page.evaluate(async () => { + window.scrollTo(0, 500) + await new Promise((resolve) => requestAnimationFrame(() => resolve())) + return window.scrollY + }) + + expect(sourceScrollY).toBeGreaterThan(0) + + await page.evaluate((expectedSourceScrollY) => { + const root = document.querySelector('#app') + if (!root) { + throw new Error('App root not found') + } + + const geometry = document.createElement('div') + geometry.setAttribute('aria-hidden', 'true') + geometry.style.height = `${window.innerHeight + expectedSourceScrollY + 100}px` + geometry.style.pointerEvents = 'none' + geometry.style.width = '1px' + document.body.append(geometry) + + const state: ScrollPaintTestState = { + sourceFrameScrollYs: [], + sourceWasReset: false, + destinationMounted: false, + destinationCommitScrollY: null, + destinationFrameScrollYs: [], + cleanup: () => {}, + } + + const getDestinationHeading = () => + Array.from(document.querySelectorAll('h3')).find( + (heading) => heading.textContent === 'normal-page', + ) + + const commitObserver = new MutationObserver(() => { + const destinationHeading = getDestinationHeading() + + if (!destinationHeading) { + return + } + + commitObserver.disconnect() + state.destinationMounted = true + state.destinationCommitScrollY = window.scrollY + }) + + commitObserver.observe(root, { childList: true, subtree: true }) + + const handleScroll = () => { + if ( + document.querySelector('[data-testid="issue-7040-source-top"]') && + Math.abs(window.scrollY - expectedSourceScrollY) > 1 + ) { + state.sourceWasReset = true + } + } + window.addEventListener('scroll', handleScroll, { passive: true }) + + const originalScrollTo = window.scrollTo + window.scrollTo = ((...args: Array) => { + const requestedTop = + typeof args[0] === 'number' + ? args[1] + : typeof args[0] === 'object' && args[0] !== null + ? (args[0] as ScrollToOptions).top + : undefined + if ( + typeof requestedTop === 'number' && + Math.abs(requestedTop - expectedSourceScrollY) > 1 && + document.querySelector('[data-testid="issue-7040-source-top"]') + ) { + state.sourceWasReset = true + } + Reflect.apply(originalScrollTo, window, args) + }) as typeof window.scrollTo + + let animationFrameId = 0 + const recordFrame = () => { + if (getDestinationHeading()) { + state.destinationFrameScrollYs.push(window.scrollY) + } else if ( + document.querySelector('[data-testid="issue-7040-source-top"]') + ) { + state.sourceFrameScrollYs.push(window.scrollY) + } + animationFrameId = requestAnimationFrame(recordFrame) + } + animationFrameId = requestAnimationFrame(recordFrame) + + state.cleanup = () => { + commitObserver.disconnect() + cancelAnimationFrame(animationFrameId) + window.removeEventListener('scroll', handleScroll) + window.scrollTo = originalScrollTo + geometry.remove() + delete window.__scrollPaintTestState + } + window.__scrollPaintTestState = state + }, sourceScrollY) + + await page.evaluate( + () => + new Promise((resolve) => { + requestAnimationFrame(() => resolve()) + }), + ) + expect(await page.evaluate(() => window.scrollY)).toBe(sourceScrollY) + + await page + .getByRole('link', { name: 'Head-/normal-page' }) + .dispatchEvent('click') + + await page.waitForFunction(() => { + const state = window.__scrollPaintTestState + if (!state?.destinationMounted) { + return false + } + + const lastFrames = state.destinationFrameScrollYs.slice(-2) + return ( + lastFrames.length === 2 && + lastFrames.every((scrollY) => Math.abs(scrollY) <= 1) + ) + }) + + const observation = await page.evaluate(() => { + const state = window.__scrollPaintTestState + if (!state) { + throw new Error('Scroll paint observer not found') + } + + return { + sourceFrameScrollYs: state.sourceFrameScrollYs, + sourceWasReset: state.sourceWasReset, + destinationCommitScrollY: state.destinationCommitScrollY, + destinationFrameScrollYs: state.destinationFrameScrollYs, + destinationMaxScrollY: + document.documentElement.scrollHeight - window.innerHeight, + finalScrollY: window.scrollY, + } + }) + + expect(observation.sourceFrameScrollYs.length).toBeGreaterThan(0) + expect( + observation.sourceFrameScrollYs.every( + (scrollY) => Math.abs(scrollY - sourceScrollY) <= 1, + ), + ).toBe(true) + expect(observation.sourceWasReset).toBe(false) + expect(observation.destinationMaxScrollY).toBeGreaterThanOrEqual( + sourceScrollY, + ) + expect(observation.finalScrollY).toBe(0) + expect(observation.destinationFrameScrollYs.length).toBeGreaterThanOrEqual(2) + expect( + observation.destinationFrameScrollYs.every( + (scrollY) => Math.abs(scrollY) <= 1, + ), + `Destination paint opportunities: ${observation.destinationFrameScrollYs.join(', ')}, commit: ${observation.destinationCommitScrollY}, final: ${observation.finalScrollY}`, + ).toBe(true) +}) + test('restores the prior scroll position after browser back then forward', async ({ page, }) => { 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 d97446da9f..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,11 +19,11 @@ "@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": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", 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 1c675b7258..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,17 +17,18 @@ "@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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@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", - "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 4475cf5adf..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,13 +19,14 @@ "@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": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", @@ -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 4d90b4124e..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:^", @@ -21,7 +21,7 @@ }, "devDependencies": { "@cloudflare/vite-plugin": "^1.29.0", - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", @@ -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 242636c63f..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,21 +20,22 @@ "@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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tailwindcss/vite": "^4.2.2", "@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", + "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 37a3f4a0e2..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.50.1", - "@rsbuild/core": "^2.0.11", + "@playwright/test": "^1.61.0", + "@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 dbd1d7a754..b6603dd01d 100644 --- a/e2e/react-start/basic/src/routeTree.gen.ts +++ b/e2e/react-start/basic/src/routeTree.gen.ts @@ -9,102 +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 HydrationCappedAssetsRouteRouteImport } from './routes/hydration-capped-assets/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 HydrationCappedAssetsChildRouteImport } from './routes/hydration-capped-assets/child' -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 = @@ -113,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({ @@ -162,51 +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 HydrationCappedAssetsRouteRoute = - HydrationCappedAssetsRouteRouteImport.update({ - id: '/hydration-capped-assets', - path: '/hydration-capped-assets', - 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({ @@ -214,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 = @@ -302,31 +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 HydrationCappedAssetsChildRoute = - HydrationCappedAssetsChildRouteImport.update({ - id: '/child', - path: '/child', - getParentRoute: () => HydrationCappedAssetsRouteRoute, - } 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({ @@ -334,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({ @@ -356,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 = @@ -384,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', @@ -449,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: '/', @@ -462,13 +484,15 @@ const NotFoundDeepBCDRoute = NotFoundDeepBCDRouteImport.update({ export interface FileRoutesByFullPath { '/': typeof IndexRoute - '/hydration-capped-assets': typeof HydrationCappedAssetsRouteRouteWithChildren '/not-found': typeof NotFoundRouteRouteWithChildren '/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 @@ -483,7 +507,8 @@ export interface FileRoutesByFullPath { '/not-found/parent-boundary': typeof NotFoundParentBoundaryRouteRouteWithChildren '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren - '/hydration-capped-assets/child': typeof HydrationCappedAssetsChildRoute + '/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 @@ -514,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 @@ -534,11 +560,13 @@ export interface FileRoutesByFullPath { } export interface FileRoutesByTo { '/': typeof IndexRoute - '/hydration-capped-assets': typeof HydrationCappedAssetsRouteRouteWithChildren '/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 @@ -548,7 +576,8 @@ export interface FileRoutesByTo { '/type-only-reexport': typeof TypeOnlyReexportRoute '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren - '/hydration-capped-assets/child': typeof HydrationCappedAssetsChildRoute + '/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 @@ -578,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 @@ -598,14 +628,16 @@ export interface FileRoutesByTo { export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute - '/hydration-capped-assets': typeof HydrationCappedAssetsRouteRouteWithChildren '/not-found': typeof NotFoundRouteRouteWithChildren '/search-params': typeof SearchParamsRouteRouteWithChildren '/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 @@ -621,7 +653,8 @@ export interface FileRoutesById { '/specialChars/malformed': typeof SpecialCharsMalformedRouteRouteWithChildren '/_layout/_layout-2': typeof LayoutLayout2RouteWithChildren '/api/users': typeof ApiUsersRouteWithChildren - '/hydration-capped-assets/child': typeof HydrationCappedAssetsChildRoute + '/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 @@ -652,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 @@ -674,13 +708,15 @@ export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath fullPaths: | '/' - | '/hydration-capped-assets' | '/not-found' | '/search-params' | '/specialChars' | '/async-scripts' + | '/auth-docs' | '/client-only' | '/deferred' + | '/execution-local' + | '/execution-rpc' | '/inline-scripts' | '/links' | '/plain-ts-type-assertion' @@ -695,7 +731,8 @@ export interface FileRouteTypes { | '/not-found/parent-boundary' | '/specialChars/malformed' | '/api/users' - | '/hydration-capped-assets/child' + | '/auth-docs/private' + | '/issue-6221/dashboard' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' | '/not-found/via-beforeLoad-target-root' @@ -726,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' @@ -746,11 +784,13 @@ export interface FileRouteTypes { fileRoutesByTo: FileRoutesByTo to: | '/' - | '/hydration-capped-assets' | '/specialChars' | '/async-scripts' + | '/auth-docs' | '/client-only' | '/deferred' + | '/execution-local' + | '/execution-rpc' | '/inline-scripts' | '/links' | '/plain-ts-type-assertion' @@ -760,7 +800,8 @@ export interface FileRouteTypes { | '/type-only-reexport' | '/specialChars/malformed' | '/api/users' - | '/hydration-capped-assets/child' + | '/auth-docs/private' + | '/issue-6221/dashboard' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' | '/not-found/via-beforeLoad-target-root' @@ -790,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' @@ -809,14 +851,16 @@ export interface FileRouteTypes { id: | '__root__' | '/' - | '/hydration-capped-assets' | '/not-found' | '/search-params' | '/specialChars' | '/_layout' | '/async-scripts' + | '/auth-docs' | '/client-only' | '/deferred' + | '/execution-local' + | '/execution-rpc' | '/inline-scripts' | '/links' | '/plain-ts-type-assertion' @@ -832,7 +876,8 @@ export interface FileRouteTypes { | '/specialChars/malformed' | '/_layout/_layout-2' | '/api/users' - | '/hydration-capped-assets/child' + | '/auth-docs/private' + | '/issue-6221/dashboard' | '/multi-cookie-redirect/target' | '/not-found/via-beforeLoad' | '/not-found/via-beforeLoad-target-root' @@ -863,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' @@ -884,14 +930,16 @@ export interface FileRouteTypes { } export interface RootRouteChildren { IndexRoute: typeof IndexRoute - HydrationCappedAssetsRouteRoute: typeof HydrationCappedAssetsRouteRouteWithChildren NotFoundRouteRoute: typeof NotFoundRouteRouteWithChildren SearchParamsRouteRoute: typeof SearchParamsRouteRouteWithChildren 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 @@ -903,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': { @@ -1011,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': { @@ -1032,214 +1040,74 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof NotFoundRouteRouteImport parentRoute: typeof rootRouteImport } - '/hydration-capped-assets': { - id: '/hydration-capped-assets' - path: '/hydration-capped-assets' - fullPath: '/hydration-capped-assets' - preLoaderRoute: typeof HydrationCappedAssetsRouteRouteImport + '/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 } - '/': { - 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 + '/primitive-beforeload-error': { + id: '/primitive-beforeload-error' + path: '/primitive-beforeload-error' + fullPath: '/primitive-beforeload-error' + preLoaderRoute: typeof PrimitiveBeforeloadErrorRouteImport 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 + '/raw-stream': { + id: '/raw-stream' + path: '/raw-stream' + fullPath: '/raw-stream' + preLoaderRoute: typeof RawStreamRouteImport 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 + '/scripts': { + id: '/scripts' + path: '/scripts' + fullPath: '/scripts' + preLoaderRoute: typeof ScriptsRouteImport 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 + '/search-params': { + id: '/search-params' + path: '/search-params' + fullPath: '/search-params' + preLoaderRoute: typeof SearchParamsRouteRouteImport parentRoute: typeof rootRouteImport } - '/hydration-capped-assets/child': { - id: '/hydration-capped-assets/child' - path: '/child' - fullPath: '/hydration-capped-assets/child' - preLoaderRoute: typeof HydrationCappedAssetsChildRouteImport - parentRoute: typeof HydrationCappedAssetsRouteRoute + '/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 + } + '/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': { @@ -1249,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': { @@ -1270,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/' @@ -1291,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': { @@ -1319,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' @@ -1403,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: '/' @@ -1420,20 +1498,6 @@ declare module '@tanstack/react-router' { } } -interface HydrationCappedAssetsRouteRouteChildren { - HydrationCappedAssetsChildRoute: typeof HydrationCappedAssetsChildRoute -} - -const HydrationCappedAssetsRouteRouteChildren: HydrationCappedAssetsRouteRouteChildren = - { - HydrationCappedAssetsChildRoute: HydrationCappedAssetsChildRoute, - } - -const HydrationCappedAssetsRouteRouteWithChildren = - HydrationCappedAssetsRouteRoute._addFileChildren( - HydrationCappedAssetsRouteRouteChildren, - ) - interface NotFoundDeepBCRouteRouteChildren { NotFoundDeepBCDRoute: typeof NotFoundDeepBCDRoute } @@ -1585,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 @@ -1685,14 +1761,16 @@ const FooBarQuxHereRouteWithChildren = FooBarQuxHereRoute._addFileChildren( const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, - HydrationCappedAssetsRouteRoute: HydrationCappedAssetsRouteRouteWithChildren, NotFoundRouteRoute: NotFoundRouteRouteWithChildren, SearchParamsRouteRoute: SearchParamsRouteRouteWithChildren, SpecialCharsRouteRoute: SpecialCharsRouteRouteWithChildren, LayoutRoute: LayoutRouteWithChildren, AsyncScriptsRoute: AsyncScriptsRoute, + AuthDocsRoute: AuthDocsRouteWithChildren, ClientOnlyRoute: ClientOnlyRoute, DeferredRoute: DeferredRoute, + ExecutionLocalRoute: ExecutionLocalRoute, + ExecutionRpcRoute: ExecutionRpcRoute, InlineScriptsRoute: InlineScriptsRoute, LinksRoute: LinksRoute, PlainTsTypeAssertionRoute: PlainTsTypeAssertionRoute, @@ -1704,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/hydration-capped-assets/child.tsx b/e2e/react-start/basic/src/routes/hydration-capped-assets/child.tsx deleted file mode 100644 index c18083a45d..0000000000 --- a/e2e/react-start/basic/src/routes/hydration-capped-assets/child.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/hydration-capped-assets/child')({ - loader: () => ({ - title: 'child loader data', - }), - head: ({ loaderData }) => ({ - meta: [ - { - name: 'issue-7-child-head', - content: loaderData?.title ?? 'missing-loader-data', - }, - ], - }), - scripts: ({ loaderData }) => [ - { - children: `window.__ISSUE_7_CHILD_SCRIPT = ${JSON.stringify( - loaderData?.title ?? 'missing-loader-data', - )}`, - }, - ], - component: () => ( -
Child route
- ), -}) diff --git a/e2e/react-start/basic/src/routes/hydration-capped-assets/route.tsx b/e2e/react-start/basic/src/routes/hydration-capped-assets/route.tsx deleted file mode 100644 index 0b75775bc0..0000000000 --- a/e2e/react-start/basic/src/routes/hydration-capped-assets/route.tsx +++ /dev/null @@ -1,11 +0,0 @@ -import { Outlet, createFileRoute, notFound } from '@tanstack/react-router' - -export const Route = createFileRoute('/hydration-capped-assets')({ - beforeLoad: () => { - throw notFound() - }, - notFoundComponent: () => ( -
Parent not found
- ), - component: () => , -}) 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/routes/posts.tsx b/e2e/react-start/basic/src/routes/posts.tsx index 0f69c18341..22fb7e60a8 100644 --- a/e2e/react-start/basic/src/routes/posts.tsx +++ b/e2e/react-start/basic/src/routes/posts.tsx @@ -1,3 +1,4 @@ +import { useState } from 'react' import { Link, Outlet, createFileRoute } from '@tanstack/react-router' import { fetchPosts } from '~/utils/posts' @@ -16,9 +17,16 @@ export const Route = createFileRoute('/posts')({ function PostsComponent() { const posts = Route.useLoaderData() + const [hydrationCount, setHydrationCount] = useState(0) return (
+
    {[...posts, { id: 'i-do-not-exist', title: 'Non-existent Post' }].map( (post) => { diff --git a/e2e/react-start/basic/src/routes/specialChars/search.tsx b/e2e/react-start/basic/src/routes/specialChars/search.tsx index 9e4b42e888..5840d425ab 100644 --- a/e2e/react-start/basic/src/routes/specialChars/search.tsx +++ b/e2e/react-start/basic/src/routes/specialChars/search.tsx @@ -7,6 +7,9 @@ export const Route = createFileRoute('/specialChars/search')({ validateSearch: z.object({ searchParam: z.string(), }), + beforeLoad: () => ({ + beforeLoadOn: isBrowser ? 'client' : 'server', + }), loader: async () => { console.log(`[loader] Running on ${isBrowser ? 'client' : 'server'}`) return { @@ -18,11 +21,15 @@ export const Route = createFileRoute('/specialChars/search')({ function RouteComponent() { const search = Route.useSearch() + const { beforeLoadOn } = Route.useRouteContext() const { loadedOn } = Route.useLoaderData() return (
    Hello "/specialChars/search"! +
    + Before load on: {beforeLoadOn} +
    Loaded on: {loadedOn}
    {search.searchParam}
    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/hydration-capped-assets.spec.ts b/e2e/react-start/basic/tests/hydration-capped-assets.spec.ts deleted file mode 100644 index fa40b16348..0000000000 --- a/e2e/react-start/basic/tests/hydration-capped-assets.spec.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' -import { isPrerender } from './utils/isPrerender' -import { isSpaMode } from './utils/isSpaMode' - -/** - * Issue 7: on a direct SSR hard load, the server can intentionally cap the - * committed match list at a parent notFound/error boundary. Hydration should not - * project head/scripts for the child route that was omitted from the server - * match list, because those assets can be added with missing or stale loader - * data before the follow-up client load enforces the same boundary. - * - * This Playwright repro uses the real React Start app, a real browser page load, - * the real SSR response, and normal client hydration. The parent route throws - * notFound from beforeLoad, while its child route defines a meta tag and inline - * script; neither child asset should appear after loading the capped parent - * boundary response. - */ - -test.use({ - whitelistErrors: [ - 'Failed to load resource: the server responded with a status of 404', - ], -}) - -test.describe('SSR hydration capped route assets', () => { - test.skip(isSpaMode || isPrerender, 'SSR hydration repro only') - - test('does not project assets for a child route omitted by the server boundary', async ({ - page, - }) => { - await page.goto('/hydration-capped-assets/child') - await page.waitForLoadState('networkidle') - - await expect(page.getByTestId('issue-7-parent-not-found')).toBeInViewport() - await expect( - page.getByTestId('issue-7-child-route-component'), - ).not.toBeInViewport() - - await expect(page.locator('meta[name="issue-7-child-head"]')).toHaveCount(0) - expect( - await page.evaluate(() => - Boolean((window as any).__ISSUE_7_CHILD_SCRIPT), - ), - ).toBe(false) - }) -}) 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/not-found.spec.ts b/e2e/react-start/basic/tests/not-found.spec.ts index d6e91696e3..339f841b21 100644 --- a/e2e/react-start/basic/tests/not-found.spec.ts +++ b/e2e/react-start/basic/tests/not-found.spec.ts @@ -12,6 +12,24 @@ test.use({ ], }) test.describe('not-found', () => { + test('direct nested not-found hydrates its already-rendered parent route', async ({ + page, + }) => { + test.skip(isSpaMode, 'issue #5106 requires a server-rendered direct visit') + + const response = await page.goto('/posts/i-do-not-exist') + await page.waitForLoadState('networkidle') + + const serverHtml = await response?.text() + expect(serverHtml).toContain('posts-parent-hydration-counter') + expect(serverHtml).toContain('Post not found') + await expect(page.getByText('Post not found')).toBeInViewport() + const counter = page.getByTestId('posts-parent-hydration-counter') + await expect(counter).toHaveText('Parent hydration count: 0') + await counter.click() + await expect(counter).toHaveText('Parent hydration count: 1') + }) + test(`global not found`, async ({ page }) => { const response = await page.goto(`/this-page-does-not-exist/foo/bar`) diff --git a/e2e/react-start/basic/tests/open-redirect-prevention.spec.ts b/e2e/react-start/basic/tests/open-redirect-prevention.spec.ts index e497109889..bc88c33605 100644 --- a/e2e/react-start/basic/tests/open-redirect-prevention.spec.ts +++ b/e2e/react-start/basic/tests/open-redirect-prevention.spec.ts @@ -77,22 +77,14 @@ test.describe('Open redirect prevention', () => { page, baseURL, }) => { - // When control characters are stripped from paths like /%0d/evil.com/ - // the result could be //evil.com/ which is a protocol-relative URL - // Our fix collapses these to /evil.com/ to prevent external redirects - // This is already tested above, but we verify the collapsed path works - const res = await page.goto('/%0d/test-path/') + // %0d is kept encoded, so /%0d/test-path/ stays as-is and won't become //test-path/ + await page.goto('/%0d/test-path/') await page.waitForLoadState('networkidle') // Should stay on the same origin expect(page.url().startsWith(baseURL!)).toBe(true) const url = new URL(page.url()) expect(url.origin).toBe(new URL(baseURL!).origin) - // Path should be collapsed to /test-path (not //test-path/) - expect(url.pathname).toMatch(/^\/test-path\/?$/) - if (!isSpaMode) { - expect(res?.request().redirectedFrom()?.url()).not.toBe(undefined) - } }) }) 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/special-characters.spec.ts b/e2e/react-start/basic/tests/special-characters.spec.ts index e88280e2e1..188d1f10a6 100644 --- a/e2e/react-start/basic/tests/special-characters.spec.ts +++ b/e2e/react-start/basic/tests/special-characters.spec.ts @@ -64,6 +64,22 @@ test.describe('Unicode route rendering', () => { expect(param).toBe('대|') }) + + test('should not cause redirect loop for curly braces in path params', async ({ + page, + baseURL, + }) => { + // %7B/%7D (curly braces) must not trigger infinite 307 redirects + const res = await page.goto('/specialChars/%7B%7Bapp_name%7D%7D') + await page.waitForLoadState('load') + + // Should not redirect — URL stays encoded + expect(page.url()).toBe(`${baseURL}/specialChars/%7B%7Bapp_name%7D%7D`) + expect(res!.status()).toBe(200) + + const param = await page.getByTestId('special-param').textContent() + expect(param).toBe('{{app_name}}') + }) }) test.describe('Special characters in search params', () => { @@ -88,11 +104,16 @@ test.describe('Unicode route rendering', () => { const loadedOn = await page .getByTestId('special-search-loaded-info') .textContent() + const beforeLoadOn = await page + .getByTestId('special-search-before-load-info') + .textContent() if (isSpaMode) { expect(loadedOn).toBe('Loaded on: client') + expect(beforeLoadOn).toBe('Before load on: client') } else { expect(loadedOn).toBe('Loaded on: server') + expect(beforeLoadOn).toBe('Before load on: server') } }) 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 2ff6a85a3a..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,11 +17,11 @@ "@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": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", @@ -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 4d3c4fd264..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:^", @@ -17,13 +17,14 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@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", - "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 a7bc5d023f..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.50.1", - "@rsbuild/core": "^2.0.11", + "@playwright/test": "^1.61.0", + "@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 1610f62a61..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:*", @@ -35,17 +40,37 @@ }, "devDependencies": { "@cloudflare/vite-plugin": "^1.29.0", - "@playwright/test": "^1.50.1", + "@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 f32c9772b9..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,10 +17,10 @@ "express": "^5.2.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "redaxios": "^0.5.1" + "redaxios": "catalog:" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/express": "^5.0.6", @@ -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 75634f79f5..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:^", @@ -20,8 +20,8 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@playwright/test": "^1.50.1", - "@rsbuild/core": "^2.0.11", + "@playwright/test": "^1.61.0", + "@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 91c5cc1281..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:*", @@ -37,16 +33,17 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-core": "workspace:*", "@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", - "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 932ab20cdc..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:^", @@ -19,7 +19,7 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@types/node-forge": "^1.3.14", @@ -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 b3a58125b9..76a5d86b1f 100644 --- a/e2e/react-start/hmr/package.json +++ b/e2e/react-start/hmr/package.json @@ -20,8 +20,8 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@playwright/test": "^1.50.1", - "@rsbuild/core": "^2.0.11", + "@playwright/test": "^1.61.0", + "@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 bfb7b5eb26..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:^", @@ -19,7 +19,7 @@ }, "devDependencies": { "@inlang/paraglide-js": "^2.4.0", - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", @@ -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 1175bd4ac0..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": { @@ -19,14 +19,29 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@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": "^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 65ad70126b..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:^", @@ -24,16 +21,17 @@ "react-tweet": "^3.3.0" }, "devDependencies": { - "@playwright/test": "^1.50.1", - "@rsbuild/core": "^2.0.11", + "@playwright/test": "^1.61.0", + "@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-6221/.gitignore b/e2e/react-start/issue-6221/.gitignore deleted file mode 100644 index 528451b60c..0000000000 --- a/e2e/react-start/issue-6221/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -dist -port*.txt -test-results diff --git a/e2e/react-start/issue-6221/playwright.config.ts b/e2e/react-start/issue-6221/playwright.config.ts deleted file mode 100644 index 2c2952c186..0000000000 --- a/e2e/react-start/issue-6221/playwright.config.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { defineConfig, devices } from '@playwright/test' -import { getTestServerPort } from '@tanstack/router-e2e-utils' -import packageJson from './package.json' with { type: 'json' } - -const PORT = await getTestServerPort(packageJson.name) -const baseURL = `http://localhost:${PORT}` - -export default defineConfig({ - testDir: './tests', - workers: 1, - reporter: [['line']], - use: { - baseURL, - }, - 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, - stdout: 'pipe', - }, - projects: [ - { - name: 'chromium', - use: { ...devices['Desktop Chrome'] }, - }, - ], -}) diff --git a/e2e/react-start/issue-6221/src/routeTree.gen.ts b/e2e/react-start/issue-6221/src/routeTree.gen.ts deleted file mode 100644 index 010acc5542..0000000000 --- a/e2e/react-start/issue-6221/src/routeTree.gen.ts +++ /dev/null @@ -1,122 +0,0 @@ -/* 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 LoginRouteImport } from './routes/login' -import { Route as DashboardRouteImport } from './routes/dashboard' -import { Route as IndexRouteImport } from './routes/index' -import { Route as ArticleIdRouteImport } from './routes/article.$id' - -const LoginRoute = LoginRouteImport.update({ - id: '/login', - path: '/login', - getParentRoute: () => rootRouteImport, -} as any) -const DashboardRoute = DashboardRouteImport.update({ - id: '/dashboard', - path: '/dashboard', - getParentRoute: () => rootRouteImport, -} as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) -const ArticleIdRoute = ArticleIdRouteImport.update({ - id: '/article/$id', - path: '/article/$id', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/dashboard': typeof DashboardRoute - '/login': typeof LoginRoute - '/article/$id': typeof ArticleIdRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/dashboard': typeof DashboardRoute - '/login': typeof LoginRoute - '/article/$id': typeof ArticleIdRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/dashboard': typeof DashboardRoute - '/login': typeof LoginRoute - '/article/$id': typeof ArticleIdRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/dashboard' | '/login' | '/article/$id' - fileRoutesByTo: FileRoutesByTo - to: '/' | '/dashboard' | '/login' | '/article/$id' - id: '__root__' | '/' | '/dashboard' | '/login' | '/article/$id' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - DashboardRoute: typeof DashboardRoute - LoginRoute: typeof LoginRoute - ArticleIdRoute: typeof ArticleIdRoute -} - -declare module '@tanstack/react-router' { - interface FileRoutesByPath { - '/login': { - id: '/login' - path: '/login' - fullPath: '/login' - preLoaderRoute: typeof LoginRouteImport - parentRoute: typeof rootRouteImport - } - '/dashboard': { - id: '/dashboard' - path: '/dashboard' - fullPath: '/dashboard' - preLoaderRoute: typeof DashboardRouteImport - parentRoute: typeof rootRouteImport - } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } - '/article/$id': { - id: '/article/$id' - path: '/article/$id' - fullPath: '/article/$id' - preLoaderRoute: typeof ArticleIdRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - DashboardRoute: DashboardRoute, - LoginRoute: LoginRoute, - ArticleIdRoute: ArticleIdRoute, -} -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-6221/src/routes/article.$id.tsx b/e2e/react-start/issue-6221/src/routes/article.$id.tsx deleted file mode 100644 index 3c1b8469e6..0000000000 --- a/e2e/react-start/issue-6221/src/routes/article.$id.tsx +++ /dev/null @@ -1,50 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' - -type ArticleData = { - title: string - body: string -} - -const loadArticle = async (id: string): Promise => { - await new Promise((resolve) => setTimeout(resolve, 100)) - - if (window.localStorage.getItem('issue-6221-auth') !== 'true') { - return null - } - - return { - title: `Article ${id} Title`, - body: `Article ${id} body`, - } -} - -export const Route = createFileRoute('/article/$id')({ - ssr: false, - loader: ({ params }) => loadArticle(params.id), - head: ({ loaderData }) => ({ - meta: [{ title: loaderData?.title ?? 'Article Not Found' }], - }), - component: Article, -}) - -function Article() { - const article = Route.useLoaderData() - - if (!article) { - return ( -
    -

    Article not found

    - - Go to login - -
    - ) - } - - return ( -
    -

    {article.title}

    -

    {article.body}

    -
    - ) -} diff --git a/e2e/react-start/issue-6221/src/routes/dashboard.tsx b/e2e/react-start/issue-6221/src/routes/dashboard.tsx deleted file mode 100644 index dc03c1f4e1..0000000000 --- a/e2e/react-start/issue-6221/src/routes/dashboard.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/dashboard')({ - head: () => ({ - meta: [{ title: 'Dashboard' }], - }), - component: Dashboard, -}) - -function Dashboard() { - return ( -
    -

    Dashboard

    -
    - ) -} diff --git a/e2e/react-start/issue-6221/src/routes/index.tsx b/e2e/react-start/issue-6221/src/routes/index.tsx deleted file mode 100644 index a8efa4c572..0000000000 --- a/e2e/react-start/issue-6221/src/routes/index.tsx +++ /dev/null @@ -1,16 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return ( -
    -

    Issue 6221

    - - Article 123 - -
    - ) -} diff --git a/e2e/react-start/issue-6221/src/routes/login.tsx b/e2e/react-start/issue-6221/src/routes/login.tsx deleted file mode 100644 index 7d07073ea4..0000000000 --- a/e2e/react-start/issue-6221/src/routes/login.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { createFileRoute, useNavigate } from '@tanstack/react-router' - -export const Route = createFileRoute('/login')({ - ssr: false, - head: () => ({ - meta: [{ title: 'Login' }], - }), - component: Login, -}) - -function Login() { - const navigate = useNavigate() - - return ( -
    -

    Login

    - -
    - ) -} diff --git a/e2e/react-start/issue-6221/tests/head.spec.ts b/e2e/react-start/issue-6221/tests/head.spec.ts deleted file mode 100644 index 679f059c01..0000000000 --- a/e2e/react-start/issue-6221/tests/head.spec.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' - -test('updates head after a stale cached loader refreshes in the background', async ({ - page, -}) => { - await page.goto('/') - await page.evaluate(() => window.localStorage.clear()) - - await page.goto('/article/123') - await expect(page.getByTestId('article-not-found')).toBeVisible() - await expect(page).toHaveTitle('Article Not Found') - - await page.getByTestId('login-link').click() - await expect(page.getByTestId('login-page')).toBeVisible() - await expect(page).toHaveTitle('Login') - - await page.getByTestId('login-button').click() - await expect(page.getByTestId('dashboard')).toBeVisible() - await expect(page).toHaveTitle('Dashboard') - - await page.goBack() - await expect(page.getByTestId('article-content')).toBeVisible() - await expect(page.getByTestId('article-title')).toHaveText( - 'Article 123 Title', - ) - - await expect(page).toHaveTitle('Article 123 Title') -}) diff --git a/e2e/react-start/issue-6221/package.json b/e2e/react-start/issue-8049/package.json similarity index 59% rename from e2e/react-start/issue-6221/package.json rename to e2e/react-start/issue-8049/package.json index c3330ecb52..be848d434c 100644 --- a/e2e/react-start/issue-6221/package.json +++ b/e2e/react-start/issue-8049/package.json @@ -1,15 +1,12 @@ { - "name": "tanstack-react-start-e2e-issue-6221", + "name": "tanstack-react-start-e2e-issue-8049", "private": true, - "sideEffects": false, "type": "module", "scripts": { + "build": "vite build && tsc --noEmit", "dev": "vite dev --port 3000", "dev:e2e": "vite dev", - "build": "vite build && tsc --noEmit", - "preview": "vite preview", - "start": "pnpm dlx 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:^", @@ -18,14 +15,11 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@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": "^0.11.9", - "typescript": "^6.0.2", "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-6221/src/routes/__root.tsx b/e2e/react-start/issue-8049/src/routes/__root.tsx similarity index 59% rename from e2e/react-start/issue-6221/src/routes/__root.tsx rename to e2e/react-start/issue-8049/src/routes/__root.tsx index 8b60be2cb9..d04f508640 100644 --- a/e2e/react-start/issue-6221/src/routes/__root.tsx +++ b/e2e/react-start/issue-8049/src/routes/__root.tsx @@ -1,36 +1,35 @@ -/// -import * as React from 'react' import { HeadContent, Link, - Outlet, 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' }, - { title: 'Issue 6221' }, ], }), shellComponent: RootDocument, - component: () => , }) -function RootDocument({ children }: { children: React.ReactNode }) { +function RootDocument({ children }: { children: ReactNode }) { return ( - + - - {children} +
    + + {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 6a22be7871..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", @@ -24,7 +24,7 @@ "zod": "^4.4.3" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", @@ -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/issue-6221/src/router.tsx b/e2e/react-start/root-document-hydration/src/router.tsx similarity index 74% rename from e2e/react-start/issue-6221/src/router.tsx rename to e2e/react-start/root-document-hydration/src/router.tsx index 191f74ee02..58f4d54e88 100644 --- a/e2e/react-start/issue-6221/src/router.tsx +++ b/e2e/react-start/root-document-hydration/src/router.tsx @@ -2,7 +2,5 @@ import { createRouter } from '@tanstack/react-router' import { routeTree } from './routeTree.gen' export function getRouter() { - return createRouter({ - routeTree, - }) + 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 40ffdd2569..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" }, @@ -40,14 +40,15 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@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": "^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 4e3deac1c7..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,17 +17,17 @@ "@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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@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 e5422cd436..a51cf9149c 100644 --- a/e2e/vue-router/basic-esbuild-file-based/package.json +++ b/e2e/vue-router/basic-esbuild-file-based/package.json @@ -7,28 +7,29 @@ "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" }, "devDependencies": { "@eslint/js": "^9.36.0", - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@typescript-eslint/eslint-plugin": "^8.44.1", "@typescript-eslint/parser": "^8.44.1", "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 b029b1ab4f..9ab7f21e82 100644 --- a/e2e/vue-router/basic-file-based-jsx/package.json +++ b/e2e/vue-router/basic-file-based-jsx/package.json @@ -8,21 +8,21 @@ "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" }, "devDependencies": { "@eslint/js": "^9.36.0", - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@typescript-eslint/eslint-plugin": "^8.44.1", "@typescript-eslint/parser": "^8.44.1", @@ -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 369a0b1fdc..e6ffa156f9 100644 --- a/e2e/vue-router/basic-file-based-sfc/package.json +++ b/e2e/vue-router/basic-file-based-sfc/package.json @@ -8,25 +8,25 @@ "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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@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 daa2519eed..f4616a5651 100644 --- a/e2e/vue-router/basic-scroll-restoration/package.json +++ b/e2e/vue-router/basic-scroll-restoration/package.json @@ -8,24 +8,24 @@ "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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@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 946addb3bf..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,17 +18,17 @@ "@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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@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 f73d3ad8b2..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,17 +18,17 @@ "@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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@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 75395b20f8..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,18 +17,18 @@ "@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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@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 be46a064c6..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,17 +16,17 @@ "@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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@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 c779a572e9..1b57dae772 100644 --- a/e2e/vue-router/basic/package.json +++ b/e2e/vue-router/basic/package.json @@ -8,22 +8,22 @@ "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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@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 14cdafcd48..f9324643ac 100644 --- a/e2e/vue-router/generator-cli-only/package.json +++ b/e2e/vue-router/generator-cli-only/package.json @@ -8,24 +8,24 @@ "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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@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 05a86b7cf1..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,12 +17,12 @@ "@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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", 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 5d8a072d87..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.50.1", - "@rsbuild/core": "^2.0.11", + "@playwright/test": "^1.61.0", + "@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 11f61237d3..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.50.1", - "@rsbuild/core": "^2.0.11", + "@playwright/test": "^1.61.0", + "@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 a7dc67fd6b..d071ee546a 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/package.json +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/package.json @@ -11,25 +11,35 @@ "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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@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 cbf6bf8499..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,16 +17,16 @@ "@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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@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 493b3e45ce..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,17 +17,17 @@ "@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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@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 d38e059360..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(() => { @@ -20,8 +21,7 @@ test.beforeEach(async ({ page }) => { // ignore } - const updateCallbackDone = Promise.resolve() - return { finished: updateCallbackDone, updateCallbackDone } + return { finished: Promise.resolve() } } }) diff --git a/e2e/vue-start/basic-auth/package.json b/e2e/vue-start/basic-auth/package.json index cb3b0cd166..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; touch .tmp/dev.db; 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,12 +19,13 @@ "@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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", @@ -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 c7e55f7937..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:^", @@ -20,15 +20,26 @@ }, "devDependencies": { "@cloudflare/vite-plugin": "^1.29.0", - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tailwindcss/vite": "^4.2.2", "@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 3189e8e867..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,21 +18,22 @@ "@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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@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 073627701a..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.50.1", - "@rsbuild/core": "^2.0.11", - "@rsbuild/plugin-babel": "^1.0.5", - "@rsbuild/plugin-vue": "^1.2.2", - "@rsbuild/plugin-vue-jsx": "^1.1.1", + "@playwright/test": "^1.61.0", + "@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 9b7d36333d..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:*", @@ -19,13 +19,14 @@ "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:*", "@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 759e13b48e..c1032ea88b 100644 --- a/e2e/vue-start/custom-basepath/package.json +++ b/e2e/vue-start/custom-basepath/package.json @@ -8,27 +8,28 @@ "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": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@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 d44bd58376..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", @@ -23,14 +23,15 @@ "zod": "^4.4.3" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@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 871200e852..025b0225be 100644 --- a/e2e/vue-start/scroll-restoration/package.json +++ b/e2e/vue-start/scroll-restoration/package.json @@ -9,28 +9,29 @@ "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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@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 217a30eb9f..0d44b648ee 100644 --- a/e2e/vue-start/selective-ssr/src/routeTree.gen.ts +++ b/e2e/vue-start/selective-ssr/src/routeTree.gen.ts @@ -9,14 +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 SsrFalsePendingMinRouteImport } from './routes/ssr-false-pending-min' -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 SsrFalsePendingMinRoute = SsrFalsePendingMinRouteImport.update({ - id: '/ssr-false-pending-min', - path: '/ssr-false-pending-min', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const PostsRoute = PostsRouteImport.update({ @@ -24,11 +23,6 @@ const PostsRoute = PostsRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', - getParentRoute: () => rootRouteImport, -} as any) const PostsPostIdRoute = PostsPostIdRouteImport.update({ id: '/$postId', path: '/$postId', @@ -38,43 +32,39 @@ const PostsPostIdRoute = PostsPostIdRouteImport.update({ export interface FileRoutesByFullPath { '/': typeof IndexRoute '/posts': typeof PostsRouteWithChildren - '/ssr-false-pending-min': typeof SsrFalsePendingMinRoute '/posts/$postId': typeof PostsPostIdRoute } export interface FileRoutesByTo { '/': typeof IndexRoute '/posts': typeof PostsRouteWithChildren - '/ssr-false-pending-min': typeof SsrFalsePendingMinRoute '/posts/$postId': typeof PostsPostIdRoute } export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute '/posts': typeof PostsRouteWithChildren - '/ssr-false-pending-min': typeof SsrFalsePendingMinRoute '/posts/$postId': typeof PostsPostIdRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/posts' | '/ssr-false-pending-min' | '/posts/$postId' + fullPaths: '/' | '/posts' | '/posts/$postId' fileRoutesByTo: FileRoutesByTo - to: '/' | '/posts' | '/ssr-false-pending-min' | '/posts/$postId' - id: '__root__' | '/' | '/posts' | '/ssr-false-pending-min' | '/posts/$postId' + to: '/' | '/posts' | '/posts/$postId' + id: '__root__' | '/' | '/posts' | '/posts/$postId' fileRoutesById: FileRoutesById } export interface RootRouteChildren { IndexRoute: typeof IndexRoute PostsRoute: typeof PostsRouteWithChildren - SsrFalsePendingMinRoute: typeof SsrFalsePendingMinRoute } declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/ssr-false-pending-min': { - id: '/ssr-false-pending-min' - path: '/ssr-false-pending-min' - fullPath: '/ssr-false-pending-min' - preLoaderRoute: typeof SsrFalsePendingMinRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/posts': { @@ -84,13 +74,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/posts/$postId': { id: '/posts/$postId' path: '/$postId' @@ -114,7 +97,6 @@ const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, PostsRoute: PostsRouteWithChildren, - SsrFalsePendingMinRoute: SsrFalsePendingMinRoute, } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) 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/selective-ssr/src/routes/ssr-false-pending-min.tsx b/e2e/vue-start/selective-ssr/src/routes/ssr-false-pending-min.tsx deleted file mode 100644 index 17bbd702ab..0000000000 --- a/e2e/vue-start/selective-ssr/src/routes/ssr-false-pending-min.tsx +++ /dev/null @@ -1,56 +0,0 @@ -import { defineComponent, onMounted, onUnmounted } from 'vue' -import { createFileRoute } from '@tanstack/vue-router' - -const pendingMinMs = 1500 - -function recordEvent(type: string) { - if (typeof window === 'undefined') { - return - } - - const global = window as any - global.__events ??= [] - global.__events.push({ type, t: performance.now() }) -} - -const Pending = defineComponent({ - setup() { - onMounted(() => { - recordEvent('pending-mounted') - }) - onUnmounted(() => { - recordEvent('pending-unmounted') - }) - - return () => ( -
    Loading SSR false route...
    - ) - }, -}) - -const Target = defineComponent({ - setup() { - onMounted(() => { - recordEvent('target-mounted') - }) - - return () => ( -
    SSR false route loaded
    - ) - }, -}) - -export const Route = createFileRoute('/ssr-false-pending-min')({ - ssr: false, - pendingMs: 0, - pendingMinMs, - pendingComponent: Pending, - loader: async () => { - recordEvent('loader-start') - await new Promise((resolve) => setTimeout(resolve, 50)) - recordEvent('loader-done') - - return { ok: true } - }, - component: Target, -}) diff --git a/e2e/vue-start/selective-ssr/tests/app.spec.ts b/e2e/vue-start/selective-ssr/tests/app.spec.ts index b14c7e028a..aea216d506 100644 --- a/e2e/vue-start/selective-ssr/tests/app.spec.ts +++ b/e2e/vue-start/selective-ssr/tests/app.spec.ts @@ -1,73 +1,8 @@ import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' -import type { Page } from '@playwright/test' const testCount = 7 -type BrowserEvent = { type: string; t: number } - -function findEvent(events: Array, type: string) { - const event = events.find((entry) => entry.type === type) - expect(event, `Expected browser event "${type}"`).toBeTruthy() - return event! -} - -function findLastEvent(events: Array, type: string) { - let event: BrowserEvent | undefined - for (let index = events.length - 1; index >= 0; index--) { - if (events[index]!.type === type) { - event = events[index] - break - } - } - expect(event, `Expected browser event "${type}"`).toBeTruthy() - return event! -} - -async function expectSsrFalsePendingMin(page: Page) { - const errors: Array = [] - - page.on('pageerror', (err) => { - errors.push(err.message) - }) - page.on('console', (msg) => { - if (msg.type() === 'error') { - errors.push(msg.text()) - } - }) - - await page.goto('/ssr-false-pending-min') - - const pending = page.getByTestId('ssr-false-pending') - const visiblePending = page.locator( - '[data-testid="ssr-false-pending"]:visible', - ) - const target = page.getByTestId('ssr-false-target') - - await expect(visiblePending).toHaveCount(1) - - await page.waitForTimeout(500) - - await expect(visiblePending).toHaveCount(1) - await expect(target).toBeHidden() - - await expect(target).toBeVisible() - await expect(pending).toHaveCount(0) - - const events = await page.evaluate>( - () => (window as any).__events ?? [], - ) - const pendingMounted = findEvent(events, 'pending-mounted') - const pendingUnmounted = findLastEvent(events, 'pending-unmounted') - const targetMounted = findEvent(events, 'target-mounted') - const loaderDone = findEvent(events, 'loader-done') - - expect(loaderDone.t - pendingMounted.t).toBeLessThan(500) - expect(pendingUnmounted.t - pendingMounted.t).toBeGreaterThanOrEqual(1400) - expect(targetMounted.t - pendingMounted.t).toBeGreaterThanOrEqual(1400) - expect(errors).toEqual([]) -} - test.describe('selective ssr', () => { test('testcount matches', async ({ page }) => { await page.goto('/') @@ -103,10 +38,4 @@ test.describe('selective ssr', () => { await expect(page.getByTestId('router-status')).toContainText('idle') }) } - - test('direct ssr false hydration keeps pending visible for pendingMinMs', async ({ - page, - }) => { - await expectSsrFalsePendingMin(page) - }) }) 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 2e84c6238e..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,13 +18,13 @@ "@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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/js-cookie": "^3.0.6", @@ -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 6e5c7cdced..6a8e1babed 100644 --- a/e2e/vue-start/server-routes/package.json +++ b/e2e/vue-start/server-routes/package.json @@ -18,13 +18,13 @@ "@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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/js-cookie": "^3.0.6", @@ -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 841aa5da85..ae682f7a9d 100644 --- a/e2e/vue-start/start-manifest/package.json +++ b/e2e/vue-start/start-manifest/package.json @@ -15,12 +15,13 @@ "vue": "^3.5.16" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@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 41b1355414..90f09ce911 100644 --- a/e2e/vue-start/virtual-routes/package.json +++ b/e2e/vue-start/virtual-routes/package.json @@ -9,29 +9,30 @@ "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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@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 8ec13f6dbc..6c30b1500f 100644 --- a/e2e/vue-start/website/package.json +++ b/e2e/vue-start/website/package.json @@ -9,27 +9,28 @@ "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" }, "devDependencies": { - "@playwright/test": "^1.50.1", + "@playwright/test": "^1.61.0", "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@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 dafac3ef01..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.18", + "@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 164e0c3b07..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.18", + "@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 afda60a9de..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.16", - "@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 bc5502b64a..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.16", - "@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 c9b60b4a41..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.18", + "@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 496bf4f428..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.16", - "@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 5e4d1c16e4..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.18", + "@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 8afb35f672..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.16", - "@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 b7df3723d4..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.16", - "@tanstack/router-plugin": "^1.168.18", + "@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 25b6c3ba79..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.16", - "@tanstack/router-plugin": "^1.168.18", + "@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 b6456f16c4..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.18", + "@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 f3b7ded6b5..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.18", + "@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 500d62838d..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.16", - "@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 ce4d0a23f9..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.16", - "@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 ae8a8cf345..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.16", - "@tanstack/router-plugin": "^1.168.18", + "@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 f52cc14be2..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.18", + "@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 a31d6bfd58..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.18", + "@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 bd7cc359ec..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.16", - "@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 40de321285..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.16", - "@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 75429bd82a..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.18", + "@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 f593f59ba2..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.16", - "@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 b0255cf627..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.16", - "@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 4817cba83b..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.18", + "@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 53d26bfa71..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.18", + "@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 2ee1c96f0d..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.16", - "@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.18", + "@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 5e16ac8b4f..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.16", - "@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.18", + "@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 19bd01d412..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.16", - "@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 25de375254..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.18", + "@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 a0ef2fabd1..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.16", - "@tanstack/router-plugin": "^1.168.18", + "@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 e6a6b51a7d..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.18", + "@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 55dfce9be7..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.16", - "@tanstack/router-plugin": "^1.168.18", + "@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 907bdc33a8..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.18", + "@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 755e90987e..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.16", - "@tanstack/router-plugin": "^1.168.18", + "@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 0f14bafacc..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.16", - "@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 f0445b6f93..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.18", + "@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 190186a6f4..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.26", + "@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 9a9f93e019..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.26", + "@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 d1402e2c53..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.26", + "@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 b512fe867d..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.26", + "@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 dcb5b81796..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-router-ssr-query": "^1.167.1", - "@tanstack/react-start": "^1.168.26", + "@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 9a2f888be5..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.26", - "@tanstack/start-static-server-functions": "^1.167.17", + "@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 72372d7806..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.26", + "@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 7b262c6bf7..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-router-ssr-query": "^1.167.1", - "@tanstack/react-start": "^1.168.26", - "@tanstack/router-plugin": "^1.168.18", + "@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 121b04bcfe..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.26", + "@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 06616b8bcd..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-router-ssr-query": "^1.167.1", - "@tanstack/react-start": "^1.168.26", + "@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 b9b113dcdb..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.26", + "@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 238ad332cf..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.26", + "@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 f26f5aa248..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.26", + "@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 b4b1fdcc18..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.26", + "@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 e77685070f..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.26", + "@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": "npm:nitro-nightly@latest", + "@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 149aed0d8e..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.26", + "@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 59aaaded53..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.26", + "@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 b555b3703e..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.26", + "@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 2de169fea6..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-router-ssr-query": "^1.167.1", - "@tanstack/react-start": "^1.168.26", + "@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/README.md b/examples/react/start-workos/README.md index d6e222c7ba..52dde9410a 100644 --- a/examples/react/start-workos/README.md +++ b/examples/react/start-workos/README.md @@ -30,7 +30,7 @@ You will need a [WorkOS account](https://dashboard.workos.com/signup). WORKOS_CLIENT_ID= WORKOS_API_KEY= WORKOS_COOKIE_PASSWORD= - WORKOS_REDIRECT_URI=http://localhost:3000/callback + WORKOS_REDIRECT_URI=http://localhost:3000/api/auth/callback ``` `WORKOS_COOKIE_PASSWORD` is the private key used to encrypt the session cookie. It has to be at least 32 characters long. You can use the [1Password generator](https://1password.com/password-generator/) or the `openssl` library to generate a strong password via the command line: ```bash diff --git a/examples/react/start-workos/package.json b/examples/react/start-workos/package.json index 4379c464b8..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/react-start": "^1.168.26", + "@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 3af69ed288..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.18", + "@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 6dee036c9e..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.16", - "@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 f849a2dc12..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.18", + "@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 bad08150a1..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.16", - "@tanstack/react-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.18", + "@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 ce1178dcc3..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.18", - "@tanstack/solid-router": "^1.170.16", - "@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 79c7b3e35b..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.18", - "@tanstack/solid-router": "^1.170.16", - "@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 7aa5a5771f..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.16", - "@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 21b0dbbb4d..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.16", - "@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 3875d710ff..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.16", - "@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.18", - "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 f644b324b0..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.16", - "@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 548e6630c7..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.16", - "@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.18", - "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 06a2d942fe..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.16", - "@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.18", - "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 df458d40c7..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.16", - "@tanstack/router-plugin": "^1.168.18", + "@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 435d2b9337..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.16", - "@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.18", + "@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 7670b540ab..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.18", - "@tanstack/solid-router": "^1.170.16", - "@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 29f03157a0..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.18", - "@tanstack/solid-router": "^1.170.16", - "@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 e63f01566d..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.16", - "@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 6b2ba6437b..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.16", - "@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 ca853c7e08..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.16", - "@tanstack/router-plugin": "^1.168.18", + "@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 8c02a9cd24..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.16", - "@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.18", - "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 3e818ed243..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.18", + "@tanstack/router-plugin": "^1.169.0", "@tanstack/solid-query": "^5.90.9", "@tanstack/solid-query-devtools": "^5.90.0", - "@tanstack/solid-router": "^1.170.16", - "@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 c078ac2bb9..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.16", - "@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 4223f4b840..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.16", - "@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 17b2ba0610..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.18", + "@tanstack/router-plugin": "^1.169.0", "@tanstack/solid-query": "^5.90.9", - "@tanstack/solid-router": "^1.170.16", - "@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 b15d437baf..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.16", - "@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 3a3d7c88e3..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.16", - "@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 8ff9be64eb..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.18", - "@tanstack/solid-router": "^1.170.16", - "@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 16fa0bcce6..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.16", - "@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.18", - "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 82e1eaec3f..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.16", - "@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.18", - "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 2a65a99a2a..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.16", - "@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.18", + "@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 310ce847a1..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.16", - "@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 d1d6bc352a..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.16", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.18", + "@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 deefbaadac..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.16", - "@tanstack/router-plugin": "^1.168.18", + "@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 9741d561b4..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.16", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.18", + "@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 6b5990d5c7..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.16", - "@tanstack/router-plugin": "^1.168.18", + "@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 50609c03ca..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.16", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.18", + "@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 ffcf38ac81..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.16", - "@tanstack/router-plugin": "^1.168.18", + "@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 482475cadf..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.16", - "@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 ebc44256b4..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.16", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/router-plugin": "^1.168.18", + "@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 20f86e46b6..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.16", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.26", + "@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 f5396a2f42..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.16", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.26", + "@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 b186dd9d6e..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.16", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.26", + "@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 302e1ca086..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.16", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.26", + "@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 923396e37a..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.16", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.26", + "@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 5fc9f4dd82..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.16", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-router-ssr-query": "^1.167.1", - "@tanstack/solid-start": "^1.168.26", + "@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 e5bb50d54a..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.16", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.26", - "@tanstack/start-static-server-functions": "^1.167.17", + "@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 49bd5d5fe9..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.16", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.26", + "@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 dc944ee3b1..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.16", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-router-ssr-query": "^1.167.1", - "@tanstack/solid-start": "^1.168.26", - "@tanstack/router-plugin": "^1.168.18", + "@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 1a787178ed..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.16", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.26", + "@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 6eaf05c9a1..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.16", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.26", + "@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 05a5e59bb6..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.16", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.26", + "@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 ccceb6045b..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.16", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.26", + "@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 6b62a70528..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.16", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.26", + "@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 5dc8d866e8..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.16", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.26", + "@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 52caa94c8f..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.16", - "@tanstack/solid-router-devtools": "^1.167.0", - "@tanstack/solid-start": "^1.168.26", + "@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 c2cd643fd7..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.18", - "@tanstack/solid-router": "^1.170.16", - "@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 d0af6cf9bb..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.16", - "@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 fa9dfaea02..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.18", - "@tanstack/solid-router": "^1.170.16", - "@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 36354edaec..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.18", - "@tanstack/vue-router": "^1.170.15", - "@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 9a46ecc019..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.18", - "@tanstack/vue-router": "^1.170.15", - "@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 bfbd3f00bb..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.15", - "@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 f901a4be58..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 --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 0e2cdc0de4..7e1e2f1a62 100644 --- a/packages/react-router/CHANGELOG.md +++ b/packages/react-router/CHANGELOG.md @@ -1,5 +1,371 @@ # @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 + +- Updated dependencies [[`e2dd204`](https://github.com/TanStack/router/commit/e2dd2049cb42eb219d3b447b8605066d19d9c1fa)]: + - @tanstack/router-core@1.171.15 + +## 1.170.17 + +### Patch Changes + +- Updated dependencies [[`9809a06`](https://github.com/TanStack/router/commit/9809a0619d4ed3fe8c2a393af5b9eca4b6c7695b)]: + - @tanstack/router-core@1.171.14 + ## 1.170.16 ### 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 ff94646687..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.16", + "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,27 +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 ( -