diff --git a/.changeset/history-forward-entries.md b/.changeset/history-forward-entries.md new file mode 100644 index 0000000000..a4517e4c6a --- /dev/null +++ b/.changeset/history-forward-entries.md @@ -0,0 +1,5 @@ +--- +'@tanstack/history': patch +--- + +Avoid temporary arrays when replacing forward memory-history entries. diff --git a/.changeset/rsbuild-manifest-module-chunks-once.md b/.changeset/rsbuild-manifest-module-chunks-once.md deleted file mode 100644 index 02febd9d84..0000000000 --- a/.changeset/rsbuild-manifest-module-chunks-once.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@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 deleted file mode 100644 index 04e8e29928..0000000000 --- a/.changeset/rsbuild-manifest-own-chunks.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@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 deleted file mode 100644 index a84a054fbd..0000000000 --- a/.changeset/rsbuild-rule-use-falsy-loaders.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@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 deleted file mode 100644 index 01a0c5ee6e..0000000000 --- a/.changeset/rsbuild-virtual-modules-build.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@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 deleted file mode 100644 index 427043a712..0000000000 --- a/.changeset/rsbuild-virtual-modules-root.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@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 deleted file mode 100644 index 9c828f13b3..0000000000 --- a/.changeset/rsc-security-floor.md +++ /dev/null @@ -1,8 +0,0 @@ ---- -'@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/sad-pans-design.md b/.changeset/sad-pans-design.md new file mode 100644 index 0000000000..3976f1cc28 --- /dev/null +++ b/.changeset/sad-pans-design.md @@ -0,0 +1,7 @@ +--- +'@tanstack/start-server-core': patch +'@tanstack/router-core': patch +'@tanstack/history': patch +--- + +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. diff --git a/.changeset/start-server-fn-custom-id-check.md b/.changeset/start-server-fn-custom-id-check.md deleted file mode 100644 index 384f0ade06..0000000000 --- a/.changeset/start-server-fn-custom-id-check.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -'@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 deleted file mode 100644 index d4e8221c59..0000000000 --- a/.changeset/start-vite-root-library-discovery.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@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/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 9dd0def7bd..a33150af03 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -4,14 +4,6 @@ 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 index a5ef10f1ff..1245a0a0fd 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -12,11 +12,3 @@ - [ ] 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 6fd5aa1c86..01be1ce5c2 100644 --- a/.github/renovate.json +++ b/.github/renovate.json @@ -21,6 +21,7 @@ "@types/node", "@types/react", "@types/react-dom", + "h3", "node", "react", "react-dom", diff --git a/.github/workflows/bundle-size.yml b/.github/workflows/bundle-size.yml index 51ffa28e4c..5d628ff768 100644 --- a/.github/workflows/bundle-size.yml +++ b/.github/workflows/bundle-size.yml @@ -9,18 +9,12 @@ on: - '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: @@ -109,8 +103,6 @@ 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: | @@ -120,7 +112,7 @@ jobs: benchmark-main: name: Publish Bundle Size History - if: (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && github.ref == 'refs/heads/main' && github.repository_owner == 'TanStack' + if: github.event_name == 'push' && github.ref == 'refs/heads/main' && github.repository_owner == 'TanStack' runs-on: ubuntu-latest permissions: contents: write diff --git a/.github/workflows/benchmarks.yml b/.github/workflows/client-nav-benchmarks.yml similarity index 91% rename from .github/workflows/benchmarks.yml rename to .github/workflows/client-nav-benchmarks.yml index bbc3a1fa24..7eedc222ae 100644 --- a/.github/workflows/benchmarks.yml +++ b/.github/workflows/client-nav-benchmarks.yml @@ -18,15 +18,11 @@ on: pull_request: paths: - 'packages/**' - - '!packages/**/tests/**' - - '!packages/**/__tests__/**' - - '!packages/**/*.test.*' - 'benchmarks/**' - - '.nvmrc' workflow_dispatch: concurrency: - group: benchmarks-${{ github.ref }} + group: client-nav-benchmarks-${{ github.ref }} cancel-in-progress: false queue: single @@ -81,7 +77,7 @@ jobs: @benchmarks/${{ matrix.benchmark }}:build:${{ matrix.framework }} - name: Run ${{ matrix.benchmark }}:${{ matrix.framework }} CodSpeed benchmark - uses: CodSpeedHQ/action@373d6868929f444bc08d901fd0eb0ad52a8875ea # v5.2.1 + uses: CodSpeedHQ/action@4296e51e7041e24dadb86d1d6e8b9320d223dbe8 # v5.0.3 timeout-minutes: 20 with: mode: ${{ matrix.mode }} diff --git a/.github/workflows/compiler-platforms.yml b/.github/workflows/compiler-platforms.yml deleted file mode 100644 index ad70e39bb6..0000000000 --- a/.github/workflows/compiler-platforms.yml +++ /dev/null @@ -1,101 +0,0 @@ -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 fde1100409..d8c779b170 100644 --- a/.github/workflows/labeler.yml +++ b/.github/workflows/labeler.yml @@ -9,8 +9,6 @@ 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 ae19b4f0d2..71026a0a92 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -10,13 +10,6 @@ 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 @@ -33,8 +26,8 @@ jobs: with: fetch-depth: 0 persist-credentials: false - - name: Start Nx Workers - run: npx nx-cloud start-workers + - name: Start Nx Agents + run: npx nx-cloud start-ci-run --distribute-on=".nx/workflows/dynamic-changesets.yaml" - name: Setup Tools uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3 # main - name: Get base and head commits for `nx affected` @@ -43,9 +36,9 @@ jobs: main-branch-name: main - name: Run Checks run: pnpm run test:pr --parallel=3 - - name: Stop Nx Workers + - name: Stop Nx Agents if: ${{ always() }} - run: npx nx-cloud stop-all-workers + run: npx nx-cloud stop-all-agents preview: name: Preview runs-on: ubuntu-latest diff --git a/.nvmrc b/.nvmrc index 63f87c20ef..b404027604 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -26.12.1 +24.8.0 diff --git a/.nx/ci-config.yaml b/.nx/ci-config.yaml deleted file mode 100644 index 2f0783feb4..0000000000 --- a/.nx/ci-config.yaml +++ /dev/null @@ -1,5 +0,0 @@ -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 new file mode 100644 index 0000000000..39d858d5b2 --- /dev/null +++ b/.nx/workflows/dynamic-changesets.yaml @@ -0,0 +1,4 @@ +distribute-on: + small-changeset: 4 linux-medium-js + medium-changeset: 8 linux-medium-js + large-changeset: 16 linux-medium-js diff --git a/.nx/workflows/sandboxing-config.yaml b/.nx/workflows/sandboxing-config.yaml new file mode 100644 index 0000000000..4fa2634bc3 --- /dev/null +++ b/.nx/workflows/sandboxing-config.yaml @@ -0,0 +1,9 @@ +exclude-reads: + - e2e/.gitignore + - '**/src/routeTree.gen.ts' +exclude-writes: + - '**/src/routeTree.gen.ts' +task-exclusions: + - target: test:build + exclude-reads: + - LICENSE diff --git a/.nx/workflows/ultracache-config.yaml b/.nx/workflows/ultracache-config.yaml deleted file mode 100644 index b3ed223621..0000000000 --- a/.nx/workflows/ultracache-config.yaml +++ /dev/null @@ -1,124 +0,0 @@ -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/AGENTS.md b/AGENTS.md index f47b5103e1..3368f3f100 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,41 +1,181 @@ # AGENTS.md -## Scope +Read and follow [`CONTRIBUTING.md`](./CONTRIBUTING.md) before analyzing or +changing this repository. Its contribution and pull request requirements apply +to AI-assisted work. -- 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`. +## Project overview -## Work and validation +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: -- 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. +- **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 -```sh -CI=1 NX_DAEMON=false pnpm nx run-many -p -t --skipRemoteCache -``` +## Setup commands -- 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`. +- 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` -## Runtime rules +## Code style -- 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. +- 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`. -## Performance and final bundle pass +## Dev environment tips -- 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. +- 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. + +## 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 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4b6e808af1..ce76a5ba5d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -142,14 +142,6 @@ pnpm dev ## AI-assisted contributions - - 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. diff --git a/_artifacts/domain_map.yaml b/_artifacts/domain_map.yaml index 0b2672f0c6..4b5d6f8386 100644 --- a/_artifacts/domain_map.yaml +++ b/_artifacts/domain_map.yaml @@ -147,15 +147,13 @@ skills: context types to not flow into loader. wrong_pattern: | createFileRoute('/posts')({ - loader: ({ context }) => - context.queryClient.query({ ...postsQuery, staleTime: 'static' }), + loader: ({ context }) => context.queryClient.ensureQueryData(postsQuery), beforeLoad: ({ context }) => ({ queryClient: context.queryClient }), }) correct_pattern: | createFileRoute('/posts')({ beforeLoad: ({ context }) => ({ queryClient: context.queryClient }), - loader: ({ context }) => - context.queryClient.query({ ...postsQuery, staleTime: 'static' }), + loader: ({ context }) => context.queryClient.ensureQueryData(postsQuery), }) source: 'docs/router/eslint/create-route-property-order.md' priority: HIGH @@ -538,7 +536,7 @@ skills: - '@tanstack/react-router-ssr-query' covers: - External cache coordination pattern - - "queryClient.query with staleTime: 'static' in loader" + - queryClient.ensureQueryData in loader - useSuspenseQuery in components - setupRouterSsrQueryIntegration - defaultPreloadStaleTime @@ -581,11 +579,11 @@ skills: priority: HIGH status: active - - mistake: 'Awaiting a fire-and-forget query in loader blocks rendering' + - mistake: 'Awaiting prefetchQuery in loader blocks rendering' mechanism: >- - 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. + 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. source: 'docs/router/integrations/query.md' priority: MEDIUM status: active diff --git a/_artifacts/skill_spec.md b/_artifacts/skill_spec.md index 7eb9554a42..4503afb48a 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 a fire-and-forget query 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 prefetchQuery 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 6f7c4c8742..ec38a04bdd 100644 --- a/_artifacts/skill_tree.yaml +++ b/_artifacts/skill_tree.yaml @@ -246,7 +246,7 @@ skills: package: 'packages/react-router' description: >- Integrating TanStack Router with TanStack Query: queryClient - in router context, static queries and fire-and-forget queries in loaders, + in router context, ensureQueryData/prefetchQuery 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 deleted file mode 100644 index 9d56a2411a..0000000000 --- a/benchmarks/AGENTS.md +++ /dev/null @@ -1,15 +0,0 @@ -# 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 index 94d2f31802..96cd63f850 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -1,7 +1,6 @@ # CPU simulation benchmarks -`client-nav` measures navigation, mounting, and React/Solid hydration in -Node/jsdom; `ssr` measures server requests. +`client-nav` measures navigation in Node/jsdom; `ssr` measures server requests. Both suites run through the CodSpeed Vitest integration in CPU simulation mode. ## Worker runtime @@ -76,13 +75,13 @@ Node and use `setImmediate` directly. Dispatch the existing `Benchmarks` workflow against an unchanged branch: ```sh -gh workflow run benchmarks.yml --ref +gh workflow run client-nav-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. +CPU results (currently 132), 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/README.md b/benchmarks/bundle-size/README.md index 2185d6b43f..e5986f106c 100644 --- a/benchmarks/bundle-size/README.md +++ b/benchmarks/bundle-size/README.md @@ -42,7 +42,7 @@ pnpm benchmark:bundle-size:run --scenario react-router.minimal,react-router.full 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`. +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:build` 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: @@ -65,29 +65,6 @@ Full stdout and stderr stay in the log files. A positive bundle-size delta does 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: @@ -114,8 +91,6 @@ Without `--name`, runs replace `current.json` and the logs for the steps they ru 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. @@ -133,8 +108,6 @@ 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 diff --git a/benchmarks/bundle-size/package.json b/benchmarks/bundle-size/package.json index ca34cd6cd7..3705df05fc 100644 --- a/benchmarks/bundle-size/package.json +++ b/benchmarks/bundle-size/package.json @@ -3,20 +3,17 @@ "private": true, "type": "module", "scripts": { - "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" + "build": "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" }, "nx": { "targets": { - "measure": { - "cache": true, + "build": { "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" @@ -68,7 +65,7 @@ "vue": "^3.5.16" }, "devDependencies": { - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", "@tanstack/router-plugin": "workspace:^", "@types/react": "^19.0.8", diff --git a/benchmarks/client-nav/README.md b/benchmarks/client-nav/README.md index ec34ecc0c1..6179c7f0b8 100644 --- a/benchmarks/client-nav/README.md +++ b/benchmarks/client-nav/README.md @@ -9,11 +9,10 @@ Cross-framework client-side CPU benchmarks for: The benchmarks run in jsdom against production builds of real apps, and are tracked in CI by CodSpeed (simulation mode). -> **Scope:** these benchmarks cover the 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`. +> **Scope:** these benchmarks cover the standalone client router only. The +> client side of TanStack Start (hydration of a server-rendered document, +> streamed payload consumption, server-function calls from the client, ...) is +> not covered here; the server side of Start is covered by `benchmarks/ssr`. ## Layout @@ -39,7 +38,7 @@ scenarios/// routes/ ``` -Navigation scenario apps use file-based routing (`@tanstack/router-plugin`) with a +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 @@ -58,11 +57,9 @@ be attributed to a specific feature area. | `control-flow` | Loader-thrown `redirect` (including a 2-hop chain), `notFound()` with `notFoundComponent`, loader errors with `errorComponent`, and boundary reset on recovery navigation. | | `head` | `HeadContent` per-navigation work: nested route `head()` evaluation, title/meta/link dedupe across matches, and head tag DOM updates during navigation. | | `history` | History push/replace/back/forward traversal, location masking, registered-but-never-blocking `useBlocker`, and `useCanGoBack`/`useLocation` subscriptions. | -| `hydration` | Initial DOM hydration: execute the SSR payload, restore `beforeLoad` context and loader data, and hydrate 192 ordinary and eight hash-sensitive Links through their follow-up effects in React and Solid. | -| `link-churn` | Links that depart, stay and mount: 30 `/hub` layout Links stay while 100 `/hub/list` leaf Links leave (alone, or with the layout to `/other`) and remount on return; a search-only change rebuilds updater and `to="."` Links. Unlike `links`, whose root-layout Links never depart. | | `links` | Per-navigation cost of ~200 mounted ``s: link prop building, active-state recompute across `activeOptions` variants, `activeProps` swaps, and `useMatchRoute` probes (the `MatchRoute` component is avoided: vue-router's implementation leaks one subscription per render). | | `loaders` | Client loader dispatch: always-stale re-runs (`staleTime: 0`), cached revisits (re-run once per lap by the `invalidate` step), `loaderDeps`-keyed caching, `router.invalidate()`, and `useLoaderData` selectors. | -| `mount` | Cold start: `createRouter` (route-tree processing) + first render + initial `router.load()` + unmount, with a fresh router per mount. | +| `mount` | Cold start: `createRouter` (route-tree processing) + first render + initial `router.load()` + unmount, with a fresh router per mount. The only scenario measuring router creation. | | `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). | @@ -71,14 +68,10 @@ be attributed to a specific feature area. ## Conventions -The hydration scenario has the separate lifecycle described below. The other -scenarios follow these navigation/mount conventions: - - Apps are built with `NODE_ENV=production` (`minify: false`) into `dist/app.js`; benches import the built bundle, so production package builds and production JSX output are measured, not dev transforms. - Scenarios behave like a real user app: navigation happens through `` clicks dispatched on real anchor elements (unless a scenario specifically measures the imperative API), the router uses the default browser history, and `scrollRestoration` is enabled. - Each benchmark iteration advances a fixed, circular sequence of steps; every step awaits the router's `onRendered` event, so render work is included and steps cannot overlap. No two consecutive steps may target the same location, and the sequence ends back on the initial route. - Setup runs one warm-up lap through the sequence and asserts each step's observable output (e.g. `document.title`), so a scenario that silently stops doing its work fails instead of reporting a fast time. -- Apps are mounted and disposed outside timing by `benchLifecycle` (`benchmarks/cpu-simulation.ts`): CodSpeed measures a single invocation, so every invocation gets a freshly mounted app; plain `vitest bench` keeps one app per warmup/run phase. Bench functions must be `async` functions, because CodSpeed's Vitest 5 provider awaits only `AsyncFunction`s. - Determinism: no wall-clock timers (async work is resolved promises or counted `setTimeout(0)` hops), `staleTime`/`gcTime` only ever `0` or effectively-infinite, no `Math.random`/`Date.now` in the measured loop. Scroll restoration uses `getScrollRestorationKey: (location) => location.pathname` so its cache stays bounded (the default random per-entry key grows one cache entry per push navigation). The `mount` scenario opts out of `scrollRestoration` entirely and destroys its history on unmount — both register page-lifetime globals that would leak across its mount/unmount loop. - Push-only step laps grow jsdom's session-history entry list over a run (jsdom never truncates entries behind the current index). Per-push cost stays O(1) so timings are unaffected; only the `history` scenario needs — and has — a lap that is depth-stationary. - Calibration: pick per-iteration step counts so a bench's `vitest bench` run stays roughly between 8 and 30 seconds (long enough to average out, short enough for CI). @@ -103,7 +96,7 @@ Run a single scenario app manually (after building it through Nx): ```bash CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav--:build:client --outputStyle=stream --skipRemoteCache -cd benchmarks/client-nav && NODE_ENV=production vitest bench --mode benchmark --config ./scenarios///vite.config.ts +cd benchmarks/client-nav && NODE_ENV=production vitest bench --config ./scenarios///vite.config.ts ``` Run framework-specific flame benchmarks (10 second loop, profiled with `@platformatic/flame`, forced to `NODE_ENV=production`): @@ -122,186 +115,3 @@ Typecheck benchmark sources (baseline + scenarios): ```bash CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav:test:types --outputStyle=stream --skipRemoteCache ``` - -## Hydration - -`scenarios/hydration/{react,solid}` provide the same initial-hydration -workload: 192 ordinary Links, eight hash-sensitive Links, and three matched -routes with three `beforeLoad` contexts and two loader results. The server URL -has no fragment; the client URL has `#details`, matching half of the hash-sensitive Links. - -```bash -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav-hydration-react:test:perf --outputStyle=stream --skipRemoteCache -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav-hydration-react:test:unit --outputStyle=stream --skipRemoteCache -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/client-nav-hydration-react:test:types:client --outputStyle=stream --skipRemoteCache -``` - -Replace `react` with `solid` to run the other adapter. - -The build generates static HTML and its real Router SSR bootstrap scripts once -with `createRequestHandler` and the adapter's streaming renderer. Generation -fully consumes the response and runs outside the CodSpeed action. The measured -worker only reads these artifacts; it does not import a server renderer or start a server. - -Each invocation uses a fresh jsdom window and a fresh evaluation of the complete -production client bundle in that window's realm. HTML parsing, bundle evaluation, -and the initial document lifecycle finish in untimed setup. This resets module -state as well as the DOM, avoiding cached hydration promises and cross-realm -payload objects. The bundle and bootstrap scripts are compiled once, so this -measures a fresh application with warm code, not JavaScript download/parse cost. - -The timed region executes the serialized payload, creates the router and its -small code-based route tree, calls the public client `hydrate` API, and hydrates -the existing DOM with the framework's native renderer: - -- **React:** a separate completion component signals from its post-hydration - effect, after the same snapshot transition as hash-sensitive Links. The harness - awaits that signal and two idle React scheduler turns, then checks the expected - active links. The window's `performance.now()` is frozen, so React's - scheduler yields only to paint after commits, not after 5 ms of wall time, which CPU - instrumentation stretches by a runner-dependent factor. Each sample therefore - uses the same number of scheduler tasks. `Date.now()` is unchanged. A - 60-second watchdog fails a sample that never settles. -- **Solid:** execute the native hydration bootstrap and retain the server's - component/key hierarchy. Wait for mount, the router's rendered event, active-link - effects, and two idle turns. DOM identity assertions include every workload - element so template fallback cannot silently replace server nodes. - -Solid bounds settlement to 100 turns. Ending at the hydration call or the -first mount would miss post-hydration Link updates. -Timer turns use `setImmediate`; scrolling is a no-op -because this is CPU simulation rather than browser layout/paint measurement. - -Untimed assertions verify restored contexts and every loader row, zero client -`beforeLoad`/loader calls, expected hrefs/active state, original DOM-node identity, -working event handlers, and absence of hydration errors. Root unmount, pending -task cancellation, and window disposal also run outside measurement. Diagnostic -tests count Link renders or reactive evaluations and check they stop before the -measured region ends; counting is disabled in the timed workload. - -The bench's own `beforeEach`/`afterEach` hooks prepare and dispose every -sample outside timing, in both CodSpeed and ordinary Vitest runs. Per-phase -setup would let later iterations reuse an already hydrated document. The -hydration unit tests cover repeated fresh-state setup. - -Each scenario is included in its framework's aggregate build and CodSpeed run. -Land the benchmark independently to establish main's baseline before comparing a -hydration optimization. Regenerate each revision's artifacts with identical -fixture data and dependencies; do not pin an old hydration wire format forever. - -## Isolated route-tree construction - -`scenarios/route-tree-scale` measures navigation over an existing tree, not -construction. `scenarios/mount` includes construction but also rendering and -loading. To isolate initialization, use the core construction benchmark: - -```bash -CI=1 NX_DAEMON=false pnpm nx run @tanstack/router-core:test:unit --outputStyle=stream --skipRemoteCache -- bench tests/route-tree-construction.bench.ts --run --testNamePattern=1000.routes --reporter=json --outputFile=/tmp/route-tree-construction.json -``` - -It covers 100, 1,000, and 10,000 static, dynamic, nested, or mixed routes. -The processing-only case creates fresh route objects in an untimed -`beforeEach`, then measures `processRouteTree` and `route.init`. A separate -case includes route-object creation. Neither case measures first interpolation -or navigation. Remove the name filter to run all sizes. Compare identical -benchmark sources in separate checkouts and repeat fresh processes; a cached -router or repeatedly initialized tree is not a construction baseline. - -## Opt-in React Link performance suite - -`link-performance/` contains additional client-navigation and SSR workloads for -focused Link work. They are **not included** in the regular client-nav/SSR -aggregate projects or their CodSpeed build dependencies; they only run through -the dedicated `@benchmarks/react-link-performance` targets below. Use `-t` to -narrow a run to specific cases. - -```bash -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:perf:client --outputStyle=stream --skipRemoteCache -- --run -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:perf:ssr --outputStyle=stream --skipRemoteCache -- --run - -# Select a feature and save the normal Vitest JSON report. -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:perf:client --outputStyle=stream --skipRemoteCache -- --run -t "updater|optional|splat" --reporter=json --outputFile=/tmp/link-perf.json -``` - -The cases cover repeated versus unique destination params, updater functions, -relative/inherited values, search middleware chains, param stringification, -optional and splat segments, encoding, masks, basepath/rewrites, and active -props with structured search. These exercise different costs: cache hits and -misses, parameter cloning, callbacks, middleware traversal, URI encoding, -building masked/public locations, active-state comparisons, and prop merging. -Existing preload, mount, and route-tree-scale scenarios remain responsible for -those separate workloads. - -- **Client:** 200 persistent measured Links, four control Links, and eight - completed navigations per timed batch. The existing client harness checks - hrefs and active state during its untimed warm-up lap. Control navigations - replace the history entry, keeping history size constant. Post-measurement - assertions also check that the measured anchors stayed mounted. -- **SSR:** four fresh-router requests per timed batch, each rendering 200 - measured Links through `RouterProvider` and `renderToString`. Router creation, - `router.load()`, rendering, and history cleanup are included. This isolates - Router SSR Link work, not Start HTTP handling, dehydration, or streaming. - HTML assertions run outside the timed batch. -- Both use the same code-based workload definitions and production JSX/library - builds. The regular Vitest entry points use at least 100 warm-up iterations, - one second of warm-up time, and five-second measurement windows. The client - and server bundles assert their resolved `isServer` environment. React and - React DOM remain external so comparisons can share the same renderer runtime. - These bundles are Node-hosted (jsdom for client mode), not browser deployments. - -Run the gate tests and typecheck separately: - -```bash -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:unit --outputStyle=stream --skipRemoteCache -CI=1 NX_DAEMON=false pnpm nx run @benchmarks/react-link-performance:test:types --outputStyle=stream --skipRemoteCache -``` - -For before/after comparisons, use identical benchmark files and dependencies -on both refs, build each ref through its Nx targets, and alternate fresh -Vitest processes. Report the actual refs, per-case means and relative margins -of error; rerun noisy or borderline results with `-t` rather than interpreting -a small difference as a proven speedup. Client and SSR times have different -batch units and should not be compared directly. - -### Stable paired comparisons - -For regression decisions, prefer the paired runner over a whole-file Vitest -run. It starts a fresh process for every case and repetition, avoiding JIT -feedback from earlier cases. Inside each process, both revisions share the -same production React installation but have separate router/app modules and -router instances. Initialization order alternates between repetitions. -Built snapshots are staged under `node_modules/.cache` so the TypeScript -harness loader does not transpile their emitted JavaScript a second time. - -```bash -# Build the baseline using these same benchmark sources in its own checkout. -# --baseline points to that checkout's link-performance/dist directory. -pnpm nx run @benchmarks/react-link-performance:test:perf:stable -- \ - --baseline /path/to/baseline/benchmarks/client-nav/link-performance/dist \ - --outputJson /tmp/paired-links.json - -# Narrow a comparison, or increase independent process repetitions. -pnpm nx run @benchmarks/react-link-performance:test:perf:stable -- \ - --baseline /path/to/baseline/benchmarks/client-nav/link-performance/dist \ - --mode ssr -t "middleware|unique-params" --repeats 6 \ - --outputJson /tmp/paired-links-ssr.json -``` - -The runner requires Node with `process.threadCpuUsage` (Node 24 works). -It fixes V8 random/hash seeds, warms each variant for at least two seconds -and 100 batches, then alternates ABBA/BAAB blocks calibrated to roughly 500 ms. -Both variants do exactly the same number of batches per block. It records -main-thread CPU time, wall time, and whole-process CPU time; GC during -measurement is not disabled or discarded. - -The default is four independent process repetitions. Reported 95% intervals -use their paired log-ratios, not the many correlated batches as independent -samples. A faster/slower verdict requires CPU and wall intervals to agree. -Intervals overlapping zero or disagreeing metrics are inconclusive; narrow -intervals entirely inside +/-2% are reported separately. - -An A/A calibration uses the current `dist` directory as `--baseline`. Its -intervals should contain zero before trusting similarly sized A/B differences. -Shared-machine contention can still make small changes unresolved. Do not -interpret a point estimate alone, or an inconclusive result, as proof that -a workload is unchanged. diff --git a/benchmarks/client-nav/link-performance/cases.ts b/benchmarks/client-nav/link-performance/cases.ts deleted file mode 100644 index a25eac563b..0000000000 --- a/benchmarks/client-nav/link-performance/cases.ts +++ /dev/null @@ -1,360 +0,0 @@ -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 deleted file mode 100644 index f819fab52b..0000000000 --- a/benchmarks/client-nav/link-performance/client.bench.ts +++ /dev/null @@ -1,30 +0,0 @@ -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 deleted file mode 100644 index 1a468a3169..0000000000 --- a/benchmarks/client-nav/link-performance/config.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -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 deleted file mode 100644 index 416b027057..0000000000 --- a/benchmarks/client-nav/link-performance/config.ts +++ /dev/null @@ -1,69 +0,0 @@ -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 deleted file mode 100644 index fd1751c081..0000000000 --- a/benchmarks/client-nav/link-performance/project.json +++ /dev/null @@ -1,103 +0,0 @@ -{ - "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 deleted file mode 100644 index f1a3fb6df7..0000000000 --- a/benchmarks/client-nav/link-performance/scenario.ts +++ /dev/null @@ -1,114 +0,0 @@ -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 deleted file mode 100644 index a187ee8c15..0000000000 --- a/benchmarks/client-nav/link-performance/src/client.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 491191b1f9..0000000000 --- a/benchmarks/client-nav/link-performance/src/ssr.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 8315b85b8b..0000000000 --- a/benchmarks/client-nav/link-performance/src/workload.tsx +++ /dev/null @@ -1,506 +0,0 @@ -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 deleted file mode 100644 index c30084e510..0000000000 --- a/benchmarks/client-nav/link-performance/ssr.bench.ts +++ /dev/null @@ -1,30 +0,0 @@ -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 deleted file mode 100644 index 59ccfa3cb4..0000000000 --- a/benchmarks/client-nav/link-performance/stable-runner.ts +++ /dev/null @@ -1,269 +0,0 @@ -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 deleted file mode 100644 index 087b32414a..0000000000 --- a/benchmarks/client-nav/link-performance/stable-worker.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -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 deleted file mode 100644 index d98679dc15..0000000000 --- a/benchmarks/client-nav/link-performance/stable-worker.ts +++ /dev/null @@ -1,112 +0,0 @@ -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 deleted file mode 100644 index ac07d34c29..0000000000 --- a/benchmarks/client-nav/link-performance/staging.ts +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index 8f5f37413b..0000000000 --- a/benchmarks/client-nav/link-performance/statistics.test.ts +++ /dev/null @@ -1,36 +0,0 @@ -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 deleted file mode 100644 index 469bdaf65a..0000000000 --- a/benchmarks/client-nav/link-performance/statistics.ts +++ /dev/null @@ -1,57 +0,0 @@ -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 deleted file mode 100644 index fbf230c977..0000000000 --- a/benchmarks/client-nav/link-performance/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "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 deleted file mode 100644 index 1cd45fc45e..0000000000 --- a/benchmarks/client-nav/link-performance/vite.client.config.ts +++ /dev/null @@ -1,3 +0,0 @@ -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 deleted file mode 100644 index f59148eaf6..0000000000 --- a/benchmarks/client-nav/link-performance/vite.ssr.config.ts +++ /dev/null @@ -1,3 +0,0 @@ -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 deleted file mode 100644 index f8454c819d..0000000000 --- a/benchmarks/client-nav/link-performance/vitest.config.ts +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 474858a529..0000000000 --- a/benchmarks/client-nav/link-performance/worker-protocol.ts +++ /dev/null @@ -1,28 +0,0 @@ -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 1f878adc67..84f0dc9807 100644 --- a/benchmarks/client-nav/package.json +++ b/benchmarks/client-nav/package.json @@ -9,10 +9,10 @@ "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 --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:perf": "NODE_ENV=production vitest bench --config ./vitest.config.ts", + "test:perf:react": "NODE_ENV=production vitest bench --config ./vitest.react.config.ts", + "test:perf:solid": "NODE_ENV=production vitest bench --config ./vitest.solid.config.ts", + "test:perf:vue": "NODE_ENV=production vitest bench --config ./vitest.vue.config.ts", "test: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", @@ -31,7 +31,7 @@ }, "devDependencies": { "@platformatic/flame": "^1.6.0", - "@codspeed/vitest-plugin": "^6.0.1", + "@codspeed/vitest-plugin": "^5.5.0", "@tanstack/router-plugin": "workspace:^", "@testing-library/react": "^16.2.0", "@vitejs/plugin-react": "^6.0.1", @@ -64,8 +64,6 @@ "@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", @@ -94,8 +92,6 @@ "@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", @@ -124,7 +120,6 @@ "@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", @@ -206,13 +201,8 @@ "@benchmarks/client-nav-history-react", "@benchmarks/client-nav-history-solid", "@benchmarks/client-nav-history-vue", - "@benchmarks/client-nav-hydration-react", - "@benchmarks/client-nav-hydration-solid", - "@benchmarks/client-nav-link-churn-react", "@benchmarks/client-nav-links-react", - "@benchmarks/client-nav-link-churn-solid", "@benchmarks/client-nav-links-solid", - "@benchmarks/client-nav-link-churn-vue", "@benchmarks/client-nav-links-vue", "@benchmarks/client-nav-loaders-react", "@benchmarks/client-nav-loaders-solid", diff --git a/benchmarks/client-nav/react/speed.bench.ts b/benchmarks/client-nav/react/speed.bench.ts index 944f182734..fcc15b5fbc 100644 --- a/benchmarks/client-nav/react/speed.bench.ts +++ b/benchmarks/client-nav/react/speed.bench.ts @@ -1,19 +1,34 @@ -import { test } from 'vitest' +import { afterAll, beforeAll, bench, describe } from 'vitest' import { setup } from './setup' -test('client-nav', async ({ bench }) => { - const scenario = setup() +describe('client-nav', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, + * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. + * + * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, + * but it does support `beforeAll` and `afterAll`. + * + * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. + */ + + beforeAll(test.before) + afterAll(test.after) + + bench( 'client-side navigation loop (react)', - { beforeAll: scenario.before, afterAll: scenario.after }, async () => { for (let i = 0; i < 10; i++) { - await scenario.tick() + await test.tick() } }, - ).run({ - warmupIterations: 100, - time: 10_000, - }) + { + warmupIterations: 100, + time: 10_000, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/react/vite.config.ts b/benchmarks/client-nav/react/vite.config.ts index 7df3f80e71..ea85a49a21 100644 --- a/benchmarks/client-nav/react/vite.config.ts +++ b/benchmarks/client-nav/react/vite.config.ts @@ -34,6 +34,5 @@ export default defineConfig({ watch: false, environment: 'jsdom', setupFiles: [`${rootDir}vitest.setup.ts`], - benchmark: { include: ['react/speed.bench.ts'] }, }, }) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts b/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts index 65dab0781e..c3f4c5231c 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-async-pipeline', async ({ bench }) => { - const scenario = setup() +describe('client-async-pipeline', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-async-pipeline navigation loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts index acef710469..96082e9963 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-async-pipeline', async ({ bench }) => { - const scenario = setup() +describe('client-async-pipeline', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-async-pipeline navigation loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routeTree.gen.ts index 27b9498b11..7c15baf4e9 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/solid/src/routeTree.gen.ts @@ -9,25 +9,25 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as 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 IndexRouteImport } from './routes/index' import { Route as SlowIdRouteImport } from './routes/slow.$id' +import { Route as NestedIdRouteImport } from './routes/nested.$id' +import { Route as CtxIdRouteImport } from './routes/ctx.$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', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const SlowIdRoute = SlowIdRouteImport.update({ + id: '/slow/$id', + path: '/slow/$id', getParentRoute: () => rootRouteImport, } as any) const NestedIdRoute = NestedIdRouteImport.update({ @@ -35,9 +35,9 @@ const NestedIdRoute = NestedIdRouteImport.update({ path: '/$id', getParentRoute: () => NestedRoute, } as any) -const SlowIdRoute = SlowIdRouteImport.update({ - id: '/slow/$id', - path: '/slow/$id', +const CtxIdRoute = CtxIdRouteImport.update({ + id: '/ctx/$id', + path: '/ctx/$id', getParentRoute: () => rootRouteImport, } as any) @@ -80,13 +80,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/nested': { id: '/nested' path: '/nested' @@ -94,11 +87,18 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof NestedRouteImport parentRoute: typeof rootRouteImport } - '/ctx/$id': { - id: '/ctx/$id' - path: '/ctx/$id' - fullPath: '/ctx/$id' - preLoaderRoute: typeof CtxIdRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/slow/$id': { + id: '/slow/$id' + path: '/slow/$id' + fullPath: '/slow/$id' + preLoaderRoute: typeof SlowIdRouteImport parentRoute: typeof rootRouteImport } '/nested/$id': { @@ -108,11 +108,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof NestedIdRouteImport parentRoute: typeof NestedRoute } - '/slow/$id': { - id: '/slow/$id' - path: '/slow/$id' - fullPath: '/slow/$id' - preLoaderRoute: typeof SlowIdRouteImport + '/ctx/$id': { + id: '/ctx/$id' + path: '/ctx/$id' + fullPath: '/ctx/$id' + preLoaderRoute: typeof CtxIdRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts index f0fd3e58df..193a3837df 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-async-pipeline', async ({ bench }) => { - const scenario = setup() +describe('client-async-pipeline', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-async-pipeline navigation loop (vue)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routeTree.gen.ts index 66b9efd7aa..ce26dc62d1 100644 --- a/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/async-pipeline/vue/src/routeTree.gen.ts @@ -9,25 +9,25 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as 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 IndexRouteImport } from './routes/index' import { Route as SlowIdRouteImport } from './routes/slow.$id' +import { Route as NestedIdRouteImport } from './routes/nested.$id' +import { Route as CtxIdRouteImport } from './routes/ctx.$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', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const SlowIdRoute = SlowIdRouteImport.update({ + id: '/slow/$id', + path: '/slow/$id', getParentRoute: () => rootRouteImport, } as any) const NestedIdRoute = NestedIdRouteImport.update({ @@ -35,9 +35,9 @@ const NestedIdRoute = NestedIdRouteImport.update({ path: '/$id', getParentRoute: () => NestedRoute, } as any) -const SlowIdRoute = SlowIdRouteImport.update({ - id: '/slow/$id', - path: '/slow/$id', +const CtxIdRoute = CtxIdRouteImport.update({ + id: '/ctx/$id', + path: '/ctx/$id', getParentRoute: () => rootRouteImport, } as any) @@ -80,13 +80,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/nested': { id: '/nested' path: '/nested' @@ -94,11 +87,18 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof NestedRouteImport parentRoute: typeof rootRouteImport } - '/ctx/$id': { - id: '/ctx/$id' - path: '/ctx/$id' - fullPath: '/ctx/$id' - preLoaderRoute: typeof CtxIdRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/slow/$id': { + id: '/slow/$id' + path: '/slow/$id' + fullPath: '/slow/$id' + preLoaderRoute: typeof SlowIdRouteImport parentRoute: typeof rootRouteImport } '/nested/$id': { @@ -108,11 +108,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof NestedIdRouteImport parentRoute: typeof NestedRoute } - '/slow/$id': { - id: '/slow/$id' - path: '/slow/$id' - fullPath: '/slow/$id' - preLoaderRoute: typeof SlowIdRouteImport + '/ctx/$id': { + id: '/ctx/$id' + path: '/ctx/$id' + fullPath: '/ctx/$id' + preLoaderRoute: typeof CtxIdRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts b/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts index d6f2190be7..7f1153021f 100644 --- a/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/control-flow/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-control-flow', async ({ bench }) => { - const scenario = setup() +describe('client-control-flow', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-control-flow navigation loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts index d803d2a313..a88093ca52 100644 --- a/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/control-flow/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-control-flow', async ({ bench }) => { - const scenario = setup() +describe('client-control-flow', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-control-flow navigation loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts index cd84f99d5d..44d88e9f8d 100644 --- a/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/control-flow/solid/src/routeTree.gen.ts @@ -9,26 +9,16 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as 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 Hop2RouteImport } from './routes/hop2' +import { Route as Hop1RouteImport } from './routes/hop1' +import { Route as BrokenRouteImport } from './routes/broken' +import { Route as IndexRouteImport } from './routes/index' import { Route as 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', +const TargetRoute = TargetRouteImport.update({ + id: '/target', + path: '/target', getParentRoute: () => rootRouteImport, } as any) const Hop2Route = Hop2RouteImport.update({ @@ -36,9 +26,19 @@ const Hop2Route = Hop2RouteImport.update({ path: '/hop2', getParentRoute: () => rootRouteImport, } as any) -const TargetRoute = TargetRouteImport.update({ - id: '/target', - path: '/target', +const Hop1Route = Hop1RouteImport.update({ + id: '/hop1', + path: '/hop1', + getParentRoute: () => rootRouteImport, +} as any) +const BrokenRoute = BrokenRouteImport.update({ + id: '/broken', + path: '/broken', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const MissingIdRoute = MissingIdRouteImport.update({ @@ -98,25 +98,11 @@ export interface RootRouteChildren { 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 + '/target': { + id: '/target' + path: '/target' + fullPath: '/target' + preLoaderRoute: typeof TargetRouteImport parentRoute: typeof rootRouteImport } '/hop2': { @@ -126,11 +112,25 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof Hop2RouteImport parentRoute: typeof rootRouteImport } - '/target': { - id: '/target' - path: '/target' - fullPath: '/target' - preLoaderRoute: typeof TargetRouteImport + '/hop1': { + id: '/hop1' + path: '/hop1' + fullPath: '/hop1' + preLoaderRoute: typeof Hop1RouteImport + parentRoute: typeof rootRouteImport + } + '/broken': { + id: '/broken' + path: '/broken' + fullPath: '/broken' + preLoaderRoute: typeof BrokenRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/missing/$id': { diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts index 8a019945c7..9a335cfb87 100644 --- a/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/control-flow/vue/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-control-flow', async ({ bench }) => { - const scenario = setup() +describe('client-control-flow', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-control-flow navigation loop (vue)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts index 6b53a6a203..60fc846f89 100644 --- a/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/control-flow/vue/src/routeTree.gen.ts @@ -9,26 +9,16 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as 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 Hop2RouteImport } from './routes/hop2' +import { Route as Hop1RouteImport } from './routes/hop1' +import { Route as BrokenRouteImport } from './routes/broken' +import { Route as IndexRouteImport } from './routes/index' import { Route as 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', +const TargetRoute = TargetRouteImport.update({ + id: '/target', + path: '/target', getParentRoute: () => rootRouteImport, } as any) const Hop2Route = Hop2RouteImport.update({ @@ -36,9 +26,19 @@ const Hop2Route = Hop2RouteImport.update({ path: '/hop2', getParentRoute: () => rootRouteImport, } as any) -const TargetRoute = TargetRouteImport.update({ - id: '/target', - path: '/target', +const Hop1Route = Hop1RouteImport.update({ + id: '/hop1', + path: '/hop1', + getParentRoute: () => rootRouteImport, +} as any) +const BrokenRoute = BrokenRouteImport.update({ + id: '/broken', + path: '/broken', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const MissingIdRoute = MissingIdRouteImport.update({ @@ -98,25 +98,11 @@ export interface RootRouteChildren { 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 + '/target': { + id: '/target' + path: '/target' + fullPath: '/target' + preLoaderRoute: typeof TargetRouteImport parentRoute: typeof rootRouteImport } '/hop2': { @@ -126,11 +112,25 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof Hop2RouteImport parentRoute: typeof rootRouteImport } - '/target': { - id: '/target' - path: '/target' - fullPath: '/target' - preLoaderRoute: typeof TargetRouteImport + '/hop1': { + id: '/hop1' + path: '/hop1' + fullPath: '/hop1' + preLoaderRoute: typeof Hop1RouteImport + parentRoute: typeof rootRouteImport + } + '/broken': { + id: '/broken' + path: '/broken' + fullPath: '/broken' + preLoaderRoute: typeof BrokenRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/missing/$id': { diff --git a/benchmarks/client-nav/scenarios/head/react/speed.bench.ts b/benchmarks/client-nav/scenarios/head/react/speed.bench.ts index d0d731a09f..97c76a1a11 100644 --- a/benchmarks/client-nav/scenarios/head/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/head/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-head', async ({ bench }) => { - const scenario = setup() +describe('client-head', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-head navigation loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts index ca156c950b..075e7673de 100644 --- a/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/head/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-head', async ({ bench }) => { - const scenario = setup() +describe('client-head', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-head navigation loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts index b6f217e527..ead6a4436a 100644 --- a/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/head/solid/src/routeTree.gen.ts @@ -9,15 +9,15 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as 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 DocsRouteImport } from './routes/docs' +import { Route as IndexRouteImport } from './routes/index' import { Route as DocsSectionRouteImport } from './routes/docs.$section' +import { Route as ArticlesIdRouteImport } from './routes/articles.$id' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SettingsRoute = SettingsRouteImport.update({ + id: '/settings', + path: '/settings', getParentRoute: () => rootRouteImport, } as any) const DocsRoute = DocsRouteImport.update({ @@ -25,14 +25,9 @@ const DocsRoute = DocsRouteImport.update({ 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', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const DocsSectionRoute = DocsSectionRouteImport.update({ @@ -40,6 +35,11 @@ const DocsSectionRoute = DocsSectionRouteImport.update({ path: '/$section', getParentRoute: () => DocsRoute, } as any) +const ArticlesIdRoute = ArticlesIdRouteImport.update({ + id: '/articles/$id', + path: '/articles/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -86,11 +86,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/settings': { + id: '/settings' + path: '/settings' + fullPath: '/settings' + preLoaderRoute: typeof SettingsRouteImport parentRoute: typeof rootRouteImport } '/docs': { @@ -100,18 +100,11 @@ declare module '@tanstack/solid-router' { 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 + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/docs/$section': { @@ -121,6 +114,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DocsSectionRouteImport parentRoute: typeof DocsRoute } + '/articles/$id': { + id: '/articles/$id' + path: '/articles/$id' + fullPath: '/articles/$id' + preLoaderRoute: typeof ArticlesIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts index d188a9dd7a..7080b4ea7d 100644 --- a/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/head/vue/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-head', async ({ bench }) => { - const scenario = setup() +describe('client-head', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-head navigation loop (vue)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts index 161f99a65c..b115854c26 100644 --- a/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/head/vue/src/routeTree.gen.ts @@ -9,15 +9,15 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as 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 DocsRouteImport } from './routes/docs' +import { Route as IndexRouteImport } from './routes/index' import { Route as DocsSectionRouteImport } from './routes/docs.$section' +import { Route as ArticlesIdRouteImport } from './routes/articles.$id' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const SettingsRoute = SettingsRouteImport.update({ + id: '/settings', + path: '/settings', getParentRoute: () => rootRouteImport, } as any) const DocsRoute = DocsRouteImport.update({ @@ -25,14 +25,9 @@ const DocsRoute = DocsRouteImport.update({ 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', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const DocsSectionRoute = DocsSectionRouteImport.update({ @@ -40,6 +35,11 @@ const DocsSectionRoute = DocsSectionRouteImport.update({ path: '/$section', getParentRoute: () => DocsRoute, } as any) +const ArticlesIdRoute = ArticlesIdRouteImport.update({ + id: '/articles/$id', + path: '/articles/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -86,11 +86,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/settings': { + id: '/settings' + path: '/settings' + fullPath: '/settings' + preLoaderRoute: typeof SettingsRouteImport parentRoute: typeof rootRouteImport } '/docs': { @@ -100,18 +100,11 @@ declare module '@tanstack/vue-router' { 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 + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/docs/$section': { @@ -121,6 +114,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof DocsSectionRouteImport parentRoute: typeof DocsRoute } + '/articles/$id': { + id: '/articles/$id' + path: '/articles/$id' + fullPath: '/articles/$id' + preLoaderRoute: typeof ArticlesIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/history/react/speed.bench.ts b/benchmarks/client-nav/scenarios/history/react/speed.bench.ts index 6ec7031857..9192258b66 100644 --- a/benchmarks/client-nav/scenarios/history/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/history/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-history', async ({ bench }) => { - const scenario = setup() +describe('client-history', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-history navigation loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts index 56af035b2b..d7f4fd898d 100644 --- a/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/history/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-history', async ({ bench }) => { - const scenario = setup() +describe('client-history', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-history navigation loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts index af253f4a15..a6ab2a4fc8 100644 --- a/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/history/solid/src/routeTree.gen.ts @@ -9,24 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as GalleryRouteImport } from './routes/gallery' -import { Route as PagesNRouteImport } from './routes/pages.$n' +import { Route as IndexRouteImport } from './routes/index' import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' +import { Route as PagesNRouteImport } from './routes/pages.$n' -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', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ @@ -34,6 +29,11 @@ const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ path: '/photos/$photoId', getParentRoute: () => rootRouteImport, } as any) +const PagesNRoute = PagesNRouteImport.update({ + id: '/pages/$n', + path: '/pages/$n', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -71,13 +71,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/gallery': { id: '/gallery' path: '/gallery' @@ -85,11 +78,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof GalleryRouteImport parentRoute: typeof rootRouteImport } - '/pages/$n': { - id: '/pages/$n' - path: '/pages/$n' - fullPath: '/pages/$n' - preLoaderRoute: typeof PagesNRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/photos/$photoId': { @@ -99,6 +92,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PhotosPhotoIdRouteImport parentRoute: typeof rootRouteImport } + '/pages/$n': { + id: '/pages/$n' + path: '/pages/$n' + fullPath: '/pages/$n' + preLoaderRoute: typeof PagesNRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts index 3d36ac4cfa..a378e45ac5 100644 --- a/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/history/vue/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-history', async ({ bench }) => { - const scenario = setup() +describe('client-history', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-history navigation loop (vue)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts index 519aef7c8f..cee1b68870 100644 --- a/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/history/vue/src/routeTree.gen.ts @@ -9,24 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as GalleryRouteImport } from './routes/gallery' -import { Route as PagesNRouteImport } from './routes/pages.$n' +import { Route as IndexRouteImport } from './routes/index' import { Route as PhotosPhotoIdRouteImport } from './routes/photos.$photoId' +import { Route as PagesNRouteImport } from './routes/pages.$n' -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', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ @@ -34,6 +29,11 @@ const PhotosPhotoIdRoute = PhotosPhotoIdRouteImport.update({ path: '/photos/$photoId', getParentRoute: () => rootRouteImport, } as any) +const PagesNRoute = PagesNRouteImport.update({ + id: '/pages/$n', + path: '/pages/$n', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -71,13 +71,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/gallery': { id: '/gallery' path: '/gallery' @@ -85,11 +78,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof GalleryRouteImport parentRoute: typeof rootRouteImport } - '/pages/$n': { - id: '/pages/$n' - path: '/pages/$n' - fullPath: '/pages/$n' - preLoaderRoute: typeof PagesNRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/photos/$photoId': { @@ -99,6 +92,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PhotosPhotoIdRouteImport parentRoute: typeof rootRouteImport } + '/pages/$n': { + id: '/pages/$n' + path: '/pages/$n' + fullPath: '/pages/$n' + preLoaderRoute: typeof PagesNRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/hydration/react/fixture.ts b/benchmarks/client-nav/scenarios/hydration/react/fixture.ts deleted file mode 100644 index 950c870a1c..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/fixture.ts +++ /dev/null @@ -1,31 +0,0 @@ -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 deleted file mode 100644 index fbc67c5a08..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/generate-fixture.mjs +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index 7e466cbaed..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/hydration.test.ts +++ /dev/null @@ -1,93 +0,0 @@ -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 deleted file mode 100644 index ca23838c0f..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index cc4c09a72d..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/settle.ts +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 7c588af3fd..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/setup.ts +++ /dev/null @@ -1,316 +0,0 @@ -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 deleted file mode 100644 index 643877760e..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index e9797f71fa..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/src/app.tsx +++ /dev/null @@ -1,216 +0,0 @@ -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 deleted file mode 100644 index 42c5a5104e..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/src/client.tsx +++ /dev/null @@ -1,83 +0,0 @@ -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 deleted file mode 100644 index 713b0a77f2..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/src/server.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 23dd08de8b..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/tsconfig.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "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 deleted file mode 100644 index 62ab87115b..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/vite.config.ts +++ /dev/null @@ -1,36 +0,0 @@ -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 deleted file mode 100644 index fbf6a149b9..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/react/vite.server.config.ts +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index 4c86d0e2f4..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/fixture.ts +++ /dev/null @@ -1,35 +0,0 @@ -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 deleted file mode 100644 index 63647e1be7..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/generate-fixture.mjs +++ /dev/null @@ -1,30 +0,0 @@ -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 deleted file mode 100644 index 4e5f3208ca..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/hydration.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -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 deleted file mode 100644 index 1fa162771b..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index ebdbc8e9b2..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/setup.ts +++ /dev/null @@ -1,326 +0,0 @@ -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 deleted file mode 100644 index b386cb8215..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index cb772d6b5b..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/src/app.tsx +++ /dev/null @@ -1,213 +0,0 @@ -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 deleted file mode 100644 index ef0f5268d6..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/src/client.tsx +++ /dev/null @@ -1,91 +0,0 @@ -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 deleted file mode 100644 index 6052c48eac..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/src/server.tsx +++ /dev/null @@ -1,40 +0,0 @@ -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 deleted file mode 100644 index daf27ddf12..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/tsconfig.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "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 deleted file mode 100644 index 16e5ff95aa..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/vite.config.ts +++ /dev/null @@ -1,38 +0,0 @@ -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 deleted file mode 100644 index 9787cbb4e2..0000000000 --- a/benchmarks/client-nav/scenarios/hydration/solid/vite.server.config.ts +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 1606b2c456..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 59221603da..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index ca0b370528..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 5febd6f795..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/src/main.tsx +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 4535430b61..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/src/routeTree.gen.ts +++ /dev/null @@ -1,121 +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 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 deleted file mode 100644 index 199cf1ff73..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/src/routes/__root.tsx +++ /dev/null @@ -1,39 +0,0 @@ -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 deleted file mode 100644 index 143cb39a7a..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.detail.$id.tsx +++ /dev/null @@ -1,21 +0,0 @@ -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 deleted file mode 100644 index 5aa37b20a7..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.list.tsx +++ /dev/null @@ -1,65 +0,0 @@ -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 deleted file mode 100644 index ac12eae2da..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/src/routes/hub.tsx +++ /dev/null @@ -1,64 +0,0 @@ -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 deleted file mode 100644 index 1f146b789f..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/src/routes/other.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 1d59cbb450..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "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 deleted file mode 100644 index 344974ebf9..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/react/vite.config.ts +++ /dev/null @@ -1,42 +0,0 @@ -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 deleted file mode 100644 index d936af35cc..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/shared.ts +++ /dev/null @@ -1,178 +0,0 @@ -/** - * 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 deleted file mode 100644 index 4e46143b32..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index a2a024341d..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 80c4aaa6fd..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index fa9d239418..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/src/main.tsx +++ /dev/null @@ -1,34 +0,0 @@ -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 deleted file mode 100644 index e3cb546963..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/src/routeTree.gen.ts +++ /dev/null @@ -1,121 +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 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 deleted file mode 100644 index a9de4ea356..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/__root.tsx +++ /dev/null @@ -1,39 +0,0 @@ -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 deleted file mode 100644 index 7aca4a9935..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.detail.$id.tsx +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 5796a50b02..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.list.tsx +++ /dev/null @@ -1,68 +0,0 @@ -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 deleted file mode 100644 index 4682f85aae..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/hub.tsx +++ /dev/null @@ -1,67 +0,0 @@ -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 deleted file mode 100644 index 2606089113..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/src/routes/other.tsx +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index 98d76ad6b8..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "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 deleted file mode 100644 index 37718a2d6a..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/solid/vite.config.ts +++ /dev/null @@ -1,50 +0,0 @@ -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 deleted file mode 100644 index fb890ddfb8..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/project.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "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 deleted file mode 100644 index 95cacb9ea8..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index dea511c24c..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/speed.bench.ts +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index f4a0b4e6ff..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/speed.flame.ts +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index cae9b54f1d..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/src/main.tsx +++ /dev/null @@ -1,41 +0,0 @@ -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 deleted file mode 100644 index 9327bbc01d..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/src/routeTree.gen.ts +++ /dev/null @@ -1,121 +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 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 deleted file mode 100644 index a4f7985c5a..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/__root.tsx +++ /dev/null @@ -1,46 +0,0 @@ -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 deleted file mode 100644 index 4701ab44eb..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.detail.$id.tsx +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index 02abd6db1b..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.list.tsx +++ /dev/null @@ -1,74 +0,0 @@ -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 deleted file mode 100644 index 5be17f3350..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/hub.tsx +++ /dev/null @@ -1,69 +0,0 @@ -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 deleted file mode 100644 index 08dec586fa..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/src/routes/other.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 7786fc3da9..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "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 deleted file mode 100644 index 8f56734e04..0000000000 --- a/benchmarks/client-nav/scenarios/link-churn/vue/vite.config.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { fileURLToPath } from 'node:url' -import { defineConfig } from 'vitest/config' -import vue from '@vitejs/plugin-vue' -import vueJsx from '@vitejs/plugin-vue-jsx' -import codspeedPlugin from '@codspeed/vitest-plugin' -import { tanstackRouter } from '@tanstack/router-plugin/vite' -import { cpuSimulationExecArgv } from '../../../../cpu-simulation' - -const rootDir = fileURLToPath(new URL('.', import.meta.url)) - -export default defineConfig({ - root: rootDir, - define: { - 'process.env.NODE_ENV': JSON.stringify('production'), - }, - plugins: [ - !!(process.env.VITEST && process.env.WITH_INSTRUMENTATION) && - codspeedPlugin(), - tanstackRouter({ - target: 'vue', - routesDirectory: `${rootDir}src/routes`, - generatedRouteTree: `${rootDir}src/routeTree.gen.ts`, - }), - vue(), - vueJsx(), - ], - build: { - outDir: './dist', - emptyOutDir: true, - minify: false, - lib: { - entry: './src/main.tsx', - formats: ['es'], - fileName: 'app', - }, - }, - test: { - execArgv: cpuSimulationExecArgv(), - name: '@benchmarks/client-nav link-churn (vue)', - watch: false, - environment: 'jsdom', - setupFiles: ['../../../vitest.setup.ts'], - }, -}) diff --git a/benchmarks/client-nav/scenarios/links/react/speed.bench.ts b/benchmarks/client-nav/scenarios/links/react/speed.bench.ts index 75f5f725d4..0892308901 100644 --- a/benchmarks/client-nav/scenarios/links/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/links/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-links', async ({ bench }) => { - const scenario = setup() +describe('client-links', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-links navigation loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts index fc7f3e71e7..a3d690b423 100644 --- a/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/links/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-links', async ({ bench }) => { - const scenario = setup() +describe('client-links', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-links navigation loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts index 0da70513e8..b61431e40d 100644 --- a/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/links/solid/src/routeTree.gen.ts @@ -9,20 +9,20 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' 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 IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const ItemsIdRoute = ItemsIdRouteImport.update({ id: '/items/$id', path: '/items/$id', @@ -61,13 +61,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -75,6 +68,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/items/$id': { id: '/items/$id' path: '/items/$id' diff --git a/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts index 2ace7a8409..e2d3f7c47a 100644 --- a/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/links/vue/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-links', async ({ bench }) => { - const scenario = setup() +describe('client-links', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-links navigation loop (vue)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts index 7d2b1e9bbb..cee64be43c 100644 --- a/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/links/vue/src/routeTree.gen.ts @@ -9,20 +9,20 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' 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 IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const ItemsIdRoute = ItemsIdRouteImport.update({ id: '/items/$id', path: '/items/$id', @@ -61,13 +61,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/about': { id: '/about' path: '/about' @@ -75,6 +68,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof AboutRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/items/$id': { id: '/items/$id' path: '/items/$id' diff --git a/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts b/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts index 8bcc53b88e..f5a51b29be 100644 --- a/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/loaders/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-loaders', async ({ bench }) => { - const scenario = setup() +describe('client-loaders', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-loaders navigation loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts index 953a17b31a..9f3bd397db 100644 --- a/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/loaders/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-loaders', async ({ bench }) => { - const scenario = setup() +describe('client-loaders', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-loaders navigation loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts index fa5d032141..bdec400237 100644 --- a/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/loaders/solid/src/routeTree.gen.ts @@ -9,24 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as DepsRouteImport } from './routes/deps' -import { Route as CachedIdRouteImport } from './routes/cached.$id' +import { Route as IndexRouteImport } from './routes/index' import { Route as FreshIdRouteImport } from './routes/fresh.$id' +import { Route as CachedIdRouteImport } from './routes/cached.$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', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const FreshIdRoute = FreshIdRouteImport.update({ @@ -34,6 +29,11 @@ const FreshIdRoute = FreshIdRouteImport.update({ path: '/fresh/$id', getParentRoute: () => rootRouteImport, } as any) +const CachedIdRoute = CachedIdRouteImport.update({ + id: '/cached/$id', + path: '/cached/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -71,13 +71,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/deps': { id: '/deps' path: '/deps' @@ -85,11 +78,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DepsRouteImport parentRoute: typeof rootRouteImport } - '/cached/$id': { - id: '/cached/$id' - path: '/cached/$id' - fullPath: '/cached/$id' - preLoaderRoute: typeof CachedIdRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/fresh/$id': { @@ -99,6 +92,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof FreshIdRouteImport parentRoute: typeof rootRouteImport } + '/cached/$id': { + id: '/cached/$id' + path: '/cached/$id' + fullPath: '/cached/$id' + preLoaderRoute: typeof CachedIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts index 1ae2f89a56..819fe020b0 100644 --- a/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/loaders/vue/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-loaders', async ({ bench }) => { - const scenario = setup() +describe('client-loaders', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-loaders navigation loop (vue)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts index 10cb8f2aca..25a82df477 100644 --- a/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/loaders/vue/src/routeTree.gen.ts @@ -9,24 +9,19 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as DepsRouteImport } from './routes/deps' -import { Route as CachedIdRouteImport } from './routes/cached.$id' +import { Route as IndexRouteImport } from './routes/index' import { Route as FreshIdRouteImport } from './routes/fresh.$id' +import { Route as CachedIdRouteImport } from './routes/cached.$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', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) const FreshIdRoute = FreshIdRouteImport.update({ @@ -34,6 +29,11 @@ const FreshIdRoute = FreshIdRouteImport.update({ path: '/fresh/$id', getParentRoute: () => rootRouteImport, } as any) +const CachedIdRoute = CachedIdRouteImport.update({ + id: '/cached/$id', + path: '/cached/$id', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -71,13 +71,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/deps': { id: '/deps' path: '/deps' @@ -85,11 +78,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof DepsRouteImport parentRoute: typeof rootRouteImport } - '/cached/$id': { - id: '/cached/$id' - path: '/cached/$id' - fullPath: '/cached/$id' - preLoaderRoute: typeof CachedIdRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } '/fresh/$id': { @@ -99,6 +92,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof FreshIdRouteImport parentRoute: typeof rootRouteImport } + '/cached/$id': { + id: '/cached/$id' + path: '/cached/$id' + fullPath: '/cached/$id' + preLoaderRoute: typeof CachedIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts b/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts index 6c3a64b026..2d675ff259 100644 --- a/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/mount/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-mount', async ({ bench }) => { - const scenario = setup() +describe('client-mount', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-mount loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts index 236f875f57..eaf7f1ed34 100644 --- a/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/mount/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-mount', async ({ bench }) => { - const scenario = setup() +describe('client-mount', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-mount loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/mount/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/mount/solid/src/routeTree.gen.ts index 30247636dd..dc0acc183d 100644 --- a/benchmarks/client-nav/scenarios/mount/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/mount/solid/src/routeTree.gen.ts @@ -9,35 +9,20 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as 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 SettingsRouteImport } from './routes/settings' +import { Route as SearchRouteImport } from './routes/search' +import { Route as BlogRouteImport } from './routes/blog' +import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' import { Route as ShopIndexRouteImport } from './routes/shop.index' +import { Route as BlogIndexRouteImport } from './routes/blog.index' import { Route as ShopProductIdRouteImport } from './routes/shop.$productId' +import { Route as BlogSlugRouteImport } from './routes/blog.$slug' -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', +const ShopRoute = ShopRouteImport.update({ + id: '/shop', + path: '/shop', getParentRoute: () => rootRouteImport, } as any) const SettingsRoute = SettingsRouteImport.update({ @@ -45,31 +30,46 @@ const SettingsRoute = SettingsRouteImport.update({ path: '/settings', getParentRoute: () => rootRouteImport, } as any) -const ShopRoute = ShopRouteImport.update({ - id: '/shop', - path: '/shop', +const SearchRoute = SearchRouteImport.update({ + id: '/search', + path: '/search', getParentRoute: () => rootRouteImport, } as any) -const BlogIndexRoute = BlogIndexRouteImport.update({ +const BlogRoute = BlogRouteImport.update({ + id: '/blog', + path: '/blog', + getParentRoute: () => rootRouteImport, +} as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => BlogRoute, -} as any) -const BlogSlugRoute = BlogSlugRouteImport.update({ - id: '/$slug', - path: '/$slug', - getParentRoute: () => BlogRoute, + getParentRoute: () => rootRouteImport, } as any) const ShopIndexRoute = ShopIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => ShopRoute, } as any) +const BlogIndexRoute = BlogIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => BlogRoute, +} as any) const ShopProductIdRoute = ShopProductIdRouteImport.update({ id: '/$productId', path: '/$productId', getParentRoute: () => ShopRoute, } as any) +const BlogSlugRoute = BlogSlugRouteImport.update({ + id: '/$slug', + path: '/$slug', + getParentRoute: () => BlogRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -154,32 +154,11 @@ export interface RootRouteChildren { 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 + '/shop': { + id: '/shop' + path: '/shop' + fullPath: '/shop' + preLoaderRoute: typeof ShopRouteImport parentRoute: typeof rootRouteImport } '/settings': { @@ -189,26 +168,33 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof SettingsRouteImport parentRoute: typeof rootRouteImport } - '/shop': { - id: '/shop' - path: '/shop' - fullPath: '/shop' - preLoaderRoute: typeof ShopRouteImport + '/search': { + id: '/search' + path: '/search' + fullPath: '/search' + preLoaderRoute: typeof SearchRouteImport parentRoute: typeof rootRouteImport } - '/blog/': { - id: '/blog/' - path: '/' - fullPath: '/blog/' - preLoaderRoute: typeof BlogIndexRouteImport - parentRoute: typeof BlogRoute + '/blog': { + id: '/blog' + path: '/blog' + fullPath: '/blog' + preLoaderRoute: typeof BlogRouteImport + parentRoute: typeof rootRouteImport } - '/blog/$slug': { - id: '/blog/$slug' - path: '/$slug' - fullPath: '/blog/$slug' - preLoaderRoute: typeof BlogSlugRouteImport - parentRoute: typeof BlogRoute + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/shop/': { id: '/shop/' @@ -217,6 +203,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ShopIndexRouteImport parentRoute: typeof ShopRoute } + '/blog/': { + id: '/blog/' + path: '/' + fullPath: '/blog/' + preLoaderRoute: typeof BlogIndexRouteImport + parentRoute: typeof BlogRoute + } '/shop/$productId': { id: '/shop/$productId' path: '/$productId' @@ -224,6 +217,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof ShopProductIdRouteImport parentRoute: typeof ShopRoute } + '/blog/$slug': { + id: '/blog/$slug' + path: '/$slug' + fullPath: '/blog/$slug' + preLoaderRoute: typeof BlogSlugRouteImport + parentRoute: typeof BlogRoute + } } } diff --git a/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts index d9268ba91b..f5538dd49c 100644 --- a/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/mount/vue/speed.bench.ts @@ -1,15 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-mount', async ({ bench }) => { - const scenario = setup() +describe('client-mount', () => { + const test = 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) + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( + 'client-mount loop (vue)', + async () => { + for (let i = 0; i < ticksPerIteration; i++) { + await test.tick() + } + await test.finishBatch() + }, + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/mount/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/mount/vue/src/routeTree.gen.ts index cd27c917e1..98643d63c9 100644 --- a/benchmarks/client-nav/scenarios/mount/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/mount/vue/src/routeTree.gen.ts @@ -9,35 +9,20 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as 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 SettingsRouteImport } from './routes/settings' +import { Route as SearchRouteImport } from './routes/search' +import { Route as BlogRouteImport } from './routes/blog' +import { Route as AboutRouteImport } from './routes/about' +import { Route as IndexRouteImport } from './routes/index' import { Route as ShopIndexRouteImport } from './routes/shop.index' +import { Route as BlogIndexRouteImport } from './routes/blog.index' import { Route as ShopProductIdRouteImport } from './routes/shop.$productId' +import { Route as BlogSlugRouteImport } from './routes/blog.$slug' -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', +const ShopRoute = ShopRouteImport.update({ + id: '/shop', + path: '/shop', getParentRoute: () => rootRouteImport, } as any) const SettingsRoute = SettingsRouteImport.update({ @@ -45,31 +30,46 @@ const SettingsRoute = SettingsRouteImport.update({ path: '/settings', getParentRoute: () => rootRouteImport, } as any) -const ShopRoute = ShopRouteImport.update({ - id: '/shop', - path: '/shop', +const SearchRoute = SearchRouteImport.update({ + id: '/search', + path: '/search', getParentRoute: () => rootRouteImport, } as any) -const BlogIndexRoute = BlogIndexRouteImport.update({ +const BlogRoute = BlogRouteImport.update({ + id: '/blog', + path: '/blog', + getParentRoute: () => rootRouteImport, +} as any) +const AboutRoute = AboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', - getParentRoute: () => BlogRoute, -} as any) -const BlogSlugRoute = BlogSlugRouteImport.update({ - id: '/$slug', - path: '/$slug', - getParentRoute: () => BlogRoute, + getParentRoute: () => rootRouteImport, } as any) const ShopIndexRoute = ShopIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => ShopRoute, } as any) +const BlogIndexRoute = BlogIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => BlogRoute, +} as any) const ShopProductIdRoute = ShopProductIdRouteImport.update({ id: '/$productId', path: '/$productId', getParentRoute: () => ShopRoute, } as any) +const BlogSlugRoute = BlogSlugRouteImport.update({ + id: '/$slug', + path: '/$slug', + getParentRoute: () => BlogRoute, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -154,32 +154,11 @@ export interface RootRouteChildren { 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 + '/shop': { + id: '/shop' + path: '/shop' + fullPath: '/shop' + preLoaderRoute: typeof ShopRouteImport parentRoute: typeof rootRouteImport } '/settings': { @@ -189,26 +168,33 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof SettingsRouteImport parentRoute: typeof rootRouteImport } - '/shop': { - id: '/shop' - path: '/shop' - fullPath: '/shop' - preLoaderRoute: typeof ShopRouteImport + '/search': { + id: '/search' + path: '/search' + fullPath: '/search' + preLoaderRoute: typeof SearchRouteImport parentRoute: typeof rootRouteImport } - '/blog/': { - id: '/blog/' - path: '/' - fullPath: '/blog/' - preLoaderRoute: typeof BlogIndexRouteImport - parentRoute: typeof BlogRoute + '/blog': { + id: '/blog' + path: '/blog' + fullPath: '/blog' + preLoaderRoute: typeof BlogRouteImport + parentRoute: typeof rootRouteImport } - '/blog/$slug': { - id: '/blog/$slug' - path: '/$slug' - fullPath: '/blog/$slug' - preLoaderRoute: typeof BlogSlugRouteImport - parentRoute: typeof BlogRoute + '/about': { + id: '/about' + path: '/about' + fullPath: '/about' + preLoaderRoute: typeof AboutRouteImport + parentRoute: typeof rootRouteImport + } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/shop/': { id: '/shop/' @@ -217,6 +203,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ShopIndexRouteImport parentRoute: typeof ShopRoute } + '/blog/': { + id: '/blog/' + path: '/' + fullPath: '/blog/' + preLoaderRoute: typeof BlogIndexRouteImport + parentRoute: typeof BlogRoute + } '/shop/$productId': { id: '/shop/$productId' path: '/$productId' @@ -224,6 +217,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof ShopProductIdRouteImport parentRoute: typeof ShopRoute } + '/blog/$slug': { + id: '/blog/$slug' + path: '/$slug' + fullPath: '/blog/$slug' + preLoaderRoute: typeof BlogSlugRouteImport + parentRoute: typeof BlogRoute + } } } diff --git a/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts b/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts index fa5809c1fd..3dfe93c117 100644 --- a/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/nested-params/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-nested-params', async ({ bench }) => { - const scenario = setup() +describe('client-nested-params', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-nested-params navigation loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts index 2c64d9a221..dc7ec11f6b 100644 --- a/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/nested-params/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-nested-params', async ({ bench }) => { - const scenario = setup() +describe('client-nested-params', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-nested-params navigation loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts index bd3e82e070..fcb336d1db 100644 --- a/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/nested-params/vue/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-nested-params', async ({ bench }) => { - const scenario = setup() +describe('client-nested-params', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-nested-params navigation loop (vue)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts b/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts index 5c210b2fd7..5b188a0a0b 100644 --- a/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/preload/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-preload', async ({ bench }) => { - const scenario = setup() +describe('client-preload', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-preload interaction loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts index f835b4a7b9..267c9fd41d 100644 --- a/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/preload/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-preload', async ({ bench }) => { - const scenario = setup() +describe('client-preload', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-preload interaction loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/preload/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/preload/solid/src/routeTree.gen.ts index 97e215b6da..645d925238 100644 --- a/benchmarks/client-nav/scenarios/preload/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/preload/solid/src/routeTree.gen.ts @@ -9,20 +9,20 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as DocsRouteImport } from './routes/docs' +import { Route as IndexRouteImport } from './routes/index' 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 IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const SectionsSectionRoute = SectionsSectionRouteImport.update({ id: '/sections/$section', path: '/sections/$section', @@ -61,13 +61,6 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/docs': { id: '/docs' path: '/docs' @@ -75,6 +68,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof DocsRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/sections/$section': { id: '/sections/$section' path: '/sections/$section' diff --git a/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts index e0ec83619b..38a2e9e664 100644 --- a/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/preload/vue/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-preload', async ({ bench }) => { - const scenario = setup() +describe('client-preload', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-preload interaction loop (vue)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/preload/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/preload/vue/src/routeTree.gen.ts index 5f95d09da0..05a751060b 100644 --- a/benchmarks/client-nav/scenarios/preload/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/preload/vue/src/routeTree.gen.ts @@ -9,20 +9,20 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' import { Route as DocsRouteImport } from './routes/docs' +import { Route as IndexRouteImport } from './routes/index' 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 IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) const SectionsSectionRoute = SectionsSectionRouteImport.update({ id: '/sections/$section', path: '/sections/$section', @@ -61,13 +61,6 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport - parentRoute: typeof rootRouteImport - } '/docs': { id: '/docs' path: '/docs' @@ -75,6 +68,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof DocsRouteImport parentRoute: typeof rootRouteImport } + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } '/sections/$section': { id: '/sections/$section' path: '/sections/$section' diff --git a/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts b/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts index dd1b6f3686..8e79c6db7e 100644 --- a/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/rewrites/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-rewrites', async ({ bench }) => { - const scenario = setup() +describe('client-rewrites', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-rewrites navigation loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts index 9c4313e2ff..cf70bcaa40 100644 --- a/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/rewrites/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-rewrites', async ({ bench }) => { - const scenario = setup() +describe('client-rewrites', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-rewrites navigation loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts index e96aff39eb..2dc9eb2679 100644 --- a/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/rewrites/vue/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-rewrites', async ({ bench }) => { - const scenario = setup() +describe('client-rewrites', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-rewrites navigation loop (vue)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.bench.ts b/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.bench.ts index 6f4b448775..337ba35b73 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/route-tree-scale/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-route-tree-scale', async ({ bench }) => { - const scenario = setup() +describe('client-route-tree-scale', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-route-tree-scale navigation loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.bench.ts index 9244ef1350..545b501617 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-route-tree-scale', async ({ bench }) => { - const scenario = setup() +describe('client-route-tree-scale', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-route-tree-scale navigation loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts index e6f3596562..20b4af6146 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/route-tree-scale/solid/src/routeTree.gen.ts @@ -9,72 +9,48 @@ // Additionally, you should also exclude this file 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 SecERouteImport } from './routes/sec-e' +import { Route as SecDRouteImport } from './routes/sec-d' +import { Route as SecCRouteImport } from './routes/sec-c' +import { Route as SecBRouteImport } from './routes/sec-b' +import { Route as SecARouteImport } from './routes/sec-a' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as IndexRouteImport } from './routes/index' import { Route as SecFIndexRouteImport } from './routes/sec-f.index' -import { Route as SecFIdRouteImport } from './routes/sec-f.$id' -import { Route as SecFAboutRouteImport } from './routes/sec-f.about' +import { Route as SecEIndexRouteImport } from './routes/sec-e.index' +import { Route as SecDIndexRouteImport } from './routes/sec-d.index' +import { Route as SecCIndexRouteImport } from './routes/sec-c.index' +import { Route as SecBIndexRouteImport } from './routes/sec-b.index' +import { Route as SecAIndexRouteImport } from './routes/sec-a.index' import { Route as SecFSettingsRouteImport } from './routes/sec-f.settings' +import { Route as SecFAboutRouteImport } from './routes/sec-f.about' +import { Route as SecFIdRouteImport } from './routes/sec-f.$id' +import { Route as SecESettingsRouteImport } from './routes/sec-e.settings' +import { Route as SecEAboutRouteImport } from './routes/sec-e.about' +import { Route as SecEIdRouteImport } from './routes/sec-e.$id' +import { Route as SecDSettingsRouteImport } from './routes/sec-d.settings' +import { Route as SecDAboutRouteImport } from './routes/sec-d.about' +import { Route as SecDIdRouteImport } from './routes/sec-d.$id' +import { Route as SecCSettingsRouteImport } from './routes/sec-c.settings' +import { Route as SecCAboutRouteImport } from './routes/sec-c.about' +import { Route as SecCIdRouteImport } from './routes/sec-c.$id' +import { Route as SecBSettingsRouteImport } from './routes/sec-b.settings' +import { Route as SecBAboutRouteImport } from './routes/sec-b.about' +import { Route as SecBIdRouteImport } from './routes/sec-b.$id' +import { Route as SecASettingsRouteImport } from './routes/sec-a.settings' +import { Route as SecAAboutRouteImport } from './routes/sec-a.about' +import { Route as SecAIdRouteImport } from './routes/sec-a.$id' +import { Route as ReleaseVChar123versionChar125RouteImport } from './routes/release.v{$version}' +import { Route as FilesSplatRouteImport } from './routes/files.$' +import { Route as LayoutBetaRouteImport } from './routes/_layout.beta' +import { Route as LayoutAlphaRouteImport } from './routes/_layout.alpha' +import { Route as marketingPromoRouteImport } from './routes/(marketing)/promo' +import { Route as marketingPricingRouteImport } from './routes/(marketing)/pricing' -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', +const SecFRoute = SecFRouteImport.update({ + id: '/sec-f', + path: '/sec-f', getParentRoute: () => rootRouteImport, } as any) const SecERoute = SecERouteImport.update({ @@ -82,150 +58,68 @@ const SecERoute = SecERouteImport.update({ path: '/sec-e', getParentRoute: () => rootRouteImport, } as any) -const SecFRoute = SecFRouteImport.update({ - id: '/sec-f', - path: '/sec-f', +const SecDRoute = SecDRouteImport.update({ + id: '/sec-d', + path: '/sec-d', getParentRoute: () => rootRouteImport, } as any) -const marketingPricingRoute = marketingPricingRouteImport.update({ - id: '/(marketing)/pricing', - path: '/pricing', +const SecCRoute = SecCRouteImport.update({ + id: '/sec-c', + path: '/sec-c', getParentRoute: () => rootRouteImport, } as any) -const marketingPromoRoute = marketingPromoRouteImport.update({ - id: '/(marketing)/promo', - path: '/promo', +const SecBRoute = SecBRouteImport.update({ + id: '/sec-b', + path: '/sec-b', 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/$', +const SecARoute = SecARouteImport.update({ + id: '/sec-a', + path: '/sec-a', getParentRoute: () => rootRouteImport, } as any) -const ReleaseVChar123versionChar125Route = - ReleaseVChar123versionChar125RouteImport.update({ - id: '/release/v{$version}', - path: '/release/v{$version}', - getParentRoute: () => rootRouteImport, - } as any) -const SecAIndexRoute = SecAIndexRouteImport.update({ +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.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, + getParentRoute: () => rootRouteImport, } as any) const SecFIndexRoute = SecFIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => SecFRoute, } as any) -const SecFIdRoute = SecFIdRouteImport.update({ - id: '/$id', - path: '/$id', +const SecEIndexRoute = SecEIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecERoute, +} as any) +const SecDIndexRoute = SecDIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecDRoute, +} as any) +const SecCIndexRoute = SecCIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecCRoute, +} as any) +const SecBIndexRoute = SecBIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecBRoute, +} as any) +const SecAIndexRoute = SecAIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecARoute, +} as any) +const SecFSettingsRoute = SecFSettingsRouteImport.update({ + id: '/settings', + path: '/settings', getParentRoute: () => SecFRoute, } as any) const SecFAboutRoute = SecFAboutRouteImport.update({ @@ -233,10 +127,116 @@ const SecFAboutRoute = SecFAboutRouteImport.update({ path: '/about', getParentRoute: () => SecFRoute, } as any) -const SecFSettingsRoute = SecFSettingsRouteImport.update({ +const SecFIdRoute = SecFIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecFRoute, +} as any) +const SecESettingsRoute = SecESettingsRouteImport.update({ id: '/settings', path: '/settings', - getParentRoute: () => SecFRoute, + getParentRoute: () => SecERoute, +} as any) +const SecEAboutRoute = SecEAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecERoute, +} as any) +const SecEIdRoute = SecEIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecERoute, +} as any) +const SecDSettingsRoute = SecDSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecDRoute, +} as any) +const SecDAboutRoute = SecDAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecDRoute, +} as any) +const SecDIdRoute = SecDIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecDRoute, +} as any) +const SecCSettingsRoute = SecCSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecCRoute, +} as any) +const SecCAboutRoute = SecCAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecCRoute, +} as any) +const SecCIdRoute = SecCIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecCRoute, +} as any) +const SecBSettingsRoute = SecBSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecBRoute, +} as any) +const SecBAboutRoute = SecBAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecBRoute, +} as any) +const SecBIdRoute = SecBIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecBRoute, +} as any) +const SecASettingsRoute = SecASettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecARoute, +} as any) +const SecAAboutRoute = SecAAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecARoute, +} as any) +const SecAIdRoute = SecAIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecARoute, +} as any) +const ReleaseVChar123versionChar125Route = + ReleaseVChar123versionChar125RouteImport.update({ + id: '/release/v{$version}', + path: '/release/v{$version}', + getParentRoute: () => rootRouteImport, + } as any) +const FilesSplatRoute = FilesSplatRouteImport.update({ + id: '/files/$', + path: '/files/$', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutBetaRoute = LayoutBetaRouteImport.update({ + id: '/beta', + path: '/beta', + getParentRoute: () => LayoutRoute, +} as any) +const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ + id: '/alpha', + path: '/alpha', + getParentRoute: () => LayoutRoute, +} as any) +const marketingPromoRoute = marketingPromoRouteImport.update({ + id: '/(marketing)/promo', + path: '/promo', + getParentRoute: () => rootRouteImport, +} as any) +const marketingPricingRoute = marketingPricingRouteImport.update({ + id: '/(marketing)/pricing', + path: '/pricing', + getParentRoute: () => rootRouteImport, } as any) export interface FileRoutesByFullPath { @@ -484,46 +484,11 @@ export interface RootRouteChildren { 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 + '/sec-f': { + id: '/sec-f' + path: '/sec-f' + fullPath: '/sec-f' + preLoaderRoute: typeof SecFRouteImport parentRoute: typeof rootRouteImport } '/sec-e': { @@ -533,194 +498,47 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof SecERouteImport parentRoute: typeof rootRouteImport } - '/sec-f': { - id: '/sec-f' - path: '/sec-f' - fullPath: '/sec-f' - preLoaderRoute: typeof SecFRouteImport + '/sec-d': { + id: '/sec-d' + path: '/sec-d' + fullPath: '/sec-d' + preLoaderRoute: typeof SecDRouteImport parentRoute: typeof rootRouteImport } - '/(marketing)/pricing': { - id: '/(marketing)/pricing' - path: '/pricing' - fullPath: '/pricing' - preLoaderRoute: typeof marketingPricingRouteImport + '/sec-c': { + id: '/sec-c' + path: '/sec-c' + fullPath: '/sec-c' + preLoaderRoute: typeof SecCRouteImport parentRoute: typeof rootRouteImport } - '/(marketing)/promo': { - id: '/(marketing)/promo' - path: '/promo' - fullPath: '/promo' - preLoaderRoute: typeof marketingPromoRouteImport + '/sec-b': { + id: '/sec-b' + path: '/sec-b' + fullPath: '/sec-b' + preLoaderRoute: typeof SecBRouteImport 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 + '/sec-a': { + id: '/sec-a' + path: '/sec-a' + fullPath: '/sec-a' + preLoaderRoute: typeof SecARouteImport parentRoute: typeof rootRouteImport } - '/release/v{$version}': { - id: '/release/v{$version}' - path: '/release/v{$version}' - fullPath: '/release/v{$version}' - preLoaderRoute: typeof ReleaseVChar123versionChar125RouteImport + '/_layout': { + id: '/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/sec-a/': { - id: '/sec-a/' + '/': { + id: '/' 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 + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/sec-f/': { id: '/sec-f/' @@ -729,11 +547,46 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof SecFIndexRouteImport parentRoute: typeof SecFRoute } - '/sec-f/$id': { - id: '/sec-f/$id' - path: '/$id' - fullPath: '/sec-f/$id' - preLoaderRoute: typeof SecFIdRouteImport + '/sec-e/': { + id: '/sec-e/' + path: '/' + fullPath: '/sec-e/' + preLoaderRoute: typeof SecEIndexRouteImport + parentRoute: typeof SecERoute + } + '/sec-d/': { + id: '/sec-d/' + path: '/' + fullPath: '/sec-d/' + preLoaderRoute: typeof SecDIndexRouteImport + parentRoute: typeof SecDRoute + } + '/sec-c/': { + id: '/sec-c/' + path: '/' + fullPath: '/sec-c/' + preLoaderRoute: typeof SecCIndexRouteImport + parentRoute: typeof SecCRoute + } + '/sec-b/': { + id: '/sec-b/' + path: '/' + fullPath: '/sec-b/' + preLoaderRoute: typeof SecBIndexRouteImport + parentRoute: typeof SecBRoute + } + '/sec-a/': { + id: '/sec-a/' + path: '/' + fullPath: '/sec-a/' + preLoaderRoute: typeof SecAIndexRouteImport + parentRoute: typeof SecARoute + } + '/sec-f/settings': { + id: '/sec-f/settings' + path: '/settings' + fullPath: '/sec-f/settings' + preLoaderRoute: typeof SecFSettingsRouteImport parentRoute: typeof SecFRoute } '/sec-f/about': { @@ -743,13 +596,160 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof SecFAboutRouteImport parentRoute: typeof SecFRoute } - '/sec-f/settings': { - id: '/sec-f/settings' - path: '/settings' - fullPath: '/sec-f/settings' - preLoaderRoute: typeof SecFSettingsRouteImport + '/sec-f/$id': { + id: '/sec-f/$id' + path: '/$id' + fullPath: '/sec-f/$id' + preLoaderRoute: typeof SecFIdRouteImport parentRoute: typeof SecFRoute } + '/sec-e/settings': { + id: '/sec-e/settings' + path: '/settings' + fullPath: '/sec-e/settings' + preLoaderRoute: typeof SecESettingsRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/about': { + id: '/sec-e/about' + path: '/about' + fullPath: '/sec-e/about' + preLoaderRoute: typeof SecEAboutRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/$id': { + id: '/sec-e/$id' + path: '/$id' + fullPath: '/sec-e/$id' + preLoaderRoute: typeof SecEIdRouteImport + parentRoute: typeof SecERoute + } + '/sec-d/settings': { + id: '/sec-d/settings' + path: '/settings' + fullPath: '/sec-d/settings' + preLoaderRoute: typeof SecDSettingsRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/about': { + id: '/sec-d/about' + path: '/about' + fullPath: '/sec-d/about' + preLoaderRoute: typeof SecDAboutRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/$id': { + id: '/sec-d/$id' + path: '/$id' + fullPath: '/sec-d/$id' + preLoaderRoute: typeof SecDIdRouteImport + parentRoute: typeof SecDRoute + } + '/sec-c/settings': { + id: '/sec-c/settings' + path: '/settings' + fullPath: '/sec-c/settings' + preLoaderRoute: typeof SecCSettingsRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/about': { + id: '/sec-c/about' + path: '/about' + fullPath: '/sec-c/about' + preLoaderRoute: typeof SecCAboutRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/$id': { + id: '/sec-c/$id' + path: '/$id' + fullPath: '/sec-c/$id' + preLoaderRoute: typeof SecCIdRouteImport + parentRoute: typeof SecCRoute + } + '/sec-b/settings': { + id: '/sec-b/settings' + path: '/settings' + fullPath: '/sec-b/settings' + preLoaderRoute: typeof SecBSettingsRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/about': { + id: '/sec-b/about' + path: '/about' + fullPath: '/sec-b/about' + preLoaderRoute: typeof SecBAboutRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/$id': { + id: '/sec-b/$id' + path: '/$id' + fullPath: '/sec-b/$id' + preLoaderRoute: typeof SecBIdRouteImport + parentRoute: typeof SecBRoute + } + '/sec-a/settings': { + id: '/sec-a/settings' + path: '/settings' + fullPath: '/sec-a/settings' + preLoaderRoute: typeof SecASettingsRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/about': { + id: '/sec-a/about' + path: '/about' + fullPath: '/sec-a/about' + preLoaderRoute: typeof SecAAboutRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/$id': { + id: '/sec-a/$id' + path: '/$id' + fullPath: '/sec-a/$id' + preLoaderRoute: typeof SecAIdRouteImport + parentRoute: typeof SecARoute + } + '/release/v{$version}': { + id: '/release/v{$version}' + path: '/release/v{$version}' + fullPath: '/release/v{$version}' + preLoaderRoute: typeof ReleaseVChar123versionChar125RouteImport + parentRoute: typeof rootRouteImport + } + '/files/$': { + id: '/files/$' + path: '/files/$' + fullPath: '/files/$' + preLoaderRoute: typeof FilesSplatRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/beta': { + id: '/_layout/beta' + path: '/beta' + fullPath: '/beta' + preLoaderRoute: typeof LayoutBetaRouteImport + parentRoute: typeof LayoutRoute + } + '/_layout/alpha': { + id: '/_layout/alpha' + path: '/alpha' + fullPath: '/alpha' + preLoaderRoute: typeof LayoutAlphaRouteImport + parentRoute: typeof LayoutRoute + } + '/(marketing)/promo': { + id: '/(marketing)/promo' + path: '/promo' + fullPath: '/promo' + preLoaderRoute: typeof marketingPromoRouteImport + parentRoute: typeof rootRouteImport + } + '/(marketing)/pricing': { + id: '/(marketing)/pricing' + path: '/pricing' + fullPath: '/pricing' + preLoaderRoute: typeof marketingPricingRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.bench.ts index 331e8e008f..9365231579 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-route-tree-scale', async ({ bench }) => { - const scenario = setup() +describe('client-route-tree-scale', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-route-tree-scale navigation loop (vue)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts index a12f981bb4..a03c051a79 100644 --- a/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/route-tree-scale/vue/src/routeTree.gen.ts @@ -9,72 +9,48 @@ // Additionally, you should also exclude this file 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 SecERouteImport } from './routes/sec-e' +import { Route as SecDRouteImport } from './routes/sec-d' +import { Route as SecCRouteImport } from './routes/sec-c' +import { Route as SecBRouteImport } from './routes/sec-b' +import { Route as SecARouteImport } from './routes/sec-a' +import { Route as LayoutRouteImport } from './routes/_layout' +import { Route as IndexRouteImport } from './routes/index' import { Route as SecFIndexRouteImport } from './routes/sec-f.index' -import { Route as SecFIdRouteImport } from './routes/sec-f.$id' -import { Route as SecFAboutRouteImport } from './routes/sec-f.about' +import { Route as SecEIndexRouteImport } from './routes/sec-e.index' +import { Route as SecDIndexRouteImport } from './routes/sec-d.index' +import { Route as SecCIndexRouteImport } from './routes/sec-c.index' +import { Route as SecBIndexRouteImport } from './routes/sec-b.index' +import { Route as SecAIndexRouteImport } from './routes/sec-a.index' import { Route as SecFSettingsRouteImport } from './routes/sec-f.settings' +import { Route as SecFAboutRouteImport } from './routes/sec-f.about' +import { Route as SecFIdRouteImport } from './routes/sec-f.$id' +import { Route as SecESettingsRouteImport } from './routes/sec-e.settings' +import { Route as SecEAboutRouteImport } from './routes/sec-e.about' +import { Route as SecEIdRouteImport } from './routes/sec-e.$id' +import { Route as SecDSettingsRouteImport } from './routes/sec-d.settings' +import { Route as SecDAboutRouteImport } from './routes/sec-d.about' +import { Route as SecDIdRouteImport } from './routes/sec-d.$id' +import { Route as SecCSettingsRouteImport } from './routes/sec-c.settings' +import { Route as SecCAboutRouteImport } from './routes/sec-c.about' +import { Route as SecCIdRouteImport } from './routes/sec-c.$id' +import { Route as SecBSettingsRouteImport } from './routes/sec-b.settings' +import { Route as SecBAboutRouteImport } from './routes/sec-b.about' +import { Route as SecBIdRouteImport } from './routes/sec-b.$id' +import { Route as SecASettingsRouteImport } from './routes/sec-a.settings' +import { Route as SecAAboutRouteImport } from './routes/sec-a.about' +import { Route as SecAIdRouteImport } from './routes/sec-a.$id' +import { Route as ReleaseVChar123versionChar125RouteImport } from './routes/release.v{$version}' +import { Route as FilesSplatRouteImport } from './routes/files.$' +import { Route as LayoutBetaRouteImport } from './routes/_layout.beta' +import { Route as LayoutAlphaRouteImport } from './routes/_layout.alpha' +import { Route as marketingPromoRouteImport } from './routes/(marketing)/promo' +import { Route as marketingPricingRouteImport } from './routes/(marketing)/pricing' -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', +const SecFRoute = SecFRouteImport.update({ + id: '/sec-f', + path: '/sec-f', getParentRoute: () => rootRouteImport, } as any) const SecERoute = SecERouteImport.update({ @@ -82,150 +58,68 @@ const SecERoute = SecERouteImport.update({ path: '/sec-e', getParentRoute: () => rootRouteImport, } as any) -const SecFRoute = SecFRouteImport.update({ - id: '/sec-f', - path: '/sec-f', +const SecDRoute = SecDRouteImport.update({ + id: '/sec-d', + path: '/sec-d', getParentRoute: () => rootRouteImport, } as any) -const marketingPricingRoute = marketingPricingRouteImport.update({ - id: '/(marketing)/pricing', - path: '/pricing', +const SecCRoute = SecCRouteImport.update({ + id: '/sec-c', + path: '/sec-c', getParentRoute: () => rootRouteImport, } as any) -const marketingPromoRoute = marketingPromoRouteImport.update({ - id: '/(marketing)/promo', - path: '/promo', +const SecBRoute = SecBRouteImport.update({ + id: '/sec-b', + path: '/sec-b', 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/$', +const SecARoute = SecARouteImport.update({ + id: '/sec-a', + path: '/sec-a', getParentRoute: () => rootRouteImport, } as any) -const ReleaseVChar123versionChar125Route = - ReleaseVChar123versionChar125RouteImport.update({ - id: '/release/v{$version}', - path: '/release/v{$version}', - getParentRoute: () => rootRouteImport, - } as any) -const SecAIndexRoute = SecAIndexRouteImport.update({ +const LayoutRoute = LayoutRouteImport.update({ + id: '/_layout', + getParentRoute: () => rootRouteImport, +} as any) +const IndexRoute = IndexRouteImport.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, + getParentRoute: () => rootRouteImport, } as any) const SecFIndexRoute = SecFIndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => SecFRoute, } as any) -const SecFIdRoute = SecFIdRouteImport.update({ - id: '/$id', - path: '/$id', +const SecEIndexRoute = SecEIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecERoute, +} as any) +const SecDIndexRoute = SecDIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecDRoute, +} as any) +const SecCIndexRoute = SecCIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecCRoute, +} as any) +const SecBIndexRoute = SecBIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecBRoute, +} as any) +const SecAIndexRoute = SecAIndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => SecARoute, +} as any) +const SecFSettingsRoute = SecFSettingsRouteImport.update({ + id: '/settings', + path: '/settings', getParentRoute: () => SecFRoute, } as any) const SecFAboutRoute = SecFAboutRouteImport.update({ @@ -233,10 +127,116 @@ const SecFAboutRoute = SecFAboutRouteImport.update({ path: '/about', getParentRoute: () => SecFRoute, } as any) -const SecFSettingsRoute = SecFSettingsRouteImport.update({ +const SecFIdRoute = SecFIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecFRoute, +} as any) +const SecESettingsRoute = SecESettingsRouteImport.update({ id: '/settings', path: '/settings', - getParentRoute: () => SecFRoute, + getParentRoute: () => SecERoute, +} as any) +const SecEAboutRoute = SecEAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecERoute, +} as any) +const SecEIdRoute = SecEIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecERoute, +} as any) +const SecDSettingsRoute = SecDSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecDRoute, +} as any) +const SecDAboutRoute = SecDAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecDRoute, +} as any) +const SecDIdRoute = SecDIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecDRoute, +} as any) +const SecCSettingsRoute = SecCSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecCRoute, +} as any) +const SecCAboutRoute = SecCAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecCRoute, +} as any) +const SecCIdRoute = SecCIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecCRoute, +} as any) +const SecBSettingsRoute = SecBSettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecBRoute, +} as any) +const SecBAboutRoute = SecBAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecBRoute, +} as any) +const SecBIdRoute = SecBIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecBRoute, +} as any) +const SecASettingsRoute = SecASettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => SecARoute, +} as any) +const SecAAboutRoute = SecAAboutRouteImport.update({ + id: '/about', + path: '/about', + getParentRoute: () => SecARoute, +} as any) +const SecAIdRoute = SecAIdRouteImport.update({ + id: '/$id', + path: '/$id', + getParentRoute: () => SecARoute, +} as any) +const ReleaseVChar123versionChar125Route = + ReleaseVChar123versionChar125RouteImport.update({ + id: '/release/v{$version}', + path: '/release/v{$version}', + getParentRoute: () => rootRouteImport, + } as any) +const FilesSplatRoute = FilesSplatRouteImport.update({ + id: '/files/$', + path: '/files/$', + getParentRoute: () => rootRouteImport, +} as any) +const LayoutBetaRoute = LayoutBetaRouteImport.update({ + id: '/beta', + path: '/beta', + getParentRoute: () => LayoutRoute, +} as any) +const LayoutAlphaRoute = LayoutAlphaRouteImport.update({ + id: '/alpha', + path: '/alpha', + getParentRoute: () => LayoutRoute, +} as any) +const marketingPromoRoute = marketingPromoRouteImport.update({ + id: '/(marketing)/promo', + path: '/promo', + getParentRoute: () => rootRouteImport, +} as any) +const marketingPricingRoute = marketingPricingRouteImport.update({ + id: '/(marketing)/pricing', + path: '/pricing', + getParentRoute: () => rootRouteImport, } as any) export interface FileRoutesByFullPath { @@ -484,46 +484,11 @@ export interface RootRouteChildren { 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 + '/sec-f': { + id: '/sec-f' + path: '/sec-f' + fullPath: '/sec-f' + preLoaderRoute: typeof SecFRouteImport parentRoute: typeof rootRouteImport } '/sec-e': { @@ -533,194 +498,47 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof SecERouteImport parentRoute: typeof rootRouteImport } - '/sec-f': { - id: '/sec-f' - path: '/sec-f' - fullPath: '/sec-f' - preLoaderRoute: typeof SecFRouteImport + '/sec-d': { + id: '/sec-d' + path: '/sec-d' + fullPath: '/sec-d' + preLoaderRoute: typeof SecDRouteImport parentRoute: typeof rootRouteImport } - '/(marketing)/pricing': { - id: '/(marketing)/pricing' - path: '/pricing' - fullPath: '/pricing' - preLoaderRoute: typeof marketingPricingRouteImport + '/sec-c': { + id: '/sec-c' + path: '/sec-c' + fullPath: '/sec-c' + preLoaderRoute: typeof SecCRouteImport parentRoute: typeof rootRouteImport } - '/(marketing)/promo': { - id: '/(marketing)/promo' - path: '/promo' - fullPath: '/promo' - preLoaderRoute: typeof marketingPromoRouteImport + '/sec-b': { + id: '/sec-b' + path: '/sec-b' + fullPath: '/sec-b' + preLoaderRoute: typeof SecBRouteImport 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 + '/sec-a': { + id: '/sec-a' + path: '/sec-a' + fullPath: '/sec-a' + preLoaderRoute: typeof SecARouteImport parentRoute: typeof rootRouteImport } - '/release/v{$version}': { - id: '/release/v{$version}' - path: '/release/v{$version}' - fullPath: '/release/v{$version}' - preLoaderRoute: typeof ReleaseVChar123versionChar125RouteImport + '/_layout': { + id: '/_layout' + path: '' + fullPath: '/' + preLoaderRoute: typeof LayoutRouteImport parentRoute: typeof rootRouteImport } - '/sec-a/': { - id: '/sec-a/' + '/': { + id: '/' 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 + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport } '/sec-f/': { id: '/sec-f/' @@ -729,11 +547,46 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof SecFIndexRouteImport parentRoute: typeof SecFRoute } - '/sec-f/$id': { - id: '/sec-f/$id' - path: '/$id' - fullPath: '/sec-f/$id' - preLoaderRoute: typeof SecFIdRouteImport + '/sec-e/': { + id: '/sec-e/' + path: '/' + fullPath: '/sec-e/' + preLoaderRoute: typeof SecEIndexRouteImport + parentRoute: typeof SecERoute + } + '/sec-d/': { + id: '/sec-d/' + path: '/' + fullPath: '/sec-d/' + preLoaderRoute: typeof SecDIndexRouteImport + parentRoute: typeof SecDRoute + } + '/sec-c/': { + id: '/sec-c/' + path: '/' + fullPath: '/sec-c/' + preLoaderRoute: typeof SecCIndexRouteImport + parentRoute: typeof SecCRoute + } + '/sec-b/': { + id: '/sec-b/' + path: '/' + fullPath: '/sec-b/' + preLoaderRoute: typeof SecBIndexRouteImport + parentRoute: typeof SecBRoute + } + '/sec-a/': { + id: '/sec-a/' + path: '/' + fullPath: '/sec-a/' + preLoaderRoute: typeof SecAIndexRouteImport + parentRoute: typeof SecARoute + } + '/sec-f/settings': { + id: '/sec-f/settings' + path: '/settings' + fullPath: '/sec-f/settings' + preLoaderRoute: typeof SecFSettingsRouteImport parentRoute: typeof SecFRoute } '/sec-f/about': { @@ -743,13 +596,160 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof SecFAboutRouteImport parentRoute: typeof SecFRoute } - '/sec-f/settings': { - id: '/sec-f/settings' - path: '/settings' - fullPath: '/sec-f/settings' - preLoaderRoute: typeof SecFSettingsRouteImport + '/sec-f/$id': { + id: '/sec-f/$id' + path: '/$id' + fullPath: '/sec-f/$id' + preLoaderRoute: typeof SecFIdRouteImport parentRoute: typeof SecFRoute } + '/sec-e/settings': { + id: '/sec-e/settings' + path: '/settings' + fullPath: '/sec-e/settings' + preLoaderRoute: typeof SecESettingsRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/about': { + id: '/sec-e/about' + path: '/about' + fullPath: '/sec-e/about' + preLoaderRoute: typeof SecEAboutRouteImport + parentRoute: typeof SecERoute + } + '/sec-e/$id': { + id: '/sec-e/$id' + path: '/$id' + fullPath: '/sec-e/$id' + preLoaderRoute: typeof SecEIdRouteImport + parentRoute: typeof SecERoute + } + '/sec-d/settings': { + id: '/sec-d/settings' + path: '/settings' + fullPath: '/sec-d/settings' + preLoaderRoute: typeof SecDSettingsRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/about': { + id: '/sec-d/about' + path: '/about' + fullPath: '/sec-d/about' + preLoaderRoute: typeof SecDAboutRouteImport + parentRoute: typeof SecDRoute + } + '/sec-d/$id': { + id: '/sec-d/$id' + path: '/$id' + fullPath: '/sec-d/$id' + preLoaderRoute: typeof SecDIdRouteImport + parentRoute: typeof SecDRoute + } + '/sec-c/settings': { + id: '/sec-c/settings' + path: '/settings' + fullPath: '/sec-c/settings' + preLoaderRoute: typeof SecCSettingsRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/about': { + id: '/sec-c/about' + path: '/about' + fullPath: '/sec-c/about' + preLoaderRoute: typeof SecCAboutRouteImport + parentRoute: typeof SecCRoute + } + '/sec-c/$id': { + id: '/sec-c/$id' + path: '/$id' + fullPath: '/sec-c/$id' + preLoaderRoute: typeof SecCIdRouteImport + parentRoute: typeof SecCRoute + } + '/sec-b/settings': { + id: '/sec-b/settings' + path: '/settings' + fullPath: '/sec-b/settings' + preLoaderRoute: typeof SecBSettingsRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/about': { + id: '/sec-b/about' + path: '/about' + fullPath: '/sec-b/about' + preLoaderRoute: typeof SecBAboutRouteImport + parentRoute: typeof SecBRoute + } + '/sec-b/$id': { + id: '/sec-b/$id' + path: '/$id' + fullPath: '/sec-b/$id' + preLoaderRoute: typeof SecBIdRouteImport + parentRoute: typeof SecBRoute + } + '/sec-a/settings': { + id: '/sec-a/settings' + path: '/settings' + fullPath: '/sec-a/settings' + preLoaderRoute: typeof SecASettingsRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/about': { + id: '/sec-a/about' + path: '/about' + fullPath: '/sec-a/about' + preLoaderRoute: typeof SecAAboutRouteImport + parentRoute: typeof SecARoute + } + '/sec-a/$id': { + id: '/sec-a/$id' + path: '/$id' + fullPath: '/sec-a/$id' + preLoaderRoute: typeof SecAIdRouteImport + parentRoute: typeof SecARoute + } + '/release/v{$version}': { + id: '/release/v{$version}' + path: '/release/v{$version}' + fullPath: '/release/v{$version}' + preLoaderRoute: typeof ReleaseVChar123versionChar125RouteImport + parentRoute: typeof rootRouteImport + } + '/files/$': { + id: '/files/$' + path: '/files/$' + fullPath: '/files/$' + preLoaderRoute: typeof FilesSplatRouteImport + parentRoute: typeof rootRouteImport + } + '/_layout/beta': { + id: '/_layout/beta' + path: '/beta' + fullPath: '/beta' + preLoaderRoute: typeof LayoutBetaRouteImport + parentRoute: typeof LayoutRoute + } + '/_layout/alpha': { + id: '/_layout/alpha' + path: '/alpha' + fullPath: '/alpha' + preLoaderRoute: typeof LayoutAlphaRouteImport + parentRoute: typeof LayoutRoute + } + '/(marketing)/promo': { + id: '/(marketing)/promo' + path: '/promo' + fullPath: '/promo' + preLoaderRoute: typeof marketingPromoRouteImport + parentRoute: typeof rootRouteImport + } + '/(marketing)/pricing': { + id: '/(marketing)/pricing' + path: '/pricing' + fullPath: '/pricing' + preLoaderRoute: typeof marketingPricingRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts b/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts index 0b38f7bddb..5bdd994e32 100644 --- a/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/search-params/react/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-search-params', async ({ bench }) => { - const scenario = setup() +describe('client-search-params', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-search-params navigation loop (react)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts b/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts index caa626c596..ea0baa1098 100644 --- a/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/search-params/solid/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-search-params', async ({ bench }) => { - const scenario = setup() +describe('client-search-params', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-search-params navigation loop (solid)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/search-params/solid/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/search-params/solid/src/routeTree.gen.ts index b15beed09b..96d211d64c 100644 --- a/benchmarks/client-nav/scenarios/search-params/solid/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/search-params/solid/src/routeTree.gen.ts @@ -9,13 +9,13 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as CatalogRouteImport } from './routes/catalog' import { Route as ProductsRouteImport } from './routes/products' +import { Route as CatalogRouteImport } from './routes/catalog' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ProductsRoute = ProductsRouteImport.update({ + id: '/products', + path: '/products', getParentRoute: () => rootRouteImport, } as any) const CatalogRoute = CatalogRouteImport.update({ @@ -23,9 +23,9 @@ const CatalogRoute = CatalogRouteImport.update({ path: '/catalog', getParentRoute: () => rootRouteImport, } as any) -const ProductsRoute = ProductsRouteImport.update({ - id: '/products', - path: '/products', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) @@ -61,11 +61,11 @@ export interface RootRouteChildren { declare module '@tanstack/solid-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/products': { + id: '/products' + path: '/products' + fullPath: '/products' + preLoaderRoute: typeof ProductsRouteImport parentRoute: typeof rootRouteImport } '/catalog': { @@ -75,11 +75,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof CatalogRouteImport parentRoute: typeof rootRouteImport } - '/products': { - id: '/products' - path: '/products' - fullPath: '/products' - preLoaderRoute: typeof ProductsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts b/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts index 728d2779e8..c82efd49c9 100644 --- a/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts +++ b/benchmarks/client-nav/scenarios/search-params/vue/speed.bench.ts @@ -1,19 +1,32 @@ -import { test } from 'vitest' -import { benchLifecycle } from '../../../../cpu-simulation' +import { afterEach, beforeEach, bench, describe } from 'vitest' import { benchOptions, ticksPerIteration } from '../shared' import { setup } from './setup' -test('client-search-params', async ({ bench }) => { - const scenario = setup() +describe('client-search-params', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores suite hooks, so Tinybench uses the `setup` + * and `teardown` options below. CodSpeed bypasses those options but supports + * `beforeEach` and `afterEach`. Only one lifecycle path runs in either + * environment, and every measured invocation receives fresh application state. + */ + + beforeEach(test.before) + afterEach(test.after) + + bench( 'client-search-params navigation loop (vue)', - benchLifecycle(scenario), async () => { for (let i = 0; i < ticksPerIteration; i++) { - await scenario.tick() + await test.tick() } - await scenario.finishBatch() + await test.finishBatch() }, - ).run(benchOptions) + { + ...benchOptions, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/scenarios/search-params/vue/src/routeTree.gen.ts b/benchmarks/client-nav/scenarios/search-params/vue/src/routeTree.gen.ts index f73b84ebe7..b95b667803 100644 --- a/benchmarks/client-nav/scenarios/search-params/vue/src/routeTree.gen.ts +++ b/benchmarks/client-nav/scenarios/search-params/vue/src/routeTree.gen.ts @@ -9,13 +9,13 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' -import { Route as IndexRouteImport } from './routes/index' -import { Route as CatalogRouteImport } from './routes/catalog' import { Route as ProductsRouteImport } from './routes/products' +import { Route as CatalogRouteImport } from './routes/catalog' +import { Route as IndexRouteImport } from './routes/index' -const IndexRoute = IndexRouteImport.update({ - id: '/', - path: '/', +const ProductsRoute = ProductsRouteImport.update({ + id: '/products', + path: '/products', getParentRoute: () => rootRouteImport, } as any) const CatalogRoute = CatalogRouteImport.update({ @@ -23,9 +23,9 @@ const CatalogRoute = CatalogRouteImport.update({ path: '/catalog', getParentRoute: () => rootRouteImport, } as any) -const ProductsRoute = ProductsRouteImport.update({ - id: '/products', - path: '/products', +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', getParentRoute: () => rootRouteImport, } as any) @@ -61,11 +61,11 @@ export interface RootRouteChildren { declare module '@tanstack/vue-router' { interface FileRoutesByPath { - '/': { - id: '/' - path: '/' - fullPath: '/' - preLoaderRoute: typeof IndexRouteImport + '/products': { + id: '/products' + path: '/products' + fullPath: '/products' + preLoaderRoute: typeof ProductsRouteImport parentRoute: typeof rootRouteImport } '/catalog': { @@ -75,11 +75,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof CatalogRouteImport parentRoute: typeof rootRouteImport } - '/products': { - id: '/products' - path: '/products' - fullPath: '/products' - preLoaderRoute: typeof ProductsRouteImport + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/client-nav/solid/speed.bench.ts b/benchmarks/client-nav/solid/speed.bench.ts index d629da17a8..34791180ce 100644 --- a/benchmarks/client-nav/solid/speed.bench.ts +++ b/benchmarks/client-nav/solid/speed.bench.ts @@ -1,19 +1,34 @@ -import { test } from 'vitest' +import { afterAll, beforeAll, bench, describe } from 'vitest' import { setup } from './setup' -test('client-nav', async ({ bench }) => { - const scenario = setup() +describe('client-nav', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, + * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. + * + * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, + * but it does support `beforeAll` and `afterAll`. + * + * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. + */ + + beforeAll(test.before) + afterAll(test.after) + + bench( 'client-side navigation loop (solid)', - { beforeAll: scenario.before, afterAll: scenario.after }, async () => { for (let i = 0; i < 10; i++) { - await scenario.tick() + await test.tick() } }, - ).run({ - warmupIterations: 100, - time: 10_000, - }) + { + warmupIterations: 100, + time: 10_000, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/solid/vite.config.ts b/benchmarks/client-nav/solid/vite.config.ts index 0c26b32f5f..1dd8e1e15c 100644 --- a/benchmarks/client-nav/solid/vite.config.ts +++ b/benchmarks/client-nav/solid/vite.config.ts @@ -37,7 +37,6 @@ export default defineConfig({ watch: false, environment: 'jsdom', setupFiles: [`${rootDir}vitest.setup.ts`], - benchmark: { include: ['solid/speed.bench.ts'] }, server: { deps: { inline: [/@solidjs/, /@tanstack\/solid-store/], diff --git a/benchmarks/client-nav/vue/speed.bench.ts b/benchmarks/client-nav/vue/speed.bench.ts index 503e91e7b7..f9e532f5ba 100644 --- a/benchmarks/client-nav/vue/speed.bench.ts +++ b/benchmarks/client-nav/vue/speed.bench.ts @@ -1,19 +1,34 @@ -import { test } from 'vitest' +import { afterAll, beforeAll, bench, describe } from 'vitest' import { setup } from './setup' -test('client-nav', async ({ bench }) => { - const scenario = setup() +describe('client-nav', () => { + const test = setup() - await bench( + /** + * Running `vitest bench` ignores "suite hooks" like `beforeAll` and `afterAll`, + * so we use tinybench's `setup` and `teardown` options to run our setup and teardown logic. + * + * But CodSpeed calls the benchmarked function directly, bypassing `setup` and `teardown`, + * but it does support `beforeAll` and `afterAll`. + * + * So it looks like we're setting up in duplicate, but in reality, it's only running once per environment, as intended. + */ + + beforeAll(test.before) + afterAll(test.after) + + bench( 'client-side navigation loop (vue)', - { beforeAll: scenario.before, afterAll: scenario.after }, async () => { for (let i = 0; i < 10; i++) { - await scenario.tick() + await test.tick() } }, - ).run({ - warmupIterations: 100, - time: 10_000, - }) + { + warmupIterations: 100, + time: 10_000, + setup: test.before, + teardown: test.after, + }, + ) }) diff --git a/benchmarks/client-nav/vue/vite.config.ts b/benchmarks/client-nav/vue/vite.config.ts index 78d8ae5638..7abe24b455 100644 --- a/benchmarks/client-nav/vue/vite.config.ts +++ b/benchmarks/client-nav/vue/vite.config.ts @@ -36,6 +36,5 @@ export default defineConfig({ watch: false, environment: 'jsdom', setupFiles: [`${rootDir}vitest.setup.ts`], - benchmark: { include: ['vue/speed.bench.ts'] }, }, }) diff --git a/benchmarks/cpu-simulation.ts b/benchmarks/cpu-simulation.ts index 9b8859f74d..7e16bf4c5a 100644 --- a/benchmarks/cpu-simulation.ts +++ b/benchmarks/cpu-simulation.ts @@ -1,23 +1,9 @@ -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() + const mode = + process.env.CODSPEED_ENV === undefined + ? undefined + : process.env.CODSPEED_RUNNER_MODE 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. @@ -36,18 +22,3 @@ export function cpuSimulationExecArgv() { } 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 18b68768f9..d93e77e70b 100644 --- a/benchmarks/memory/README.md +++ b/benchmarks/memory/README.md @@ -2,7 +2,7 @@ Dedicated memory benchmarks for TanStack Router / Start, measured with the CodSpeed **memory instrument** (`mode: memory` in -`.github/workflows/benchmarks.yml`). The workflow runs on every +`.github/workflows/client-nav-benchmarks.yml`). The workflow runs on every push to `main` except docs/examples/e2e-only pushes: CodSpeed compares a PR against the run on its merge-base commit, and a main commit without a run makes CodSpeed silently fall back to an older base — a single outlier base run then @@ -34,8 +34,8 @@ benchmarks/memory// One app per scenario; apps and bench names are stable once landed (CodSpeed continuity). Never grow an existing scenario for a new case — add a scenario. `setup.ts` imports the built app and exports the concrete workload; -`memory.bench.ts` registers it with Vitest's `bench` test fixture, and -`memory.flame.ts` runs the same workload through the Flame profiler. +`memory.bench.ts` registers `bench(...)` directly, and `memory.flame.ts` runs the +same workload through the Flame profiler. ## How the memory instrument executes a bench @@ -43,21 +43,19 @@ continuity). Never grow an existing scenario for a new case — add a scenario. 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. 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. + measured one. Client suite hooks mount a fresh app before each invocation + and tear it down afterward, outside the measurement window. This prevents + warmup navigation history and caches from changing the starting state. + Module-level counters/LCGs keep generated URLs unique across invocations. +- Plain `vitest bench` never runs suite hooks (`beforeEach`/`afterEach`) 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. - 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 +- Before each CodSpeed invocation, a setup 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 @@ -74,14 +72,13 @@ continuity). Never grow an existing scenario for a new case — add a scenario. 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% +repetitions with these 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%, @@ -104,19 +101,6 @@ collections. This does not preallocate 512 MiB, and the smallest sufficient budg 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:** a fixed number of sequential operations, measuring native @@ -258,7 +242,7 @@ WITH_INSTRUMENTATION=1 codspeed run --mode memory -- pnpm nx run @benchmarks/mem Run the benchmark workflow on an experiment branch: ```bash -gh workflow run benchmarks.yml --ref +gh workflow run client-nav-benchmarks.yml --ref ``` Repeat at the same commit, using distinct branch names if runs should overlap diff --git a/benchmarks/memory/client/bench-utils.ts b/benchmarks/memory/client/bench-utils.ts index 785e8fac7f..0cbaedbd71 100644 --- a/benchmarks/memory/client/bench-utils.ts +++ b/benchmarks/memory/client/bench-utils.ts @@ -1,5 +1,3 @@ -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 463047f4d9..8b877b0740 100644 --- a/benchmarks/memory/client/benchmark.ts +++ b/benchmarks/memory/client/benchmark.ts @@ -1,10 +1,6 @@ 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 4dc6246183..af1770ba0d 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": "^6.0.1", + "@codspeed/vitest-plugin": "^5.5.0", "@datadog/pprof": "^5.13.2", "@platformatic/flame": "^1.6.0", "@testing-library/react": "^16.2.0", @@ -202,7 +202,7 @@ "build:react" ], "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.react.config.ts", + "command": "NODE_ENV=production vitest bench --config ./vitest.react.config.ts", "cwd": "benchmarks/memory/client" } }, @@ -214,7 +214,7 @@ "build:solid" ], "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.solid.config.ts", + "command": "NODE_ENV=production vitest bench --config ./vitest.solid.config.ts", "cwd": "benchmarks/memory/client" } }, @@ -226,7 +226,7 @@ "build:vue" ], "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.vue.config.ts", + "command": "NODE_ENV=production vitest bench --config ./vitest.vue.config.ts", "cwd": "benchmarks/memory/client" } }, 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 43ab822de3..85a1f11ee6 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/react/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterEach, beforeEach, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeEach(workload.before) + afterEach(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) 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 43ab822de3..85a1f11ee6 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/solid/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterEach, beforeEach, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeEach(workload.before) + afterEach(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) 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 43ab822de3..85a1f11ee6 100644 --- a/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/interrupted-navigations/vue/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterEach, beforeEach, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeEach(workload.before) + afterEach(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) 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 43ab822de3..85a1f11ee6 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,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterEach, beforeEach, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeEach(workload.before) + afterEach(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) 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 43ab822de3..85a1f11ee6 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,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterEach, beforeEach, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeEach(workload.before) + afterEach(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) 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 43ab822de3..85a1f11ee6 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,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterEach, beforeEach, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeEach(workload.before) + afterEach(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) 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 43ab822de3..85a1f11ee6 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/react/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/mount-unmount/react/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterEach, beforeEach, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeEach(workload.before) + afterEach(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) 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 43ab822de3..85a1f11ee6 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/mount-unmount/solid/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterEach, beforeEach, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeEach(workload.before) + afterEach(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) 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 43ab822de3..85a1f11ee6 100644 --- a/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/mount-unmount/vue/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterEach, beforeEach, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeEach(workload.before) + afterEach(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) 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 43ab822de3..85a1f11ee6 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/react/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/navigation-churn/react/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterEach, beforeEach, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeEach(workload.before) + afterEach(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) 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 43ab822de3..85a1f11ee6 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/navigation-churn/solid/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterEach, beforeEach, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeEach(workload.before) + afterEach(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) 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 43ab822de3..85a1f11ee6 100644 --- a/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/navigation-churn/vue/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterEach, beforeEach, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeEach(workload.before) + afterEach(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) 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 43ab822de3..85a1f11ee6 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/react/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/react/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterEach, beforeEach, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeEach(workload.before) + afterEach(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) 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 43ab822de3..85a1f11ee6 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/solid/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/solid/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterEach, beforeEach, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeEach(workload.before) + afterEach(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) 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 43ab822de3..85a1f11ee6 100644 --- a/benchmarks/memory/client/scenarios/preload-churn/vue/memory.bench.ts +++ b/benchmarks/memory/client/scenarios/preload-churn/vue/memory.bench.ts @@ -1,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterEach, beforeEach, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeEach(workload.before) + afterEach(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) 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 43ab822de3..85a1f11ee6 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,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterEach, beforeEach, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeEach(workload.before) + afterEach(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) 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 43ab822de3..85a1f11ee6 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,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterEach, beforeEach, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeEach(workload.before) + afterEach(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) 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 43ab822de3..85a1f11ee6 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,14 +1,21 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-client/bench-utils' +import { afterEach, beforeEach, bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-client/bench-utils' import { workload } from './setup' await workload.sanity() -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(workload), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + if (workload.before && workload.after) { + beforeEach(workload.before) + afterEach(workload.after) + + bench(workload.name, workload.run, { + ...memoryBenchOptions, + setup: workload.before, + teardown: workload.after, + }) + return + } + + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/client/vitest.setup.ts b/benchmarks/memory/client/vitest.setup.ts index ce3127275a..5f78f1a7d1 100644 --- a/benchmarks/memory/client/vitest.setup.ts +++ b/benchmarks/memory/client/vitest.setup.ts @@ -1,3 +1,6 @@ +import { beforeEach } from 'vitest' +import { endMemoryTurn, isMemoryInstrumented } from '../turn' + // @ts-expect-error global.IS_REACT_ACT_ENVIRONMENT = true @@ -7,3 +10,7 @@ window.scrollTo = scrollTo globalThis.scrollTo = scrollTo export {} + +if (isMemoryInstrumented()) { + beforeEach(endMemoryTurn) +} diff --git a/benchmarks/memory/runtime.ts b/benchmarks/memory/runtime.ts index 010149b4df..2aded74582 100644 --- a/benchmarks/memory/runtime.ts +++ b/benchmarks/memory/runtime.ts @@ -7,16 +7,9 @@ export function memoryExecArgv() { 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', @@ -29,8 +22,8 @@ export function memoryConfig(side: 'client' | 'server') { return { execArgv, setupFiles: - side === 'client' - ? [fileURLToPath(new URL('./client/vitest.setup.ts', import.meta.url))] + side === 'client' || isMemoryInstrumented() + ? [fileURLToPath(new URL(`./${side}/vitest.setup.ts`, import.meta.url))] : [], } } diff --git a/benchmarks/memory/server/bench-utils.ts b/benchmarks/memory/server/bench-utils.ts index 9caaf63384..8893d5be4b 100644 --- a/benchmarks/memory/server/bench-utils.ts +++ b/benchmarks/memory/server/bench-utils.ts @@ -1,5 +1,3 @@ -export { memoryBenchHooks } from '../turn' - export interface StartRequestHandler { fetch: (request: Request) => Promise | Response } diff --git a/benchmarks/memory/server/benchmark.ts b/benchmarks/memory/server/benchmark.ts index 9b8dc2c76f..301a9f956d 100644 --- a/benchmarks/memory/server/benchmark.ts +++ b/benchmarks/memory/server/benchmark.ts @@ -1,9 +1,5 @@ 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 d09343c7b6..4688384061 100644 --- a/benchmarks/memory/server/package.json +++ b/benchmarks/memory/server/package.json @@ -23,7 +23,7 @@ "vue": "^3.5.16" }, "devDependencies": { - "@codspeed/vitest-plugin": "^6.0.1", + "@codspeed/vitest-plugin": "^5.5.0", "@datadog/pprof": "^5.13.2", "@platformatic/flame": "^1.6.0", "@vitejs/plugin-react": "^6.0.1", @@ -208,7 +208,7 @@ "build:react" ], "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.react.config.ts", + "command": "NODE_ENV=production vitest bench --config ./vitest.react.config.ts", "cwd": "benchmarks/memory/server" } }, @@ -220,7 +220,7 @@ "build:solid" ], "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.solid.config.ts", + "command": "NODE_ENV=production vitest bench --config ./vitest.solid.config.ts", "cwd": "benchmarks/memory/server" } }, @@ -232,7 +232,7 @@ "build:vue" ], "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.vue.config.ts", + "command": "NODE_ENV=production vitest bench --config ./vitest.vue.config.ts", "cwd": "benchmarks/memory/server" } }, 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 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/react/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/aborted-requests/shared.ts b/benchmarks/memory/server/scenarios/aborted-requests/shared.ts index 29eca99e00..b5a61594ba 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/shared.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/shared.ts @@ -221,7 +221,7 @@ export function createWorkloadGroup( handler: StartRequestHandler, ) { const mode = abortedRequestModes[framework] - const run = async () => runAbortedRequestLoop(handler, mode) + const run = () => runAbortedRequestLoop(handler, mode) return { sanity: () => assertAbortedRequestsSanity(handler, mode), diff --git a/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.bench.ts b/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.bench.ts index 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/solid/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) 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 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/aborted-requests/vue/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) 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 a6f07b97be..2780830cb2 100644 --- a/benchmarks/memory/server/scenarios/error-paths/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/react/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() const workload = workloadGroup.workloads[0]! -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + bench(workload.name, workload.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 index 89071137c3..d41877e6ce 100644 --- a/benchmarks/memory/server/scenarios/error-paths/react/memory.error.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/react/memory.error.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { 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, - ) +describe('memory', () => { + bench(workload.name, workload.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 index fa6a6693ed..42d67b1164 100644 --- 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 @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { 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, - ) +describe('memory', () => { + bench(workload.name, workload.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 index b2c3d24200..6179e469dd 100644 --- a/benchmarks/memory/server/scenarios/error-paths/react/memory.unmatched.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/react/memory.unmatched.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { 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, - ) +describe('memory', () => { + bench(workload.name, workload.run, memoryBenchOptions) }) diff --git a/benchmarks/memory/server/scenarios/error-paths/shared.ts b/benchmarks/memory/server/scenarios/error-paths/shared.ts index 11ed293d22..966505f3a0 100644 --- a/benchmarks/memory/server/scenarios/error-paths/shared.ts +++ b/benchmarks/memory/server/scenarios/error-paths/shared.ts @@ -136,7 +136,7 @@ export function createWorkloadGroup( framework: Framework, handler: StartRequestHandler, ) { - const runRedirect = async () => + const runRedirect = () => runSequentialRequestLoop(handler, { random: redirectRandom, iterations: errorPathsIterations, @@ -144,7 +144,7 @@ export function createWorkloadGroup( validateResponse: validateRedirectResponse, }) - const runNotFound = async () => + const runNotFound = () => runSequentialRequestLoop(handler, { random: notFoundRandom, iterations: errorPathsIterations, @@ -152,7 +152,7 @@ export function createWorkloadGroup( validateResponse: validateNotFoundResponse, }) - const runError = async () => + const runError = () => runSequentialRequestLoop(handler, { random: errorRandom, iterations: errorPathsIterations, @@ -160,7 +160,7 @@ export function createWorkloadGroup( validateResponse: validateErrorResponse, }) - const runUnmatched = async () => + const runUnmatched = () => runSequentialRequestLoop(handler, { random: unmatchedRandom, iterations: errorPathsIterations, 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 a6f07b97be..2780830cb2 100644 --- a/benchmarks/memory/server/scenarios/error-paths/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/solid/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() const workload = workloadGroup.workloads[0]! -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + bench(workload.name, workload.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 index 89071137c3..d41877e6ce 100644 --- a/benchmarks/memory/server/scenarios/error-paths/solid/memory.error.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/solid/memory.error.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { 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, - ) +describe('memory', () => { + bench(workload.name, workload.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 index fa6a6693ed..42d67b1164 100644 --- 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 @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { 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, - ) +describe('memory', () => { + bench(workload.name, workload.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 index b2c3d24200..6179e469dd 100644 --- a/benchmarks/memory/server/scenarios/error-paths/solid/memory.unmatched.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/solid/memory.unmatched.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { 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, - ) +describe('memory', () => { + bench(workload.name, workload.run, memoryBenchOptions) }) 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 a6f07b97be..2780830cb2 100644 --- a/benchmarks/memory/server/scenarios/error-paths/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/vue/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() const workload = workloadGroup.workloads[0]! -test('memory', async ({ bench }) => { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) +describe('memory', () => { + bench(workload.name, workload.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 index 89071137c3..d41877e6ce 100644 --- a/benchmarks/memory/server/scenarios/error-paths/vue/memory.error.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/vue/memory.error.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { 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, - ) +describe('memory', () => { + bench(workload.name, workload.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 index fa6a6693ed..42d67b1164 100644 --- 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 @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { 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, - ) +describe('memory', () => { + bench(workload.name, workload.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 index b2c3d24200..6179e469dd 100644 --- a/benchmarks/memory/server/scenarios/error-paths/vue/memory.unmatched.bench.ts +++ b/benchmarks/memory/server/scenarios/error-paths/vue/memory.unmatched.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { 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, - ) +describe('memory', () => { + bench(workload.name, workload.run, memoryBenchOptions) }) 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 8b5f16ad63..9a5c211fee 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,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/peak-large-page/shared.ts b/benchmarks/memory/server/scenarios/peak-large-page/shared.ts index 085e576244..486c025f5a 100644 --- a/benchmarks/memory/server/scenarios/peak-large-page/shared.ts +++ b/benchmarks/memory/server/scenarios/peak-large-page/shared.ts @@ -48,7 +48,7 @@ export function createWorkloadGroup( framework: Framework, handler: StartRequestHandler, ) { - const run = async () => + const run = () => runSequentialRequestLoop(handler, { seed: benchmarkSeed, iterations: peakLargePageIterations, 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 8b5f16ad63..9a5c211fee 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,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) 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 8b5f16ad63..9a5c211fee 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,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) 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 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/request-churn/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/request-churn/react/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/request-churn/shared.ts b/benchmarks/memory/server/scenarios/request-churn/shared.ts index b200c96ed6..32125148cd 100644 --- a/benchmarks/memory/server/scenarios/request-churn/shared.ts +++ b/benchmarks/memory/server/scenarios/request-churn/shared.ts @@ -62,7 +62,7 @@ export function createWorkloadGroup( return new Request(`http://localhost/items/${id}?q=${q}`, requestInit) } - const run = async () => + const run = () => runSequentialRequestLoop(handler, { random: benchmarkRandom, iterations: requestChurnIterations, 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 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/request-churn/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/request-churn/solid/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) 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 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/request-churn/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/request-churn/vue/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) 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 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/react/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/serialization-payload/shared.ts b/benchmarks/memory/server/scenarios/serialization-payload/shared.ts index 14ec8f7e0a..7f40aeb9d2 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/shared.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/shared.ts @@ -55,7 +55,7 @@ export function createWorkloadGroup( framework: Framework, handler: StartRequestHandler, ) { - const run = async () => + const run = () => runSequentialRequestLoop(handler, { seed: benchmarkSeed, iterations: serializationPayloadIterations, 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 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/solid/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) 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 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/serialization-payload/vue/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) 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 8b5f16ad63..9a5c211fee 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,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts b/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts index 167b24d3b6..5fd1e22632 100644 --- a/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts +++ b/benchmarks/memory/server/scenarios/server-fn-churn/shared.ts @@ -202,7 +202,7 @@ export async function createWorkloadGroup( handler: StartRequestHandler, ) { const urls = await discoverUrls(handler) - const run = async () => + const run = () => runSequentialRequestLoop(handler, { seed: benchmarkSeed, iterations: serverFnChurnIterations, 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 8b5f16ad63..9a5c211fee 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,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) 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 8b5f16ad63..9a5c211fee 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,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) 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 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/react/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/react/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/scenarios/streaming-peak/shared.ts b/benchmarks/memory/server/scenarios/streaming-peak/shared.ts index c027047408..01917c4743 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/shared.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/shared.ts @@ -92,7 +92,7 @@ export function createWorkloadGroup( framework: Framework, handler: StartRequestHandler, ) { - const run = async () => + const run = () => runSequentialRequestLoop(handler, { seed: benchmarkSeed, iterations: streamingPeakIterations, 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 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/solid/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) 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 8b5f16ad63..9a5c211fee 100644 --- a/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.bench.ts +++ b/benchmarks/memory/server/scenarios/streaming-peak/vue/memory.bench.ts @@ -1,16 +1,11 @@ -import { test } from 'vitest' -import { - memoryBenchHooks, - memoryBenchOptions, -} from '#memory-server/bench-utils' +import { bench, describe } from 'vitest' +import { memoryBenchOptions } from '#memory-server/bench-utils' import { workloadGroup } from './setup' await workloadGroup.sanity() -test('memory', async ({ bench }) => { +describe('memory', () => { for (const workload of workloadGroup.workloads) { - await bench(workload.name, memoryBenchHooks(), workload.run).run( - memoryBenchOptions, - ) + bench(workload.name, workload.run, memoryBenchOptions) } }) diff --git a/benchmarks/memory/server/vitest.setup.ts b/benchmarks/memory/server/vitest.setup.ts new file mode 100644 index 0000000000..be96c0067a --- /dev/null +++ b/benchmarks/memory/server/vitest.setup.ts @@ -0,0 +1,4 @@ +import { beforeEach } from 'vitest' +import { endMemoryTurn } from '../turn' + +beforeEach(endMemoryTurn) diff --git a/benchmarks/memory/turn.ts b/benchmarks/memory/turn.ts index 08729685fe..3ee6d53833 100644 --- a/benchmarks/memory/turn.ts +++ b/benchmarks/memory/turn.ts @@ -10,25 +10,3 @@ export function isMemoryInstrumented() { 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 3d90af1598..625e1006c5 100644 --- a/benchmarks/ssr/README.md +++ b/benchmarks/ssr/README.md @@ -98,18 +98,3 @@ 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/package.json b/benchmarks/ssr/package.json index 20c1837468..07fbd92849 100644 --- a/benchmarks/ssr/package.json +++ b/benchmarks/ssr/package.json @@ -15,11 +15,11 @@ "vue": "^3.5.16" }, "devDependencies": { - "@codspeed/vitest-plugin": "^6.0.1", + "@codspeed/vitest-plugin": "^5.5.0", "@vitejs/plugin-react": "^6.0.1", "@vitejs/plugin-vue-jsx": "^5.1.5", "@types/react": "catalog:", - "seroval": "^1.6.7", + "seroval": "^1.6.2", "@typescript/native": "npm:typescript@^7.0.2", "jsdom": "29.1.1", "typescript": "npm:@typescript/typescript6@^6.0.2", @@ -116,7 +116,7 @@ "build:vue" ], "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark", + "command": "NODE_ENV=production vitest bench", "cwd": "benchmarks/ssr" } }, @@ -134,7 +134,7 @@ "build:react" ], "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.react.config.ts", + "command": "NODE_ENV=production vitest bench --config ./vitest.react.config.ts", "cwd": "benchmarks/ssr" } }, @@ -145,7 +145,7 @@ "build:solid" ], "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.solid.config.ts", + "command": "NODE_ENV=production vitest bench --config ./vitest.solid.config.ts", "cwd": "benchmarks/ssr" } }, @@ -156,7 +156,7 @@ "build:vue" ], "options": { - "command": "NODE_ENV=production vitest bench --mode benchmark --config ./vitest.vue.config.ts", + "command": "NODE_ENV=production vitest bench --config ./vitest.vue.config.ts", "cwd": "benchmarks/ssr" } }, diff --git a/benchmarks/ssr/react/speed.bench.ts b/benchmarks/ssr/react/speed.bench.ts index 6825a7ddfb..419b1ccb36 100644 --- a/benchmarks/ssr/react/speed.bench.ts +++ b/benchmarks/ssr/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { runSsrRequestLoop } from '../bench-utils' import type { StartRequestHandler } from '../bench-utils' @@ -11,12 +11,14 @@ const { default: handler } = (await import( default: StartRequestHandler } -test('ssr', async ({ bench }) => { - await bench('ssr request loop (react)', async () => - runSsrRequestLoop(handler, { seed: benchmarkSeed }), - ).run({ - warmupIterations: 100, - time: 10_000, - throws: true, - }) +describe('ssr', () => { + bench( + 'ssr request loop (react)', + () => runSsrRequestLoop(handler, { seed: benchmarkSeed }), + { + warmupIterations: 100, + time: 10_000, + throws: true, + }, + ) }) 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 index 0496613afb..6413559b92 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertAssetsScenario, assetsBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertAssetsScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr assets linked-css control (react)', async () => - runAssetsLinkedControlLoop(handler), - ).run(assetsBenchOptions) +describe('ssr', () => { + bench( + 'ssr assets linked-css control (react)', + () => runAssetsLinkedControlLoop(handler), + assetsBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/assets/react/speed.bench.ts b/benchmarks/ssr/scenarios/assets/react/speed.bench.ts index 7dc57d89f1..5970b88f0b 100644 --- a/benchmarks/ssr/scenarios/assets/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/assets/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertAssetsScenario, assetsBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertAssetsScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr assets inline-css cdn (react)', async () => - runAssetsInlineLoop(handler), - ).run(assetsBenchOptions) +describe('ssr', () => { + bench( + 'ssr assets inline-css cdn (react)', + () => runAssetsInlineLoop(handler), + assetsBenchOptions, + ) }) 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 index d159124a04..63fa209ac3 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertAssetsScenario, assetsBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertAssetsScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr assets linked-css control (solid)', async () => - runAssetsLinkedControlLoop(handler), - ).run(assetsBenchOptions) +describe('ssr', () => { + bench( + 'ssr assets linked-css control (solid)', + () => runAssetsLinkedControlLoop(handler), + assetsBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/assets/solid/speed.bench.ts b/benchmarks/ssr/scenarios/assets/solid/speed.bench.ts index 47f483df11..fb5631a50e 100644 --- a/benchmarks/ssr/scenarios/assets/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/assets/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertAssetsScenario, assetsBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertAssetsScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr assets inline-css cdn (solid)', async () => - runAssetsInlineLoop(handler), - ).run(assetsBenchOptions) +describe('ssr', () => { + bench( + 'ssr assets inline-css cdn (solid)', + () => runAssetsInlineLoop(handler), + assetsBenchOptions, + ) }) 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 index e56d41df6b..ae8712da75 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertAssetsScenario, assetsBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertAssetsScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr assets linked-css control (vue)', async () => - runAssetsLinkedControlLoop(handler), - ).run(assetsBenchOptions) +describe('ssr', () => { + bench( + 'ssr assets linked-css control (vue)', + () => runAssetsLinkedControlLoop(handler), + assetsBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/assets/vue/speed.bench.ts b/benchmarks/ssr/scenarios/assets/vue/speed.bench.ts index 3f77a0dcc1..5225e3dc66 100644 --- a/benchmarks/ssr/scenarios/assets/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/assets/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertAssetsScenario, assetsBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertAssetsScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr assets inline-css cdn (vue)', async () => - runAssetsInlineLoop(handler), - ).run(assetsBenchOptions) +describe('ssr', () => { + bench( + 'ssr assets inline-css cdn (vue)', + () => runAssetsInlineLoop(handler), + assetsBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/before-load/react/speed.bench.ts b/benchmarks/ssr/scenarios/before-load/react/speed.bench.ts index 8a4355a168..09073687c0 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 { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertBeforeLoadScenario, beforeLoadBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertBeforeLoadScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr before-load chain (react)', async () => - runBeforeLoadLoop(handler), - ).run(beforeLoadBenchOptions) +describe('ssr', () => { + bench( + 'ssr before-load chain (react)', + () => runBeforeLoadLoop(handler), + beforeLoadBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/before-load/solid/speed.bench.ts b/benchmarks/ssr/scenarios/before-load/solid/speed.bench.ts index 27e0d3a64c..5f6e8baf8a 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 { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertBeforeLoadScenario, beforeLoadBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertBeforeLoadScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr before-load chain (solid)', async () => - runBeforeLoadLoop(handler), - ).run(beforeLoadBenchOptions) +describe('ssr', () => { + bench( + 'ssr before-load chain (solid)', + () => runBeforeLoadLoop(handler), + beforeLoadBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/before-load/vue/speed.bench.ts b/benchmarks/ssr/scenarios/before-load/vue/speed.bench.ts index 8684c159eb..d2cfd6814b 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 { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertBeforeLoadScenario, beforeLoadBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertBeforeLoadScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr before-load chain (vue)', async () => - runBeforeLoadLoop(handler), - ).run(beforeLoadBenchOptions) +describe('ssr', () => { + bench( + 'ssr before-load chain (vue)', + () => runBeforeLoadLoop(handler), + beforeLoadBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts b/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts index 899f400799..3c0a3f502e 100644 --- a/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr redirect (react)', async () => runRedirectLoop(handler)).run( +describe('ssr', () => { + bench( + 'ssr redirect (react)', + () => runRedirectLoop(handler), 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 index 0a93c5eac3..3e117895d8 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr control-flow error 500 (react)', async () => - runErrorLoop(handler), - ).run(controlFlowBenchOptions) +describe('ssr', () => { + bench( + 'ssr control-flow error 500 (react)', + () => runErrorLoop(handler), + 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 index 53e09fd34e..566748735e 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr control-flow route headers (react)', async () => - runRouteHeadersLoop(handler), - ).run(controlFlowBenchOptions) +describe('ssr', () => { + bench( + 'ssr control-flow route headers (react)', + () => runRouteHeadersLoop(handler), + 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 index 1cd7c1044c..b7c25a0bb2 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr control-flow unmatched 404 (react)', async () => - runUnmatchedLoop(handler), - ).run(controlFlowBenchOptions) +describe('ssr', () => { + bench( + 'ssr control-flow unmatched 404 (react)', + () => runUnmatchedLoop(handler), + 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 index 1e8abfd318..e56335c602 100644 --- a/benchmarks/ssr/scenarios/control-flow/react/speed.not-found.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/react/speed.not-found.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr not-found (react)', async () => - runNotFoundLoop(handler), - ).run(controlFlowBenchOptions) +describe('ssr', () => { + bench( + 'ssr not-found (react)', + () => runNotFoundLoop(handler), + controlFlowBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/control-flow/solid/speed.bench.ts b/benchmarks/ssr/scenarios/control-flow/solid/speed.bench.ts index 904b693e25..b76cd741df 100644 --- a/benchmarks/ssr/scenarios/control-flow/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr redirect (solid)', async () => runRedirectLoop(handler)).run( +describe('ssr', () => { + bench( + 'ssr redirect (solid)', + () => runRedirectLoop(handler), 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 index 57a2f0fbe9..119f65c9ee 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr control-flow error 500 (solid)', async () => - runErrorLoop(handler), - ).run(controlFlowBenchOptions) +describe('ssr', () => { + bench( + 'ssr control-flow error 500 (solid)', + () => runErrorLoop(handler), + 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 index 6581e92b39..8954e67986 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr control-flow route headers (solid)', async () => - runRouteHeadersLoop(handler), - ).run(controlFlowBenchOptions) +describe('ssr', () => { + bench( + 'ssr control-flow route headers (solid)', + () => runRouteHeadersLoop(handler), + 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 index 40f1679320..d59282def9 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr control-flow unmatched 404 (solid)', async () => - runUnmatchedLoop(handler), - ).run(controlFlowBenchOptions) +describe('ssr', () => { + bench( + 'ssr control-flow unmatched 404 (solid)', + () => runUnmatchedLoop(handler), + 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 index efcb7cc229..66cf63fe79 100644 --- a/benchmarks/ssr/scenarios/control-flow/solid/speed.not-found.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/solid/speed.not-found.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr not-found (solid)', async () => - runNotFoundLoop(handler), - ).run(controlFlowBenchOptions) +describe('ssr', () => { + bench( + 'ssr not-found (solid)', + () => runNotFoundLoop(handler), + 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 3cec17d9c8..5e7342c172 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 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' +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' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const BoomIdRoute = BoomIdRouteImport.update({ - id: '/boom/$id', - path: '/boom/$id', - getParentRoute: () => rootRouteImport, -} as any) -const FromIdRoute = FromIdRouteImport.update({ - id: '/from/$id', - path: '/from/$id', - getParentRoute: () => rootRouteImport, -} as any) -const HeadersIdRoute = HeadersIdRouteImport.update({ - id: '/headers/$id', - path: '/headers/$id', +const TargetIdRoute = TargetIdRouteImport.update({ + id: '/target/$id', + path: '/target/$id', getParentRoute: () => rootRouteImport, } as any) const MissingIdRoute = MissingIdRouteImport.update({ @@ -41,9 +31,19 @@ const MissingIdRoute = MissingIdRouteImport.update({ path: '/missing/$id', getParentRoute: () => rootRouteImport, } as any) -const TargetIdRoute = TargetIdRouteImport.update({ - id: '/target/$id', - path: '/target/$id', +const HeadersIdRoute = HeadersIdRouteImport.update({ + id: '/headers/$id', + path: '/headers/$id', + getParentRoute: () => rootRouteImport, +} as any) +const FromIdRoute = FromIdRouteImport.update({ + id: '/from/$id', + path: '/from/$id', + getParentRoute: () => rootRouteImport, +} as any) +const BoomIdRoute = BoomIdRouteImport.update({ + id: '/boom/$id', + path: '/boom/$id', getParentRoute: () => rootRouteImport, } as any) @@ -117,25 +117,11 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/boom/$id': { - id: '/boom/$id' - path: '/boom/$id' - fullPath: '/boom/$id' - preLoaderRoute: typeof BoomIdRouteImport - parentRoute: typeof rootRouteImport - } - '/from/$id': { - id: '/from/$id' - path: '/from/$id' - fullPath: '/from/$id' - preLoaderRoute: typeof FromIdRouteImport - parentRoute: typeof rootRouteImport - } - '/headers/$id': { - id: '/headers/$id' - path: '/headers/$id' - fullPath: '/headers/$id' - preLoaderRoute: typeof HeadersIdRouteImport + '/target/$id': { + id: '/target/$id' + path: '/target/$id' + fullPath: '/target/$id' + preLoaderRoute: typeof TargetIdRouteImport parentRoute: typeof rootRouteImport } '/missing/$id': { @@ -145,11 +131,25 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof MissingIdRouteImport parentRoute: typeof rootRouteImport } - '/target/$id': { - id: '/target/$id' - path: '/target/$id' - fullPath: '/target/$id' - preLoaderRoute: typeof TargetIdRouteImport + '/headers/$id': { + id: '/headers/$id' + path: '/headers/$id' + fullPath: '/headers/$id' + preLoaderRoute: typeof HeadersIdRouteImport + parentRoute: typeof rootRouteImport + } + '/from/$id': { + id: '/from/$id' + path: '/from/$id' + fullPath: '/from/$id' + preLoaderRoute: typeof FromIdRouteImport + parentRoute: typeof rootRouteImport + } + '/boom/$id': { + id: '/boom/$id' + path: '/boom/$id' + fullPath: '/boom/$id' + preLoaderRoute: typeof BoomIdRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts b/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts index 0b95f426f2..e57ec26b52 100644 --- a/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr redirect (vue)', async () => runRedirectLoop(handler)).run( +describe('ssr', () => { + bench( + 'ssr redirect (vue)', + () => runRedirectLoop(handler), 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 index 262ca951af..e118e1dd28 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr control-flow error 500 (vue)', async () => - runErrorLoop(handler), - ).run(controlFlowBenchOptions) +describe('ssr', () => { + bench( + 'ssr control-flow error 500 (vue)', + () => runErrorLoop(handler), + 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 index bf8c90a8a1..0bef524eaf 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr control-flow route headers (vue)', async () => - runRouteHeadersLoop(handler), - ).run(controlFlowBenchOptions) +describe('ssr', () => { + bench( + 'ssr control-flow route headers (vue)', + () => runRouteHeadersLoop(handler), + 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 index d7f8ebeb9e..e29919dc56 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr control-flow unmatched 404 (vue)', async () => - runUnmatchedLoop(handler), - ).run(controlFlowBenchOptions) +describe('ssr', () => { + bench( + 'ssr control-flow unmatched 404 (vue)', + () => runUnmatchedLoop(handler), + 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 index 4b84fb594c..b2ab3af3c7 100644 --- a/benchmarks/ssr/scenarios/control-flow/vue/speed.not-found.bench.ts +++ b/benchmarks/ssr/scenarios/control-flow/vue/speed.not-found.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertControlFlowSanity, controlFlowBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertControlFlowSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr not-found (vue)', async () => runNotFoundLoop(handler)).run( +describe('ssr', () => { + bench( + 'ssr not-found (vue)', + () => runNotFoundLoop(handler), 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 6dcf0d095e..f5063d1c09 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 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' +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' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', getParentRoute: () => rootRouteImport, } as any) -const BoomIdRoute = BoomIdRouteImport.update({ - id: '/boom/$id', - path: '/boom/$id', - getParentRoute: () => rootRouteImport, -} as any) -const FromIdRoute = FromIdRouteImport.update({ - id: '/from/$id', - path: '/from/$id', - getParentRoute: () => rootRouteImport, -} as any) -const HeadersIdRoute = HeadersIdRouteImport.update({ - id: '/headers/$id', - path: '/headers/$id', +const TargetIdRoute = TargetIdRouteImport.update({ + id: '/target/$id', + path: '/target/$id', getParentRoute: () => rootRouteImport, } as any) const MissingIdRoute = MissingIdRouteImport.update({ @@ -41,9 +31,19 @@ const MissingIdRoute = MissingIdRouteImport.update({ path: '/missing/$id', getParentRoute: () => rootRouteImport, } as any) -const TargetIdRoute = TargetIdRouteImport.update({ - id: '/target/$id', - path: '/target/$id', +const HeadersIdRoute = HeadersIdRouteImport.update({ + id: '/headers/$id', + path: '/headers/$id', + getParentRoute: () => rootRouteImport, +} as any) +const FromIdRoute = FromIdRouteImport.update({ + id: '/from/$id', + path: '/from/$id', + getParentRoute: () => rootRouteImport, +} as any) +const BoomIdRoute = BoomIdRouteImport.update({ + id: '/boom/$id', + path: '/boom/$id', getParentRoute: () => rootRouteImport, } as any) @@ -117,25 +117,11 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/boom/$id': { - id: '/boom/$id' - path: '/boom/$id' - fullPath: '/boom/$id' - preLoaderRoute: typeof BoomIdRouteImport - parentRoute: typeof rootRouteImport - } - '/from/$id': { - id: '/from/$id' - path: '/from/$id' - fullPath: '/from/$id' - preLoaderRoute: typeof FromIdRouteImport - parentRoute: typeof rootRouteImport - } - '/headers/$id': { - id: '/headers/$id' - path: '/headers/$id' - fullPath: '/headers/$id' - preLoaderRoute: typeof HeadersIdRouteImport + '/target/$id': { + id: '/target/$id' + path: '/target/$id' + fullPath: '/target/$id' + preLoaderRoute: typeof TargetIdRouteImport parentRoute: typeof rootRouteImport } '/missing/$id': { @@ -145,11 +131,25 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof MissingIdRouteImport parentRoute: typeof rootRouteImport } - '/target/$id': { - id: '/target/$id' - path: '/target/$id' - fullPath: '/target/$id' - preLoaderRoute: typeof TargetIdRouteImport + '/headers/$id': { + id: '/headers/$id' + path: '/headers/$id' + fullPath: '/headers/$id' + preLoaderRoute: typeof HeadersIdRouteImport + parentRoute: typeof rootRouteImport + } + '/from/$id': { + id: '/from/$id' + path: '/from/$id' + fullPath: '/from/$id' + preLoaderRoute: typeof FromIdRouteImport + parentRoute: typeof rootRouteImport + } + '/boom/$id': { + id: '/boom/$id' + path: '/boom/$id' + fullPath: '/boom/$id' + preLoaderRoute: typeof BoomIdRouteImport parentRoute: typeof rootRouteImport } } diff --git a/benchmarks/ssr/scenarios/global-middleware/bench.ts b/benchmarks/ssr/scenarios/global-middleware/bench.ts index d2784aed38..a89d03cabb 100644 --- a/benchmarks/ssr/scenarios/global-middleware/bench.ts +++ b/benchmarks/ssr/scenarios/global-middleware/bench.ts @@ -7,13 +7,10 @@ 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 } @@ -143,7 +140,6 @@ 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) @@ -158,7 +154,6 @@ 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), @@ -180,11 +175,7 @@ async function assertDocumentResponse(handler: StartRequestHandler) { } } -async function assertServerRouteResponseForCount( - handler: StartRequestHandler, - count: RequestMiddlewareCount, -) { - setRequestMiddlewareCount(count) +async function assertServerRouteResponse(handler: StartRequestHandler) { const id = 'route-sanity' const response = await handler.fetch( new Request(`${origin}/api/ping/${id}`, apiRequestInit), @@ -208,8 +199,10 @@ async function assertServerRouteResponseForCount( marker?: string requestTotal?: number } - const expectedContext = getExpectedRequestContext(count) - const expectedMarker = makeServerRouteMarker(id, expectedContext) + const expectedMarker = makeServerRouteMarker(id, { + requestTrace: 'req.r1.r2.r3', + requestTotal: expectedRequestTotal, + }) if (body.marker !== expectedMarker) { throw new Error( @@ -217,9 +210,9 @@ async function assertServerRouteResponseForCount( ) } - if (body.requestTotal !== expectedContext.requestTotal) { + if (body.requestTotal !== expectedRequestTotal) { throw new Error( - `Expected server route requestTotal ${expectedContext.requestTotal}, received ${body.requestTotal}`, + `Expected server route requestTotal ${expectedRequestTotal}, received ${body.requestTotal}`, ) } } @@ -228,7 +221,6 @@ async function assertServerFnResponse( handler: StartRequestHandler, context: GlobalMiddlewareBenchContext, ) { - setRequestMiddlewareCount(3) const response = await handler.fetch( buildPostRequest(context.urls, context.bodies, 0), ) @@ -265,14 +257,10 @@ export async function assertGlobalMiddlewareScenario( ) { await assertDocumentResponse(handler) await assertServerFnResponse(handler, context) - for (const count of [0, 1, 2, 3] as const) { - await assertServerRouteResponseForCount(handler, count) - } - setRequestMiddlewareCount(3) + await assertServerRouteResponse(handler) } export function runGlobalMiddlewareDocumentLoop(handler: StartRequestHandler) { - setRequestMiddlewareCount(3) return runRequestLoop(handler, { seed: benchmarkSeed, concurrency: 16, @@ -285,7 +273,6 @@ export function runGlobalMiddlewareServerFnLoop( handler: StartRequestHandler, context: GlobalMiddlewareBenchContext, ) { - setRequestMiddlewareCount(3) return runRequestLoop(handler, { seed: benchmarkSeed, concurrency: 16, @@ -297,9 +284,7 @@ export function runGlobalMiddlewareServerFnLoop( export function runGlobalMiddlewareServerRouteLoop( handler: StartRequestHandler, - count: RequestMiddlewareCount = 3, ) { - setRequestMiddlewareCount(count) return runRequestLoop(handler, { seed: benchmarkSeed, concurrency: 16, diff --git a/benchmarks/ssr/scenarios/global-middleware/react/speed.bench.ts b/benchmarks/ssr/scenarios/global-middleware/react/speed.bench.ts index cb3f9f427c..c68d718262 100644 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/global-middleware/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, @@ -18,8 +18,10 @@ const context = await setupGlobalMiddlewareBench(handler) await assertGlobalMiddlewareScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr global-mw document (react)', async () => - runGlobalMiddlewareDocumentLoop(handler), - ).run(globalMiddlewareBenchOptions) +describe('ssr', () => { + bench( + 'ssr global-mw document (react)', + () => runGlobalMiddlewareDocumentLoop(handler), + 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 index 48c444de77..2655ef2f49 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, @@ -18,8 +18,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr global-mw server-fn (react)', + () => runGlobalMiddlewareServerFnLoop(handler, context), + 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 deleted file mode 100644 index 22f53883ee..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-0-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index f01b48d66e..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-1-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index b01957f806..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/react/speed.global-mw-server-route-2-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -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 index 08d97fcaf6..9dc19cf943 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, @@ -18,8 +18,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr global-mw server-route (react)', + () => runGlobalMiddlewareServerRouteLoop(handler), + globalMiddlewareBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts b/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts index 8dfb2dd3c4..6b59e8035b 100644 --- a/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts +++ b/benchmarks/ssr/scenarios/global-middleware/react/src/start.ts @@ -1,5 +1,4 @@ import { createMiddleware, createStart } from '@tanstack/react-start' -import { getRequestMiddlewareCount } from '../../shared' import type { GlobalMiddlewareContext } from '../../shared' function appendTrace( @@ -49,13 +48,6 @@ 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 @@ -83,6 +75,10 @@ const functionMiddlewareB = createMiddleware({ type: 'function' }).server( ) export const startInstance = createStart(() => ({ - requestMiddleware: requestMiddlewareSets[getRequestMiddlewareCount()], + requestMiddleware: [ + requestMiddlewareA, + requestMiddlewareB, + requestMiddlewareC, + ], functionMiddleware: [functionMiddlewareA, functionMiddlewareB], })) diff --git a/benchmarks/ssr/scenarios/global-middleware/shared.ts b/benchmarks/ssr/scenarios/global-middleware/shared.ts index 8fbe788911..f90fa9b233 100644 --- a/benchmarks/ssr/scenarios/global-middleware/shared.ts +++ b/benchmarks/ssr/scenarios/global-middleware/shared.ts @@ -10,41 +10,11 @@ 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 0e5f504090..5f27210e36 100644 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/global-middleware/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, @@ -18,8 +18,10 @@ const context = await setupGlobalMiddlewareBench(handler) await assertGlobalMiddlewareScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr global-mw document (solid)', async () => - runGlobalMiddlewareDocumentLoop(handler), - ).run(globalMiddlewareBenchOptions) +describe('ssr', () => { + bench( + 'ssr global-mw document (solid)', + () => runGlobalMiddlewareDocumentLoop(handler), + 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 index 915507ef9f..eb19e10ec9 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, @@ -18,8 +18,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr global-mw server-fn (solid)', + () => runGlobalMiddlewareServerFnLoop(handler, context), + 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 deleted file mode 100644 index a791145935..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-0-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index 1baab0f344..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-1-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index d6fde20764..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/solid/speed.global-mw-server-route-2-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -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 index 558ebeb9a4..495c57112a 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, @@ -18,8 +18,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr global-mw server-route (solid)', + () => runGlobalMiddlewareServerRouteLoop(handler), + 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 65f7fa5848..28d816525e 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 ApiFnUrlsRouteImport } from './routes/api.fn-urls' import { Route as PageIdRouteImport } from './routes/page.$id' +import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' 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 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 ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ + id: '/api/fn-urls', + path: '/api/fn-urls', + 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 } - '/api/fn-urls': { - id: '/api/fn-urls' - path: '/api/fn-urls' - fullPath: '/api/fn-urls' - preLoaderRoute: typeof ApiFnUrlsRouteImport - parentRoute: typeof rootRouteImport - } '/page/$id': { id: '/page/$id' path: '/page/$id' @@ -92,6 +85,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof PageIdRouteImport parentRoute: typeof rootRouteImport } + '/api/fn-urls': { + id: '/api/fn-urls' + path: '/api/fn-urls' + fullPath: '/api/fn-urls' + preLoaderRoute: typeof ApiFnUrlsRouteImport + 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 a6f6214b82..8c4168d574 100644 --- a/benchmarks/ssr/scenarios/global-middleware/solid/src/start.ts +++ b/benchmarks/ssr/scenarios/global-middleware/solid/src/start.ts @@ -1,5 +1,4 @@ import { createMiddleware, createStart } from '@tanstack/solid-start' -import { getRequestMiddlewareCount } from '../../shared' import type { GlobalMiddlewareContext } from '../../shared' function appendTrace( @@ -49,13 +48,6 @@ 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 @@ -83,6 +75,10 @@ const functionMiddlewareB = createMiddleware({ type: 'function' }).server( ) export const startInstance = createStart(() => ({ - requestMiddleware: requestMiddlewareSets[getRequestMiddlewareCount()], + requestMiddleware: [ + requestMiddlewareA, + requestMiddlewareB, + requestMiddlewareC, + ], functionMiddleware: [functionMiddlewareA, functionMiddlewareB], })) diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts b/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts index 9660f29d07..5d92aab849 100644 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/global-middleware/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, @@ -18,8 +18,10 @@ const context = await setupGlobalMiddlewareBench(handler) await assertGlobalMiddlewareScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr global-mw document (vue)', async () => - runGlobalMiddlewareDocumentLoop(handler), - ).run(globalMiddlewareBenchOptions) +describe('ssr', () => { + bench( + 'ssr global-mw document (vue)', + () => runGlobalMiddlewareDocumentLoop(handler), + 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 index 297e8cee7b..ab158504c8 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, @@ -18,8 +18,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr global-mw server-fn (vue)', + () => runGlobalMiddlewareServerFnLoop(handler, context), + 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 deleted file mode 100644 index d023dd458a..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-0-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index 5018163631..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-1-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index f9abd8eb60..0000000000 --- a/benchmarks/ssr/scenarios/global-middleware/vue/speed.global-mw-server-route-2-middleware.bench.ts +++ /dev/null @@ -1,25 +0,0 @@ -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 index adcec3019f..e7fd4cd205 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertGlobalMiddlewareScenario, globalMiddlewareBenchOptions, @@ -18,8 +18,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr global-mw server-route (vue)', + () => runGlobalMiddlewareServerRouteLoop(handler), + 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 3118848e4d..aae3329420 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 ApiFnUrlsRouteImport } from './routes/api.fn-urls' import { Route as PageIdRouteImport } from './routes/page.$id' +import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' 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 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 ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ + id: '/api/fn-urls', + path: '/api/fn-urls', + 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 } - '/api/fn-urls': { - id: '/api/fn-urls' - path: '/api/fn-urls' - fullPath: '/api/fn-urls' - preLoaderRoute: typeof ApiFnUrlsRouteImport - parentRoute: typeof rootRouteImport - } '/page/$id': { id: '/page/$id' path: '/page/$id' @@ -92,6 +85,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof PageIdRouteImport parentRoute: typeof rootRouteImport } + '/api/fn-urls': { + id: '/api/fn-urls' + path: '/api/fn-urls' + fullPath: '/api/fn-urls' + preLoaderRoute: typeof ApiFnUrlsRouteImport + parentRoute: typeof rootRouteImport + } '/api/ping/$id': { id: '/api/ping/$id' path: '/api/ping/$id' diff --git a/benchmarks/ssr/scenarios/global-middleware/vue/src/start.ts b/benchmarks/ssr/scenarios/global-middleware/vue/src/start.ts index 6e4eb2c5ef..dc3f142e27 100644 --- a/benchmarks/ssr/scenarios/global-middleware/vue/src/start.ts +++ b/benchmarks/ssr/scenarios/global-middleware/vue/src/start.ts @@ -1,5 +1,4 @@ import { createMiddleware, createStart } from '@tanstack/vue-start' -import { getRequestMiddlewareCount } from '../../shared' import type { GlobalMiddlewareContext } from '../../shared' function appendTrace( @@ -49,13 +48,6 @@ 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 @@ -83,6 +75,10 @@ const functionMiddlewareB = createMiddleware({ type: 'function' }).server( ) export const startInstance = createStart(() => ({ - requestMiddleware: requestMiddlewareSets[getRequestMiddlewareCount()], + requestMiddleware: [ + requestMiddlewareA, + requestMiddlewareB, + requestMiddlewareC, + ], functionMiddleware: [functionMiddlewareA, functionMiddlewareB], })) diff --git a/benchmarks/ssr/scenarios/head/react/speed.bench.ts b/benchmarks/ssr/scenarios/head/react/speed.bench.ts index f75008506e..19158b32a9 100644 --- a/benchmarks/ssr/scenarios/head/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/head/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertHeadSanity, headBenchOptions, runHeadLoop } from '../shared' import type { StartRequestHandler } from '../shared' @@ -12,8 +12,6 @@ const { default: handler } = (await import( await assertHeadSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr head (react)', async () => runHeadLoop(handler)).run( - headBenchOptions, - ) +describe('ssr', () => { + bench('ssr head (react)', () => runHeadLoop(handler), headBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/head/solid/speed.bench.ts b/benchmarks/ssr/scenarios/head/solid/speed.bench.ts index 333e2f091b..ad5bf52809 100644 --- a/benchmarks/ssr/scenarios/head/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/head/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertHeadSanity, headBenchOptions, runHeadLoop } from '../shared' import type { StartRequestHandler } from '../shared' @@ -12,8 +12,6 @@ const { default: handler } = (await import( await assertHeadSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr head (solid)', async () => runHeadLoop(handler)).run( - headBenchOptions, - ) +describe('ssr', () => { + bench('ssr head (solid)', () => runHeadLoop(handler), headBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/head/vue/speed.bench.ts b/benchmarks/ssr/scenarios/head/vue/speed.bench.ts index 936735a909..5d8243b588 100644 --- a/benchmarks/ssr/scenarios/head/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/head/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertHeadSanity, headBenchOptions, runHeadLoop } from '../shared' import type { StartRequestHandler } from '../shared' @@ -12,8 +12,6 @@ const { default: handler } = (await import( await assertHeadSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr head (vue)', async () => runHeadLoop(handler)).run( - headBenchOptions, - ) +describe('ssr', () => { + bench('ssr head (vue)', () => runHeadLoop(handler), headBenchOptions) }) diff --git a/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts b/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts index 7acd43c635..a5eecfc648 100644 --- a/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/loaders/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertLoadersSanity, benchOptions, @@ -16,8 +16,6 @@ const { default: handler } = (await import( await assertLoadersSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr loaders (react)', async () => runLoadersLoop(handler)).run( - benchOptions, - ) +describe('ssr', () => { + bench('ssr loaders (react)', () => runLoadersLoop(handler), benchOptions) }) diff --git a/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts b/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts index 7fc8d88389..7b3f6247ea 100644 --- a/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/loaders/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertLoadersSanity, benchOptions, @@ -16,8 +16,6 @@ const { default: handler } = (await import( await assertLoadersSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr loaders (solid)', async () => runLoadersLoop(handler)).run( - benchOptions, - ) +describe('ssr', () => { + bench('ssr loaders (solid)', () => runLoadersLoop(handler), benchOptions) }) diff --git a/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts b/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts index 321350d98c..fb39e0652c 100644 --- a/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/loaders/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertLoadersSanity, benchOptions, @@ -16,8 +16,6 @@ const { default: handler } = (await import( await assertLoadersSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr loaders (vue)', async () => runLoadersLoop(handler)).run( - benchOptions, - ) +describe('ssr', () => { + bench('ssr loaders (vue)', () => runLoadersLoop(handler), benchOptions) }) diff --git a/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts b/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts index 920186c5db..a8af260279 100644 --- a/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/rewrites/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertRewriteScenario, rewriteBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertRewriteScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr rewrite localized (react)', async () => - runRewriteLocalizedLoop(handler), - ).run(rewriteBenchOptions) +describe('ssr', () => { + bench( + 'ssr rewrite localized (react)', + () => runRewriteLocalizedLoop(handler), + 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 index f5d09089a6..cffabcafb5 100644 --- a/benchmarks/ssr/scenarios/rewrites/react/speed.rewrite-passthrough.bench.ts +++ b/benchmarks/ssr/scenarios/rewrites/react/speed.rewrite-passthrough.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertRewriteScenario, rewriteBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertRewriteScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr rewrite passthrough (react)', async () => - runRewritePassthroughLoop(handler), - ).run(rewriteBenchOptions) +describe('ssr', () => { + bench( + 'ssr rewrite passthrough (react)', + () => runRewritePassthroughLoop(handler), + rewriteBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts b/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts index 488fb2ca52..5fdef077c9 100644 --- a/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/rewrites/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertRewriteScenario, rewriteBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertRewriteScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr rewrite localized (solid)', async () => - runRewriteLocalizedLoop(handler), - ).run(rewriteBenchOptions) +describe('ssr', () => { + bench( + 'ssr rewrite localized (solid)', + () => runRewriteLocalizedLoop(handler), + 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 index 7b86e2ba11..2458a59b69 100644 --- a/benchmarks/ssr/scenarios/rewrites/solid/speed.rewrite-passthrough.bench.ts +++ b/benchmarks/ssr/scenarios/rewrites/solid/speed.rewrite-passthrough.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertRewriteScenario, rewriteBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertRewriteScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr rewrite passthrough (solid)', async () => - runRewritePassthroughLoop(handler), - ).run(rewriteBenchOptions) +describe('ssr', () => { + bench( + 'ssr rewrite passthrough (solid)', + () => runRewritePassthroughLoop(handler), + rewriteBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts b/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts index 5fd4da9d3e..b8a98c3408 100644 --- a/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/rewrites/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertRewriteScenario, rewriteBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertRewriteScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr rewrite localized (vue)', async () => - runRewriteLocalizedLoop(handler), - ).run(rewriteBenchOptions) +describe('ssr', () => { + bench( + 'ssr rewrite localized (vue)', + () => runRewriteLocalizedLoop(handler), + 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 index f3664b5f21..e011a9fc8d 100644 --- a/benchmarks/ssr/scenarios/rewrites/vue/speed.rewrite-passthrough.bench.ts +++ b/benchmarks/ssr/scenarios/rewrites/vue/speed.rewrite-passthrough.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertRewriteScenario, rewriteBenchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertRewriteScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr rewrite passthrough (vue)', async () => - runRewritePassthroughLoop(handler), - ).run(rewriteBenchOptions) +describe('ssr', () => { + bench( + 'ssr rewrite passthrough (vue)', + () => runRewritePassthroughLoop(handler), + rewriteBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/selective-ssr/react/speed.bench.ts b/benchmarks/ssr/scenarios/selective-ssr/react/speed.bench.ts index ba6bd4a61d..e0e8a0e3c4 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 { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertSelectiveSanity, benchOptions, @@ -16,8 +16,6 @@ const { default: handler } = (await import( await assertSelectiveSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr selective (react)', async () => - runSelectiveLoop(handler), - ).run(benchOptions) +describe('ssr', () => { + bench('ssr selective (react)', () => runSelectiveLoop(handler), benchOptions) }) diff --git a/benchmarks/ssr/scenarios/selective-ssr/solid/speed.bench.ts b/benchmarks/ssr/scenarios/selective-ssr/solid/speed.bench.ts index 76265397ab..6a2803d45f 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 { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertSelectiveSanity, benchOptions, @@ -16,8 +16,6 @@ const { default: handler } = (await import( await assertSelectiveSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr selective (solid)', async () => - runSelectiveLoop(handler), - ).run(benchOptions) +describe('ssr', () => { + bench('ssr selective (solid)', () => runSelectiveLoop(handler), benchOptions) }) diff --git a/benchmarks/ssr/scenarios/selective-ssr/vue/speed.bench.ts b/benchmarks/ssr/scenarios/selective-ssr/vue/speed.bench.ts index ff60341b27..f3082a102d 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 { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertSelectiveSanity, benchOptions, @@ -16,8 +16,6 @@ const { default: handler } = (await import( await assertSelectiveSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr selective (vue)', async () => runSelectiveLoop(handler)).run( - benchOptions, - ) +describe('ssr', () => { + bench('ssr selective (vue)', () => runSelectiveLoop(handler), benchOptions) }) diff --git a/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts b/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts index 8be07d2643..9032280e51 100644 --- a/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/serialization/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertSerializationScenario, runRichSerializationLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertSerializationScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr dehydrate rich types (react)', async () => - runRichSerializationLoop(handler), - ).run(serializationBenchOptions) +describe('ssr', () => { + bench( + 'ssr dehydrate rich types (react)', + () => runRichSerializationLoop(handler), + 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 index c70fddc6c4..a6c8d99fb6 100644 --- a/benchmarks/ssr/scenarios/serialization/react/speed.dehydrate-plain-control.bench.ts +++ b/benchmarks/ssr/scenarios/serialization/react/speed.dehydrate-plain-control.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertSerializationScenario, runPlainSerializationLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertSerializationScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr dehydrate plain control (react)', async () => - runPlainSerializationLoop(handler), - ).run(serializationBenchOptions) +describe('ssr', () => { + bench( + 'ssr dehydrate plain control (react)', + () => runPlainSerializationLoop(handler), + serializationBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts b/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts index 70bda8c7af..3fa22ccea9 100644 --- a/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/serialization/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertSerializationScenario, runRichSerializationLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertSerializationScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr dehydrate rich types (solid)', async () => - runRichSerializationLoop(handler), - ).run(serializationBenchOptions) +describe('ssr', () => { + bench( + 'ssr dehydrate rich types (solid)', + () => runRichSerializationLoop(handler), + 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 index d7ccb16f6f..354512e09d 100644 --- a/benchmarks/ssr/scenarios/serialization/solid/speed.dehydrate-plain-control.bench.ts +++ b/benchmarks/ssr/scenarios/serialization/solid/speed.dehydrate-plain-control.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertSerializationScenario, runPlainSerializationLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertSerializationScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr dehydrate plain control (solid)', async () => - runPlainSerializationLoop(handler), - ).run(serializationBenchOptions) +describe('ssr', () => { + bench( + 'ssr dehydrate plain control (solid)', + () => runPlainSerializationLoop(handler), + serializationBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/serialization/solid/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/serialization/solid/src/routeTree.gen.ts index b9e25f918e..69b63cffe9 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 PlainIdRouteImport } from './routes/plain.$id' import { Route as RichIdRouteImport } from './routes/rich.$id' +import { Route as PlainIdRouteImport } from './routes/plain.$id' -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) +const PlainIdRoute = PlainIdRouteImport.update({ + id: '/plain/$id', + path: '/plain/$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 { - '/plain/$id': { - id: '/plain/$id' - path: '/plain/$id' - fullPath: '/plain/$id' - preLoaderRoute: typeof PlainIdRouteImport - parentRoute: typeof rootRouteImport - } '/rich/$id': { id: '/rich/$id' path: '/rich/$id' @@ -65,6 +58,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof RichIdRouteImport parentRoute: typeof rootRouteImport } + '/plain/$id': { + id: '/plain/$id' + path: '/plain/$id' + fullPath: '/plain/$id' + preLoaderRoute: typeof PlainIdRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts b/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts index 7f733dd601..d68c615fdc 100644 --- a/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/serialization/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertSerializationScenario, runRichSerializationLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertSerializationScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr dehydrate rich types (vue)', async () => - runRichSerializationLoop(handler), - ).run(serializationBenchOptions) +describe('ssr', () => { + bench( + 'ssr dehydrate rich types (vue)', + () => runRichSerializationLoop(handler), + 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 index 8efdeb6c79..875a858226 100644 --- a/benchmarks/ssr/scenarios/serialization/vue/speed.dehydrate-plain-control.bench.ts +++ b/benchmarks/ssr/scenarios/serialization/vue/speed.dehydrate-plain-control.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertSerializationScenario, runPlainSerializationLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertSerializationScenario(handler) -test('ssr', async ({ bench }) => { - await bench('ssr dehydrate plain control (vue)', async () => - runPlainSerializationLoop(handler), - ).run(serializationBenchOptions) +describe('ssr', () => { + bench( + 'ssr dehydrate plain control (vue)', + () => runPlainSerializationLoop(handler), + serializationBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/serialization/vue/src/routeTree.gen.ts b/benchmarks/ssr/scenarios/serialization/vue/src/routeTree.gen.ts index cd7b0b449b..02268c2c3c 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 PlainIdRouteImport } from './routes/plain.$id' import { Route as RichIdRouteImport } from './routes/rich.$id' +import { Route as PlainIdRouteImport } from './routes/plain.$id' -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) +const PlainIdRoute = PlainIdRouteImport.update({ + id: '/plain/$id', + path: '/plain/$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 { - '/plain/$id': { - id: '/plain/$id' - path: '/plain/$id' - fullPath: '/plain/$id' - preLoaderRoute: typeof PlainIdRouteImport - parentRoute: typeof rootRouteImport - } '/rich/$id': { id: '/rich/$id' path: '/rich/$id' @@ -65,6 +58,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof RichIdRouteImport parentRoute: typeof rootRouteImport } + '/plain/$id': { + id: '/plain/$id' + path: '/plain/$id' + fullPath: '/plain/$id' + preLoaderRoute: typeof PlainIdRouteImport + parentRoute: typeof rootRouteImport + } } } 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 fa80cdb690..149ff591ed 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnTransportScenario, runServerFnMultipartRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnTransportBench(handler) await assertServerFnTransportScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn multipart (react)', async () => - runServerFnMultipartRequestLoop(handler, context), - ).run(serverFnTransportBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn multipart (react)', + () => runServerFnMultipartRequestLoop(handler, context), + 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 index fd535ee313..43b31c609d 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnTransportScenario, runServerFnRawResponseRequestLoop, @@ -16,8 +16,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr server-fn raw-response (react)', + () => runServerFnRawResponseRequestLoop(handler, context), + 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 index 8fbce405dd..4c90ffb847 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnTransportScenario, runServerFnRawStreamRequestLoop, @@ -16,8 +16,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr server-fn raw-stream (react)', + () => runServerFnRawStreamRequestLoop(handler, context), + serverFnTransportBenchOptions, + ) }) 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 adac07cb22..aaa2028902 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnTransportScenario, runServerFnMultipartRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnTransportBench(handler) await assertServerFnTransportScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn multipart (solid)', async () => - runServerFnMultipartRequestLoop(handler, context), - ).run(serverFnTransportBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn multipart (solid)', + () => runServerFnMultipartRequestLoop(handler, context), + 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 index 843a4c97ce..661430c3ae 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnTransportScenario, runServerFnRawResponseRequestLoop, @@ -16,8 +16,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr server-fn raw-response (solid)', + () => runServerFnRawResponseRequestLoop(handler, context), + 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 index aa24d55e79..37d9b86e12 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnTransportScenario, runServerFnRawStreamRequestLoop, @@ -16,8 +16,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr server-fn raw-stream (solid)', + () => runServerFnRawStreamRequestLoop(handler, context), + serverFnTransportBenchOptions, + ) }) 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 24305cf1bc..99d266298d 100644 --- a/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fn-transport/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnTransportScenario, runServerFnMultipartRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnTransportBench(handler) await assertServerFnTransportScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn multipart (vue)', async () => - runServerFnMultipartRequestLoop(handler, context), - ).run(serverFnTransportBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn multipart (vue)', + () => runServerFnMultipartRequestLoop(handler, context), + 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 index 2eeb9a4f6b..36e1b9ed22 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnTransportScenario, runServerFnRawResponseRequestLoop, @@ -16,8 +16,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr server-fn raw-response (vue)', + () => runServerFnRawResponseRequestLoop(handler, context), + 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 index a73905004d..4c9e5dc752 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnTransportScenario, runServerFnRawStreamRequestLoop, @@ -16,8 +16,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr server-fn raw-stream (vue)', + () => runServerFnRawStreamRequestLoop(handler, context), + serverFnTransportBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts b/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts index c876772ad1..697bfe967a 100644 --- a/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnGetRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn GET (react)', async () => - runServerFnGetRequestLoop(handler, context), - ).run(serverFnBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn GET (react)', + () => runServerFnGetRequestLoop(handler, context), + 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 index 6a0cb55f78..4b1c7c7d1e 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnDocumentSsrRequestLoop, @@ -16,8 +16,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr server-fn during document ssr (react)', + () => runServerFnDocumentSsrRequestLoop(handler), + 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 index 96f1160078..1f600dd8cf 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnNotFoundRequestLoop, @@ -16,8 +16,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr server-fn not-found (react)', + () => runServerFnNotFoundRequestLoop(handler, context), + 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 index e85d5debd3..0b4b3e5d6c 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnPostRequestLoop, @@ -16,8 +16,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr server-fn POST (react)', + () => runServerFnPostRequestLoop(handler, context), + 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 index 5dae598549..d07b4ab583 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnRedirectRequestLoop, @@ -16,8 +16,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr server-fn redirect (react)', + () => runServerFnRedirectRequestLoop(handler, context), + 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 index 40d6961206..589e2ccaf3 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnSendContextRequestLoop, @@ -16,8 +16,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr server-fn send-context (react)', + () => runServerFnSendContextRequestLoop(handler, context), + serverFnBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts b/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts index f6bbdc9e73..42e57c4ce2 100644 --- a/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnGetRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn GET (solid)', async () => - runServerFnGetRequestLoop(handler, context), - ).run(serverFnBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn GET (solid)', + () => runServerFnGetRequestLoop(handler, context), + 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 index 933f61b59c..1cbe7ef20b 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnDocumentSsrRequestLoop, @@ -16,8 +16,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr server-fn during document ssr (solid)', + () => runServerFnDocumentSsrRequestLoop(handler), + 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 index 513b69f4ba..bd5cc10457 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnNotFoundRequestLoop, @@ -16,8 +16,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr server-fn not-found (solid)', + () => runServerFnNotFoundRequestLoop(handler, context), + 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 index e2ce8ad9ee..d2cf977cfa 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnPostRequestLoop, @@ -16,8 +16,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr server-fn POST (solid)', + () => runServerFnPostRequestLoop(handler, context), + 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 index 14353f1290..017ac79af0 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnRedirectRequestLoop, @@ -16,8 +16,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr server-fn redirect (solid)', + () => runServerFnRedirectRequestLoop(handler, context), + 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 index 76d3a554bd..a3d0a991d1 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnSendContextRequestLoop, @@ -16,8 +16,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr server-fn send-context (solid)', + () => runServerFnSendContextRequestLoop(handler, context), + 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 3d0bd34eaa..3db5e487b3 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 ApiFnUrlsRouteImport } from './routes/api.fn-urls' import { Route as SsrCallIdRouteImport } from './routes/ssr-call.$id' +import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', 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) +const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ + id: '/api/fn-urls', + path: '/api/fn-urls', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -68,13 +68,6 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/api/fn-urls': { - id: '/api/fn-urls' - path: '/api/fn-urls' - fullPath: '/api/fn-urls' - preLoaderRoute: typeof ApiFnUrlsRouteImport - parentRoute: typeof rootRouteImport - } '/ssr-call/$id': { id: '/ssr-call/$id' path: '/ssr-call/$id' @@ -82,6 +75,13 @@ declare module '@tanstack/solid-router' { preLoaderRoute: typeof SsrCallIdRouteImport parentRoute: typeof rootRouteImport } + '/api/fn-urls': { + id: '/api/fn-urls' + path: '/api/fn-urls' + fullPath: '/api/fn-urls' + preLoaderRoute: typeof ApiFnUrlsRouteImport + parentRoute: typeof rootRouteImport + } } } diff --git a/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts b/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts index 3f67c1a500..c4d94659d9 100644 --- a/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/server-fns/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnGetRequestLoop, @@ -16,8 +16,10 @@ const context = await setupServerFnBench(handler) await assertServerFnScenario(handler, context) -test('ssr', async ({ bench }) => { - await bench('ssr server-fn GET (vue)', async () => - runServerFnGetRequestLoop(handler, context), - ).run(serverFnBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-fn GET (vue)', + () => runServerFnGetRequestLoop(handler, context), + 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 index 56c9addca5..c6155bcead 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnDocumentSsrRequestLoop, @@ -16,8 +16,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr server-fn during document ssr (vue)', + () => runServerFnDocumentSsrRequestLoop(handler), + 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 index e9a6e31617..dca17511b8 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnNotFoundRequestLoop, @@ -16,8 +16,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr server-fn not-found (vue)', + () => runServerFnNotFoundRequestLoop(handler, context), + 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 index df9312ccd1..4c2166056a 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnPostRequestLoop, @@ -16,8 +16,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr server-fn POST (vue)', + () => runServerFnPostRequestLoop(handler, context), + 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 index 67c4611644..25741baa62 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnRedirectRequestLoop, @@ -16,8 +16,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr server-fn redirect (vue)', + () => runServerFnRedirectRequestLoop(handler, context), + 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 index 6f51ef4bab..c1c2d581ba 100644 --- 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 @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerFnScenario, runServerFnSendContextRequestLoop, @@ -16,8 +16,10 @@ 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) +describe('ssr', () => { + bench( + 'ssr server-fn send-context (vue)', + () => runServerFnSendContextRequestLoop(handler, context), + 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 0e24cd9c15..fa27fb1a5d 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 ApiFnUrlsRouteImport } from './routes/api.fn-urls' import { Route as SsrCallIdRouteImport } from './routes/ssr-call.$id' +import { Route as ApiFnUrlsRouteImport } from './routes/api.fn-urls' const IndexRoute = IndexRouteImport.update({ id: '/', path: '/', 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) +const ApiFnUrlsRoute = ApiFnUrlsRouteImport.update({ + id: '/api/fn-urls', + path: '/api/fn-urls', + getParentRoute: () => rootRouteImport, +} as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -68,13 +68,6 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/api/fn-urls': { - id: '/api/fn-urls' - path: '/api/fn-urls' - fullPath: '/api/fn-urls' - preLoaderRoute: typeof ApiFnUrlsRouteImport - parentRoute: typeof rootRouteImport - } '/ssr-call/$id': { id: '/ssr-call/$id' path: '/ssr-call/$id' @@ -82,6 +75,13 @@ declare module '@tanstack/vue-router' { preLoaderRoute: typeof SsrCallIdRouteImport parentRoute: typeof rootRouteImport } + '/api/fn-urls': { + id: '/api/fn-urls' + path: '/api/fn-urls' + fullPath: '/api/fn-urls' + preLoaderRoute: typeof ApiFnUrlsRouteImport + parentRoute: typeof rootRouteImport + } } } 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 6331216522..8e96bc8e04 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 { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerRouteMiddlewareResponse, runServerRouteMiddlewareLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertServerRouteMiddlewareResponse(handler) -test('ssr', async ({ bench }) => { - await bench('ssr server-route middleware (react)', async () => - runServerRouteMiddlewareLoop(handler), - ).run(serverRouteMiddlewareBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-route middleware (react)', + () => runServerRouteMiddlewareLoop(handler), + serverRouteMiddlewareBenchOptions, + ) }) 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 77d58e7b19..7e6fac4bbe 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 { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerRouteMiddlewareResponse, runServerRouteMiddlewareLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertServerRouteMiddlewareResponse(handler) -test('ssr', async ({ bench }) => { - await bench('ssr server-route middleware (solid)', async () => - runServerRouteMiddlewareLoop(handler), - ).run(serverRouteMiddlewareBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-route middleware (solid)', + () => runServerRouteMiddlewareLoop(handler), + serverRouteMiddlewareBenchOptions, + ) }) 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 3d03b9c1fa..e67ca0a420 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 { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerRouteMiddlewareResponse, runServerRouteMiddlewareLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertServerRouteMiddlewareResponse(handler) -test('ssr', async ({ bench }) => { - await bench('ssr server-route middleware (vue)', async () => - runServerRouteMiddlewareLoop(handler), - ).run(serverRouteMiddlewareBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-route middleware (vue)', + () => runServerRouteMiddlewareLoop(handler), + serverRouteMiddlewareBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-routes/react/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes/react/speed.bench.ts index 631314148a..1bdb7946b2 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 { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerRouteResponse, runServerRouteLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertServerRouteResponse(handler) -test('ssr', async ({ bench }) => { - await bench('ssr server-route (react)', async () => - runServerRouteLoop(handler), - ).run(serverRouteBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-route (react)', + () => runServerRouteLoop(handler), + serverRouteBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-routes/solid/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes/solid/speed.bench.ts index 4788d31854..ce3e1f8a21 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 { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerRouteResponse, runServerRouteLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertServerRouteResponse(handler) -test('ssr', async ({ bench }) => { - await bench('ssr server-route (solid)', async () => - runServerRouteLoop(handler), - ).run(serverRouteBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-route (solid)', + () => runServerRouteLoop(handler), + serverRouteBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/server-routes/vue/speed.bench.ts b/benchmarks/ssr/scenarios/server-routes/vue/speed.bench.ts index 09c0bbe90b..f2b9e27acb 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 { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertServerRouteResponse, runServerRouteLoop, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertServerRouteResponse(handler) -test('ssr', async ({ bench }) => { - await bench('ssr server-route (vue)', async () => - runServerRouteLoop(handler), - ).run(serverRouteBenchOptions) +describe('ssr', () => { + bench( + 'ssr server-route (vue)', + () => runServerRouteLoop(handler), + serverRouteBenchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts b/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts index eb4c9dc1d6..c1dbf38ae5 100644 --- a/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts +++ b/benchmarks/ssr/scenarios/streaming/react/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertStreamingSanity, benchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertStreamingSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr streaming deferred (react)', async () => - runStreamingLoop(handler), - ).run(benchOptions) +describe('ssr', () => { + bench( + 'ssr streaming deferred (react)', + () => runStreamingLoop(handler), + benchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts b/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts index 19d5817d32..0828715220 100644 --- a/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts +++ b/benchmarks/ssr/scenarios/streaming/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertStreamingSanity, benchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertStreamingSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr streaming deferred (solid)', async () => - runStreamingLoop(handler), - ).run(benchOptions) +describe('ssr', () => { + bench( + 'ssr streaming deferred (solid)', + () => runStreamingLoop(handler), + benchOptions, + ) }) diff --git a/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts b/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts index 42473fc694..a484f95d6a 100644 --- a/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts +++ b/benchmarks/ssr/scenarios/streaming/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { assertStreamingSanity, benchOptions, @@ -16,8 +16,10 @@ const { default: handler } = (await import( await assertStreamingSanity(handler) -test('ssr', async ({ bench }) => { - await bench('ssr streaming deferred (vue)', async () => - runStreamingLoop(handler), - ).run(benchOptions) +describe('ssr', () => { + bench( + 'ssr streaming deferred (vue)', + () => runStreamingLoop(handler), + benchOptions, + ) }) diff --git a/benchmarks/ssr/solid/speed.bench.ts b/benchmarks/ssr/solid/speed.bench.ts index 2f72977612..0c4317415d 100644 --- a/benchmarks/ssr/solid/speed.bench.ts +++ b/benchmarks/ssr/solid/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { runSsrRequestLoop } from '../bench-utils' import type { StartRequestHandler } from '../bench-utils' @@ -11,12 +11,14 @@ const { default: handler } = (await import( default: StartRequestHandler } -test('ssr', async ({ bench }) => { - await bench('ssr request loop (solid)', async () => - runSsrRequestLoop(handler, { seed: benchmarkSeed }), - ).run({ - warmupIterations: 100, - time: 10_000, - throws: true, - }) +describe('ssr', () => { + bench( + 'ssr request loop (solid)', + () => runSsrRequestLoop(handler, { seed: benchmarkSeed }), + { + warmupIterations: 100, + time: 10_000, + throws: true, + }, + ) }) diff --git a/benchmarks/ssr/vue/speed.bench.ts b/benchmarks/ssr/vue/speed.bench.ts index 57b59e0504..849f042e3c 100644 --- a/benchmarks/ssr/vue/speed.bench.ts +++ b/benchmarks/ssr/vue/speed.bench.ts @@ -1,4 +1,4 @@ -import { test } from 'vitest' +import { bench, describe } from 'vitest' import { runSsrRequestLoop } from '../bench-utils' import type { StartRequestHandler } from '../bench-utils' @@ -11,12 +11,14 @@ const { default: handler } = (await import( default: StartRequestHandler } -test('ssr', async ({ bench }) => { - await bench('ssr request loop (vue)', async () => - runSsrRequestLoop(handler, { seed: benchmarkSeed }), - ).run({ - warmupIterations: 100, - time: 10_000, - throws: true, - }) +describe('ssr', () => { + bench( + 'ssr request loop (vue)', + () => runSsrRequestLoop(handler, { seed: benchmarkSeed }), + { + warmupIterations: 100, + time: 10_000, + throws: true, + }, + ) }) diff --git a/docs/AGENTS.md b/docs/AGENTS.md deleted file mode 100644 index ab2d4117e2..0000000000 --- a/docs/AGENTS.md +++ /dev/null @@ -1,4 +0,0 @@ -# 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 7c94d484d1..ad3e07fad7 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 with Vite, Rspack/Rsbuild or Webpack. With Esbuild, setting it to `true` is an error. +This feature is only available if you are using the TanStack Router Bundler Plugin. 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/RouterEventsType.md b/docs/router/api/router/RouterEventsType.md index c27887fba1..c79bb47f81 100644 --- a/docs/router/api/router/RouterEventsType.md +++ b/docs/router/api/router/RouterEventsType.md @@ -47,6 +47,9 @@ type RouterEvents = { hrefChanged: boolean hashChanged: boolean } + onInjectedHtml: { + type: 'onInjectedHtml' + } onRendered: { type: 'onRendered' fromLocation?: ParsedLocation @@ -64,7 +67,7 @@ Once an event is emitted, the following properties will be present on the event ### `type` property -- Type: `onBeforeNavigate | onBeforeLoad | onLoad | onBeforeRouteMount | onResolved | onRendered` +- Type: `onBeforeNavigate | onBeforeLoad | onLoad | onBeforeRouteMount | onResolved | onRendered | onInjectedHtml` - 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 31f410b208..3556f4ab24 100644 --- a/docs/router/api/router/RouterOptionsType.md +++ b/docs/router/api/router/RouterOptionsType.md @@ -375,10 +375,9 @@ const router = createRouter({ ### `pathParamsAllowedCharacters` property -- Type: `ReadonlyArray<';' | ':' | '@' | '&' | '=' | '+' | '$' | ','>` +- Type: `Array<';' | ':' | '@' | '&' | '=' | '+' | '$' | ','>` - 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/RouterType.md b/docs/router/api/router/RouterType.md index 3fde90e32e..cf8fdebeae 100644 --- a/docs/router/api/router/RouterType.md +++ b/docs/router/api/router/RouterType.md @@ -11,9 +11,8 @@ An instance of the `Router` has the following properties and methods: ### `.update` method -- Type: `(newOptions: Omit) => void` +- Type: `(newOptions: RouterOptions) => 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 diff --git a/docs/router/api/router/linkComponent.md b/docs/router/api/router/linkComponent.md index 478271a208..a8227913b5 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, set [pathParamsAllowedCharacters](../router/RouterOptionsType#pathparamsallowedcharacters-property) when creating the router. This setting cannot be changed on an existing router instance. +To opt-out, update the [pathParamsAllowedCharacters](../router/RouterOptionsType#pathparamsallowedcharacters-property) config on the router ```tsx import { createRouter } from '@tanstack/react-router' diff --git a/docs/router/eslint/create-route-property-order.md b/docs/router/eslint/create-route-property-order.md index 453fd64acc..c22aa7c52d 100644 --- a/docs/router/eslint/create-route-property-order.md +++ b/docs/router/eslint/create-route-property-order.md @@ -37,10 +37,7 @@ import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/path')({ loader: async ({ context }) => { - await context.queryClient.query({ - ...getQueryOptions(context.hello), - staleTime: 'static', - }) + await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) }, beforeLoad: () => ({ hello: 'world' }), }) @@ -58,10 +55,7 @@ import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/path')({ loader: async ({ context }) => { - await context.queryClient.query({ - ...getQueryOptions(context.hello), - staleTime: 'static', - }) + await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) }, beforeLoad: () => ({ hello: 'world' }), }) @@ -86,10 +80,7 @@ import { createFileRoute } from '@tanstack/react-router' export const Route = createFileRoute('/path')({ beforeLoad: () => ({ hello: 'world' }), loader: async ({ context }) => { - await context.queryClient.query({ - ...getQueryOptions(context.hello), - staleTime: 'static', - }) + await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) }, }) ``` @@ -107,10 +98,7 @@ import { createFileRoute } from '@tanstack/solid-router' export const Route = createFileRoute('/path')({ beforeLoad: () => ({ hello: 'world' }), loader: async ({ context }) => { - await context.queryClient.query({ - ...getQueryOptions(context.hello), - staleTime: 'static', - }) + await context.queryClient.ensureQueryData(getQueryOptions(context.hello)) }, }) ``` diff --git a/docs/router/guide/automatic-code-splitting.md b/docs/router/guide/automatic-code-splitting.md index 859a19ff09..be599845bc 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. It is available with Vite, Rspack/Rsbuild and Webpack, not with Esbuild. +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. ```ts // vite.config.ts diff --git a/docs/router/guide/deferred-data-loading.md b/docs/router/guide/deferred-data-loading.md index f378d7adbf..9956542ebd 100644 --- a/docs/router/guide/deferred-data-loading.md +++ b/docs/router/guide/deferred-data-loading.md @@ -90,16 +90,15 @@ So, instead of using `defer` and `Await`, you'll instead want to use the Route's ```tsx // src/routes/posts.$postId.tsx import { createFileRoute } from '@tanstack/react-router' -import { noop } from '@tanstack/react-query' import { slowDataOptions, fastDataOptions } from '~/api/query-options' export const Route = createFileRoute('/posts/$postId')({ loader: async ({ context: { queryClient } }) => { // Kick off the fetching of some slower data, but do not await it - void queryClient.query(slowDataOptions()).catch(noop) + queryClient.prefetchQuery(slowDataOptions()) // Fetch and await some data that resolves quickly - await queryClient.query({ ...fastDataOptions(), staleTime: 'static' }) + await queryClient.ensureQueryData(fastDataOptions()) }, }) ``` @@ -109,16 +108,15 @@ export const Route = createFileRoute('/posts/$postId')({ ```tsx // src/routes/posts.$postId.tsx import { createFileRoute } from '@tanstack/solid-router' -import { noop } from '@tanstack/solid-query' import { slowDataOptions, fastDataOptions } from '~/api/query-options' export const Route = createFileRoute('/posts/$postId')({ loader: async ({ context: { queryClient } }) => { // Kick off the fetching of some slower data, but do not await it - void queryClient.query(slowDataOptions()).catch(noop) + queryClient.prefetchQuery(slowDataOptions()) // Fetch and await some data that resolves quickly - await queryClient.query({ ...fastDataOptions(), staleTime: 'static' }) + await queryClient.ensureQueryData(fastDataOptions()) }, }) ``` diff --git a/docs/router/guide/external-data-loading.md b/docs/router/guide/external-data-loading.md index 4ffb318686..c044db7757 100644 --- a/docs/router/guide/external-data-loading.md +++ b/docs/router/guide/external-data-loading.md @@ -6,7 +6,7 @@ title: External Data Loading > [!IMPORTANT] > This guide is geared towards external state management libraries and their integration with TanStack Router for data fetching, ssr, hydration/dehydration and streaming. If you haven't read the standard [Data Loading](./data-loading.md) guide, please do so first. -Router can coordinate loaders and an existing API without Start. If you also want an integrated server runtime and typed server functions for your React application, follow [TanStack Query with Start](/start/latest/docs/framework/react/guide/tanstack-query) for request-scoped SSR, hydration, and mutation invalidation with a tested example. +For a full-stack React application, follow [TanStack Query with Start](/start/latest/docs/framework/react/guide/tanstack-query) for request-scoped SSR, hydration, and mutation invalidation with a tested example. ## To **Store** or to **Coordinate**? @@ -84,8 +84,7 @@ const postsQueryOptions = queryOptions({ export const Route = createFileRoute('/posts')({ // Use the `loader` option to ensure that the data is loaded - loader: () => - queryClient.query({ ...postsQueryOptions, staleTime: 'static' }), + loader: () => queryClient.ensureQueryData(postsQueryOptions), component: () => { // Read the data from the cache and subscribe to updates const { @@ -109,8 +108,7 @@ When an error occurs while using `suspense` with `TanStack Query`, you need to l ```tsx export const Route = createFileRoute('/')({ - loader: () => - queryClient.query({ ...postsQueryOptions, staleTime: 'static' }), + loader: () => queryClient.ensureQueryData(postsQueryOptions), errorComponent: ({ error, reset }) => { const router = useRouter() const queryErrorResetBoundary = useQueryErrorResetBoundary() diff --git a/docs/router/guide/path-params.md b/docs/router/guide/path-params.md index d326eabb4b..7ebaaad19e 100644 --- a/docs/router/guide/path-params.md +++ b/docs/router/guide/path-params.md @@ -1395,8 +1395,6 @@ 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/router-context.md b/docs/router/guide/router-context.md index 347082106f..5fc4001010 100644 --- a/docs/router/guide/router-context.md +++ b/docs/router/guide/router-context.md @@ -278,10 +278,9 @@ Then, in your route: export const Route = createFileRoute('/todos')({ component: Todos, loader: async ({ context }) => { - await context.queryClient.query({ + await context.queryClient.ensureQueryData({ queryKey: ['todos', { userId: user.id }], queryFn: fetchTodos, - staleTime: 'static', }) }, }) diff --git a/docs/router/guide/ssr.md b/docs/router/guide/ssr.md index 46a0941e7c..ae3cdbef7c 100644 --- a/docs/router/guide/ssr.md +++ b/docs/router/guide/ssr.md @@ -158,8 +158,6 @@ 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 @@ -262,9 +260,6 @@ 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 3faaed79e7..2adffc58c5 100644 --- a/docs/router/guide/type-safety.md +++ b/docs/router/guide/type-safety.md @@ -137,13 +137,12 @@ 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.query` 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.ensureQueryData` in a `loader`. ```tsx export const Route = createFileRoute('/posts/$postId/deep')({ - // (ctx: LoaderFnContext) => Promise loader: ({ context: { queryClient }, params: { postId } }) => - queryClient.query({ ...postQueryOptions(postId), staleTime: 'static' }), + queryClient.ensureQueryData(postQueryOptions(postId)), component: PostDeepComponent, }) @@ -155,16 +154,12 @@ 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.query({ - ...postQueryOptions(postId), - staleTime: 'static', - }) + await queryClient.ensureQueryData(postQueryOptions(postId)) }, component: PostDeepComponent, }) diff --git a/docs/router/how-to/setup-testing.md b/docs/router/how-to/setup-testing.md index 104cbedc0d..48afa122f4 100644 --- a/docs/router/how-to/setup-testing.md +++ b/docs/router/how-to/setup-testing.md @@ -659,10 +659,9 @@ describe('React Query Integration', () => { path: '/posts', component: PostsList, loader: ({ context: { queryClient } }) => - queryClient.query({ + queryClient.ensureQueryData({ queryKey: ['posts'], queryFn: mockFetchPosts, - staleTime: 'static', }), }) diff --git a/docs/router/installation/with-esbuild.md b/docs/router/installation/with-esbuild.md index 8ecd9b8d0a..b5cad0622c 100644 --- a/docs/router/installation/with-esbuild.md +++ b/docs/router/installation/with-esbuild.md @@ -25,6 +25,7 @@ export default { plugins: [ tanstackRouter({ target: 'react', + autoCodeSplitting: true, }), ], } @@ -49,7 +50,10 @@ const ctx = await esbuild.context({ format: 'esm', target: ['esnext'], sourcemap: true, - plugins: [solidPlugin(), tanstackRouter({ target: 'solid' })], + plugins: [ + solidPlugin(), + tanstackRouter({ target: 'solid', autoCodeSplitting: true }), + ], }) if (isDev) { @@ -68,9 +72,6 @@ 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 707f90900c..fd174187b5 100644 --- a/docs/router/integrations/query.md +++ b/docs/router/integrations/query.md @@ -152,7 +152,7 @@ Preload critical data in the route `loader` to avoid waterfalls and loading flas -# Blocking `query` in loader +# React ```tsx title="src/routes/posts.tsx" import { queryOptions, useSuspenseQuery, useQuery } from '@tanstack/react-query' @@ -165,12 +165,7 @@ const postsQuery = queryOptions({ export const Route = createFileRoute('/posts')({ // Ensure the data is in the cache before render - loader: ({ context }) => - context.queryClient.query({ - ...postsQuery, - // returns data from cache immediately, otherwise executes a fetch - staleTime: 'static', - }), + loader: ({ context }) => context.queryClient.ensureQueryData(postsQuery), component: PostsPage, }) @@ -185,15 +180,15 @@ function PostsPage() { ### Prefetching and streaming -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. +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. -# Non-blocking `query` in loader +# React ```tsx title="src/routes/users.$id.tsx" import { createFileRoute } from '@tanstack/react-router' -import { noop, queryOptions, useQuery } from '@tanstack/react-query' +import { queryOptions, useQuery } from '@tanstack/react-query' const userQuery = (id: string) => queryOptions({ @@ -202,18 +197,15 @@ const userQuery = (id: string) => }) export const Route = createFileRoute('/user/$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) + 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)) }, }) ``` -> [!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/start/config.json b/docs/start/config.json index 36af0e6e0d..4c7b90db47 100644 --- a/docs/start/config.json +++ b/docs/start/config.json @@ -36,10 +36,6 @@ { "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" } ] }, @@ -57,10 +53,6 @@ { "label": "Build from Scratch", "to": "framework/solid/build-from-scratch" - }, - { - "label": "Migrate from the Release Candidate", - "to": "framework/solid/migrate-from-release-candidate" } ] } @@ -523,6 +515,53 @@ } ] }, + { + "label": "Learn Start", + "children": [], + "frameworks": [ + { + "label": "react", + "children": [ + { + "label": "Course overview", + "to": "framework/react/tutorial/learn-start" + }, + { + "label": "1. Setup", + "to": "framework/react/tutorial/learn-start/setup" + }, + { + "label": "2. Routes", + "to": "framework/react/tutorial/learn-start/routes" + }, + { + "label": "3. Data", + "to": "framework/react/tutorial/learn-start/data" + }, + { + "label": "4. Forms", + "to": "framework/react/tutorial/learn-start/forms" + }, + { + "label": "5. Authentication", + "to": "framework/react/tutorial/learn-start/authentication" + }, + { + "label": "6. SEO", + "to": "framework/react/tutorial/learn-start/seo" + }, + { + "label": "7. Deployment", + "to": "framework/react/tutorial/learn-start/deployment" + }, + { + "label": "8. Tests", + "to": "framework/react/tutorial/learn-start/tests" + } + ] + } + ] + }, { "label": "Tutorials", "children": [], diff --git a/docs/start/framework/react/guide/authentication-overview.md b/docs/start/framework/react/guide/authentication-overview.md index e80ba97f8c..a8ccd4bbb4 100644 --- a/docs/start/framework/react/guide/authentication-overview.md +++ b/docs/start/framework/react/guide/authentication-overview.md @@ -116,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 written with `setCookie`, read with `getCookie` +- **Session Management**: HTTP-only cookies via `setResponseHeader`, read with `getRequestHeader` - **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 103e9c4455..4fbd7e9e22 100644 --- a/docs/start/framework/react/guide/authentication-server-primitives.md +++ b/docs/start/framework/react/guide/authentication-server-primitives.md @@ -28,39 +28,47 @@ Whichever you choose, the cookie flags matter: ```ts // src/server/session.ts import { - deleteCookie, - getCookie, - setCookie, + getRequestHeader, + setResponseHeader, } 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) { - setCookie(SESSION_COOKIE, token, { - ...sessionCookieOptions, - maxAge: ONE_DAY, - }) + setResponseHeader( + 'Set-Cookie', + [ + `${SESSION_COOKIE}=${token}`, + `HttpOnly`, + `Secure`, + `SameSite=Lax`, + `Path=/`, + `Max-Age=${ONE_DAY}`, + ].join('; '), + ) } export function clearSessionCookie() { - deleteCookie(SESSION_COOKIE, sessionCookieOptions) + setResponseHeader( + 'Set-Cookie', + `${SESSION_COOKIE}=; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=0`, + ) } export function readSessionToken(): string | null { - return getCookie(SESSION_COOKIE) ?? 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 } ``` -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. | @@ -161,7 +169,7 @@ For OAuth authorization-code flow: // src/server/oauth.functions.ts import { createServerFn } from '@tanstack/react-start' import { redirect } from '@tanstack/react-router' -import { setCookie } from '@tanstack/react-start/server' +import { setResponseHeader } from '@tanstack/react-start/server' import crypto from 'node:crypto' const OAUTH_STATE_COOKIE = '__Host-oauth' @@ -182,13 +190,10 @@ export const startOAuth = createServerFn({ method: 'GET' }).handler( crypto.createHash('sha256').update(verifier).digest(), ) - setCookie(OAUTH_STATE_COOKIE, signed({ state, verifier }), { - httpOnly: true, - secure: true, - sameSite: 'lax', - path: '/', - maxAge: 600, - }) + setResponseHeader( + 'Set-Cookie', + `${OAUTH_STATE_COOKIE}=${signed({ state, verifier })}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=600`, + ) throw redirect({ href: diff --git a/docs/start/framework/react/guide/authentication.md b/docs/start/framework/react/guide/authentication.md index c77c681ee0..dd8adcebee 100644 --- a/docs/start/framework/react/guide/authentication.md +++ b/docs/start/framework/react/guide/authentication.md @@ -35,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 server functions, request and cookie utilities, and route protection. Session storage and authentication come from your application or a library you choose. +TanStack Start provides the tools for both through server functions, sessions, and route protection. > 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. @@ -48,7 +48,6 @@ 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' }) @@ -62,9 +61,11 @@ export const loginFn = createServerFn({ method: 'POST' }) } // Create session - const session = await getAppSession() - session.userId = user.id - await session.save() + const session = await useAppSession() + await session.update({ + userId: user.id, + email: user.email, + }) // Redirect to protected area throw redirect({ to: '/dashboard' }) @@ -72,16 +73,16 @@ export const loginFn = createServerFn({ method: 'POST' }) // Logout server function export const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await getAppSession() - session.destroy() + const session = await useAppSession() + await session.clear() throw redirect({ to: '/' }) }) // Get current user export const getCurrentUserFn = createServerFn({ method: 'GET' }).handler( async () => { - const session = await getAppSession() - const userId = session.userId + const session = await useAppSession() + const userId = session.data.userId if (!userId) { return null @@ -95,53 +96,33 @@ export const getCurrentUserFn = createServerFn({ method: 'GET' }).handler( ### 2. Session Management -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. +TanStack Start provides secure HTTP-only cookie sessions: ```tsx -// utils/session.ts — import only from server code -import { getIronSession } from 'iron-session' -import { getCookie, setCookie } from '@tanstack/react-start/server' +// utils/session.ts +import { useSession } from '@tanstack/react-start/server' type SessionData = { - userId: string - oauthState: string + userId?: string + email?: string + role?: string } -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: '/', - }, +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, }, - ) + }) } ``` -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 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`. @@ -273,9 +254,8 @@ export const registerFn = createServerFn({ method: 'POST' }) }) // Create session - const session = await getAppSession() - session.userId = user.id - await session.save() + const session = await useAppSession() + await session.update({ userId: user.id }) return { success: true, user: { id: user.id, email: user.email } } }) @@ -343,9 +323,8 @@ export const initiateOAuthFn = createServerFn({ method: 'POST' }) const state = generateRandomState() // Store state in session for CSRF protection - const session = await getAppSession() - session.oauthState = state - await session.save() + const session = await useAppSession() + await session.update({ oauthState: state }) // Generate OAuth URL const authUrl = generateOAuthUrl(provider, state) @@ -408,9 +387,21 @@ const hashedPassword = await bcrypt.hash(password, saltRounds) ### 2. Session Security -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. +```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 + }, + }) +} +``` ### 3. Rate Limiting @@ -589,14 +580,16 @@ 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 ttl = data.rememberMe ? 30 * 24 * 60 * 60 : 8 * 60 * 60 - const session = await getAppSession(ttl) - session.userId = user.id - await session.save() + 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 + }, + ) return { success: true } }) @@ -624,6 +617,7 @@ 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/deferred-hydration.md b/docs/start/framework/react/guide/deferred-hydration.md index ba07d65b24..1dc4760fa7 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 { noop, useQueryClient } from '@tanstack/react-query' +import { useQueryClient } from '@tanstack/react-query' import { Hydrate } from '@tanstack/react-start' import { visible } from '@tanstack/react-start/hydration' @@ -255,10 +255,8 @@ function DeferredReviews() { { - await Promise.all([ - preload(), - queryClient.query(reviewsQueryOptions).catch(noop), - ]) + await preload() + await queryClient.prefetchQuery(reviewsQueryOptions) }} > diff --git a/docs/start/framework/react/guide/early-hints.md b/docs/start/framework/react/guide/early-hints.md index 2341215022..a5913952e6 100644 --- a/docs/start/framework/react/guide/early-hints.md +++ b/docs/start/framework/react/guide/early-hints.md @@ -164,7 +164,6 @@ 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 94fbb52501..f472a3a26a 100644 --- a/docs/start/framework/react/guide/environment-functions.md +++ b/docs/start/framework/react/guide/environment-functions.md @@ -121,37 +121,3 @@ 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/hosting.md b/docs/start/framework/react/guide/hosting.md index 2d02f881b3..5b4a8c2661 100644 --- a/docs/start/framework/react/guide/hosting.md +++ b/docs/start/framework/react/guide/hosting.md @@ -116,32 +116,6 @@ 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_ @@ -501,7 +475,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, this should be `./.output`) + - **Output directory:** `./dist` (if you're using Nitro v2 or v3, 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 451d405f81..8bf47c729a 100644 --- a/docs/start/framework/react/guide/import-protection.md +++ b/docs/start/framework/react/guide/import-protection.md @@ -3,6 +3,8 @@ 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/path-aliases.md b/docs/start/framework/react/guide/path-aliases.md index bd75dc01ed..ff9735df83 100644 --- a/docs/start/framework/react/guide/path-aliases.md +++ b/docs/start/framework/react/guide/path-aliases.md @@ -26,7 +26,9 @@ After updating your `tsconfig.json` file, configure your build tool so it resolv # Vite -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: +## 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: ```ts // vite.config.ts @@ -40,6 +42,31 @@ 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/rendering-markdown.md b/docs/start/framework/react/guide/rendering-markdown.md index bf644124d9..4258d6f4f1 100644 --- a/docs/start/framework/react/guide/rendering-markdown.md +++ b/docs/start/framework/react/guide/rendering-markdown.md @@ -3,85 +3,191 @@ id: rendering-markdown title: Rendering Markdown --- -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. +This guide covers two methods for importing and rendering markdown content in your TanStack Start application: -This guide covers static posts loaded with Content Collections and remote content fetched through a server function. Both use the same Markdown component. +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 -## Rendering Markdown +Both methods share a common rendering pipeline using the `unified` ecosystem. -Install TanStack Markdown: +## Setting Up the Markdown Processor + +Both approaches use the same markdown-to-HTML processing pipeline. First, install the required dependencies: ```bash -npm install @tanstack/markdown +npm install unified remark-parse remark-gfm remark-rehype rehype-raw rehype-slug rehype-autolink-headings rehype-stringify shiki html-react-parser gray-matter ``` -Create a shared component that accepts either Markdown source or a parsed document: +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: ```tsx // src/components/Markdown.tsx -import { Markdown as ReactMarkdown } from '@tanstack/markdown/react' -import type { MarkdownDocument } from '@tanstack/markdown' +import parse, { type HTMLReactParserOptions, Element } from 'html-react-parser' +import { renderMarkdown, type MarkdownResult } from '~/utils/markdown' type MarkdownProps = { - content: string | MarkdownDocument + content: string className?: string } export function Markdown({ content, className }: MarkdownProps) { - return ( -
- {content} -
- ) + 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)}
} ``` -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. +## Method 1: Static Markdown with content-collections -Use the `components` prop to customize elements, for example to lazy-load images: +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. -```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 +### Installation ```bash -npm install -D @content-collections/core @content-collections/vite zod +npm install @content-collections/core @content-collections/vite ``` -```ts +### Configuration + +Create a `content-collections.ts` file in your project root: + +```tsx // content-collections.ts import { defineCollection, defineConfig } from '@content-collections/core' -import { z } from 'zod' +import matter from 'gray-matter' + +function extractFrontMatter(content: string) { + const { data, content: body, excerpt } = matter(content, { excerpt: true }) + return { data, body, excerpt: excerpt || '' } +} const posts = defineCollection({ name: 'posts', - directory: './src/blog', + directory: './src/blog', // Directory containing your .md files include: '*.md', - schema: z.object({ + schema: (z) => ({ title: z.string(), - 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, + published: z.string().date(), + description: z.string().optional(), + authors: z.string().array(), }), + 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({ @@ -89,56 +195,40 @@ export default defineConfig({ }) ``` -Content Collections already separates frontmatter from `content`, so this transform does not need a second frontmatter parser. +### Vite Integration -Add the plugin to your existing Vite configuration, keeping any deployment plugins your app needs: +Add the content-collections plugin to your Vite config: -```ts -// vite.config.ts +```tsx +// app.config.ts +import { defineConfig } from '@tanstack/react-start/config' 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({ - plugins: [ - contentCollections(), - tsConfigPaths({ projects: ['./tsconfig.json'] }), - tanstackStart(), - viteReact(), - ], + vite: { + plugins: [contentCollections()], + }, }) ``` -Add the generated collection alias to your existing `tsconfig.json`: +### Creating Blog Posts -```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`: +Create markdown files in your designated directory: ````markdown ---- +## + title: Hello World -published: '2026-01-15' -description: My first blog post +published: 2024-01-15 authors: - - Jane Doe + +- Jane Doe + description: My first blog post + --- +![Hero Image](/images/hero.jpg) + Welcome to my blog! This is my first post. ## Getting Started @@ -150,11 +240,13 @@ console.log('Hello, world!') ``` ```` -### Listing Posts +### Using the Collection + +Access your posts through the generated collection: ```tsx // src/routes/blog.index.tsx -import { createFileRoute, Link } from '@tanstack/react-router' +import { createFileRoute } from '@tanstack/react-router' import { allPosts } from 'content-collections' export const Route = createFileRoute('/blog/')({ @@ -162,30 +254,31 @@ export const Route = createFileRoute('/blog/')({ }) function BlogIndex() { - const sortedPosts = [...allPosts].sort((a, b) => - b.published.localeCompare(a.published), + // Posts are sorted by published date + const sortedPosts = allPosts.sort( + (a, b) => new Date(b.published).getTime() - new Date(a.published).getTime(), ) return ( -
+

Blog

    {sortedPosts.map((post) => (
  • - {post.title} +

    {post.title}

    +

    {post.excerpt}

    + {post.published} -

    {post.description}

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

{post.title}

-

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

+
+

{post.title}

+

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

+
) } ``` -The renderer parses the Markdown synchronously and renders React elements on both the server and client. +## Method 2: Dynamic Markdown from Remote Sources -## Remote Markdown with a Server Function +For content stored externally (like GitHub repositories), you can fetch and render markdown dynamically using server functions. -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: - -```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' - -export const fetchDocs = createServerFn({ method: 'GET' }) - .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 document: ${response.status}`) - } - - const { data, content } = matter(await response.text()) - - return { - title: typeof data.title === 'string' ? data.title : slug, - document: parseMarkdown(content), - } - }) -``` +### Creating a Fetch Utility ```tsx -// src/routes/docs.$slug.tsx -import { createFileRoute } from '@tanstack/react-router' -import { Markdown } from '~/components/Markdown' -import { fetchDocs } from '~/utils/docs' +// src/utils/docs.server.ts +import { createServerFn } from '@tanstack/react-start' +import matter from 'gray-matter' -export const Route = createFileRoute('/docs/$slug')({ - loader: ({ params }) => fetchDocs({ data: params.slug }), +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}`, + }, + }) + + if (!response.ok) { + throw new Error(`Failed to fetch: ${response.status}`) + } + + const rawContent = await response.text() + const { data: frontmatter, content } = matter(rawContent) + + return { + frontmatter, + content, + filePath, + } + }) +``` + +### 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 +import { createFileRoute } from '@tanstack/react-router' +import { fetchDocs } from '~/utils/docs.server' +import { Markdown } from '~/components/Markdown' + +export const Route = createFileRoute('/docs/$path')({ + loader: async ({ params }) => { + return fetchDocs({ + data: { + repo: 'your-org/your-repo', + branch: 'main', + filePath: `docs/${params.path}.md`, + }, + }) + }, component: DocsPage, }) function DocsPage() { - const { title, document } = Route.useLoaderData() + const { frontmatter, content } = Route.useLoaderData() return (
-

{title}

- +

{frontmatter.title}

+
) } ``` -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. +### Fetching Directory Contents -## Syntax Highlighting with TanStack Highlight - -Install [TanStack Highlight](https://tanstack.com/highlight/latest/docs/overview). The Markdown adapter requires version `0.0.6` or newer: - -```bash -npm install @tanstack/highlight -``` - -Register the languages your content uses and create the Markdown adapter: - -```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' - -const highlighter = createHighlighter({ - languages: [plaintext, js, ts, tsx], -}) - -export const highlightMarkdownCode = - createTanStackMarkdownHighlighter(highlighter) -``` - -Update the shared component to pass the highlighter and include its theme styles: +To build navigation from a GitHub directory: ```tsx -// 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 +// src/utils/docs.server.ts +type GitHubContent = { + name: string + path: string + type: 'file' | 'dir' } -export function Markdown({ content, className }: MarkdownProps) { - return ( -
- - - {content} - -
+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, + })) + }) +``` + +## Adding Syntax Highlighting with Shiki + +For code blocks with syntax highlighting, integrate Shiki into your markdown processor: + +```tsx +// src/utils/markdown.ts +import { codeToHtml } from 'shiki' + +// 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', + }, + }) +} +``` + +Then handle code blocks in your Markdown component: + +```tsx +// In your Markdown component's replace function +if (domNode.name === 'pre') { + const codeElement = domNode.children.find( + (child) => child instanceof Element && child.name === 'code', ) + if (codeElement) { + const className = codeElement.attribs.class || '' + const language = className.replace('language-', '') || 'text' + const code = getText(codeElement) + + return + } } ``` -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.
+## Summary
 
-## Table of Contents
+| 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 |
 
-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.
+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.
diff --git a/docs/start/framework/react/guide/seo.md b/docs/start/framework/react/guide/seo.md
index 1a202503a8..5b8fd3898c 100644
--- a/docs/start/framework/react/guide/seo.md
+++ b/docs/start/framework/react/guide/seo.md
@@ -7,6 +7,8 @@ description: Configure SEO in TanStack Start with page metadata, canonical URLs,
 > [!NOTE]
 > Looking to optimize for AI assistants and LLMs? See the [Generative Engine Optimization (GEO) guide](./geo).
 
+For a runnable content app, follow [SEO for Published Notes](../tutorial/learn-start/seo). Its checkpoint verifies server HTML, canonical URLs, structured data, social images, redirects, a sitemap, and private-draft exclusions.
+
 ## What is SEO, really?
 
 SEO (Search Engine Optimization) is often misunderstood as simply "showing up on Google" or a checkbox that a library can magically provide. In reality, SEO is a broad discipline focused on delivering valuable content that people need and making it easy for them to find.
@@ -129,30 +131,34 @@ export const Route = createFileRoute('/posts/$postId')({
     const post = await fetchPost(params.postId)
     return { post }
   },
-  head: ({ loaderData }) => ({
-    meta: [{ title: loaderData.post.title }],
-    scripts: [
-      {
-        type: 'application/ld+json',
-        children: JSON.stringify({
-          '@context': 'https://schema.org',
-          '@type': 'Article',
-          headline: loaderData.post.title,
-          description: loaderData.post.excerpt,
-          image: loaderData.post.coverImage,
-          author: {
-            '@type': 'Person',
-            name: loaderData.post.author.name,
+  head: ({ loaderData }) => {
+    if (!loaderData) {
+      return {}
+    }
+    const { post } = loaderData
+    return {
+      meta: [
+        { title: post.title },
+        {
+          'script:ld+json': {
+            '@context': 'https://schema.org',
+            '@type': 'Article',
+            headline: post.title,
+            description: post.excerpt,
+            image: post.coverImage,
+            author: { '@type': 'Person', name: post.author.name },
+            datePublished: post.publishedAt,
           },
-          datePublished: loaderData.post.publishedAt,
-        }),
-      },
-    ],
-  }),
+        },
+      ],
+    }
+  },
   component: PostPage,
 })
 ```
 
+Use the `script:ld+json` meta entry to let Router serialize and escape the object. A raw `JSON.stringify` string passed to a script's `children` does not escape HTML script-closing sequences in user content. Choose a schema type that matches the visible page and only include facts you actually publish. Valid structured data does not guarantee a rich result; see [Google's structured data guidelines](https://developers.google.com/search/docs/appearance/structured-data/sd-policies).
+
 ## Server-Side Rendering
 
 SSR is enabled by default in TanStack Start. This ensures that search engine crawlers receive fully rendered HTML content, which is critical for SEO.
diff --git a/docs/start/framework/react/guide/server-components.md b/docs/start/framework/react/guide/server-components.md
index 581ae145bd..6bbc716754 100644
--- a/docs/start/framework/react/guide/server-components.md
+++ b/docs/start/framework/react/guide/server-components.md
@@ -86,7 +86,7 @@ export default defineConfig({
 
 
 
-**Requirements:** React 19+, Vite 8+ or Rsbuild 2+
+**Requirements:** React 19+, Vite 7+ or Rsbuild 2+
 
 ## Quick Start
 
@@ -401,10 +401,7 @@ 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.query({
-      ...postQueryOptions(params.postId),
-      staleTime: 'static',
-    })
+    await context.queryClient.ensureQueryData(postQueryOptions(params.postId))
   },
   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 5f74eb7846..127b04fc86 100644
--- a/docs/start/framework/react/guide/server-entry-point.md
+++ b/docs/start/framework/react/guide/server-entry-point.md
@@ -4,71 +4,35 @@ title: Server Entry Point
 ---
 
 > [!NOTE]
-> 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 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.
 
 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.
 
-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:
+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.
 
 ```tsx
 // src/server.ts
 import handler, { createServerEntry } from '@tanstack/react-start/server-entry'
 
 export default createServerEntry({
-  fetch(request, opts) {
-    return handler.fetch(request, opts)
+  fetch(request) {
+    return handler.fetch(request)
   },
 })
 ```
 
 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:
@@ -87,155 +51,16 @@ const customHandler = defineHandlerCallback((ctx) => {
   return defaultStreamHandler(ctx)
 })
 
-const startHandler = createStartHandler(customHandler)
+const fetch = createStartHandler(customHandler)
 
 export default createServerEntry({
-  fetch(request, opts) {
-    return startHandler(request, opts)
-  },
+  fetch,
 })
 ```
 
-## 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. 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.
+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.
 
 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:
 
@@ -256,11 +81,8 @@ declare module '@tanstack/react-router' {
 }
 
 export default createServerEntry({
-  fetch(request, opts) {
-    return handler.fetch(request, {
-      ...opts,
-      context: { hello: 'world', foo: 123 },
-    })
+  async fetch(request) {
+    return handler.fetch(request, { 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 879aa9e867..903e5d7b86 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 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.
+Return `Response` objects binary data, or custom content types.
 
 ### Progressive Enhancement
 
@@ -425,9 +425,7 @@ Customization:
 
 You can customize function ID generation for the production build by providing a `generateFunctionId` function when configuring the TanStack Start build tool plugin.
 
-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.
+Prefer deterministic inputs (filename + functionName) so IDs remain stable between builds.
 
 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
index dec42ca26c..7797ae306b 100644
--- a/docs/start/framework/react/guide/tanstack-query.md
+++ b/docs/start/framework/react/guide/tanstack-query.md
@@ -1,12 +1,6 @@
 ---
 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.
 ---
 
diff --git a/docs/start/framework/react/migrate-from-next-js.md b/docs/start/framework/react/migrate-from-next-js.md
index dc5377df08..5739846a95 100644
--- a/docs/start/framework/react/migrate-from-next-js.md
+++ b/docs/start/framework/react/migrate-from-next-js.md
@@ -10,7 +10,7 @@ Start does not interpret Next.js route conventions or configuration. Keep your a
 
 ## Run the reference application
 
-Use Node 24 or newer and pnpm 12:
+Use Node 24 or newer and pnpm 11:
 
 ```sh
 git clone --depth 1 https://github.com/TanStack/router.git
@@ -22,7 +22,7 @@ cd examples/react/start-next-migration
 
 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`.
 
-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.
+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. The two apps use different session formats and cookie names, so sign in separately to each.
 
 With those ports free, run:
 
@@ -148,7 +148,7 @@ Next.js Action forms and these Start event-handler forms have different no-JavaS
 
 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.
 
-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.
+The example deliberately changes from `iron-session` with Next.js `cookies()` to Start's `useSession`. Existing cookies are not assumed to be 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.
 
 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.
 
diff --git a/docs/start/framework/react/migrate-from-release-candidate.md b/docs/start/framework/react/migrate-from-release-candidate.md
deleted file mode 100644
index 5cfa614cda..0000000000
--- a/docs/start/framework/react/migrate-from-release-candidate.md
+++ /dev/null
@@ -1,39 +0,0 @@
----
-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 ced7b65458..596dc77fe9 100644
--- a/docs/start/framework/react/overview.md
+++ b/docs/start/framework/react/overview.md
@@ -5,7 +5,9 @@ description: Build full-stack React applications with TanStack Start, including
 ---
 
 > [!NOTE]
-> 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 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 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/tutorial/fetching-external-api.md b/docs/start/framework/react/tutorial/fetching-external-api.md
index 8bdb048c88..8d6af3edce 100644
--- a/docs/start/framework/react/tutorial/fetching-external-api.md
+++ b/docs/start/framework/react/tutorial/fetching-external-api.md
@@ -3,6 +3,8 @@ id: fetching-external-api
 title: Calling an external API using TanStack Start
 ---
 
+For a course that adds routing, a database, accounts, SEO, deployment, and tests to one app, see [Learn Start](./learn-start).
+
 This guide demonstrates how to integrate external API calls into your TanStack Start application using route loaders. We will use TMDB API to fetch popular movies using TanStack Start and understand how to fetch data in a TanStack Start app.
 
 The complete code for this tutorial is available on [GitHub](https://github.com/shrutikapoor08/tanstack-start-movies).
diff --git a/docs/start/framework/react/tutorial/learn-start.md b/docs/start/framework/react/tutorial/learn-start.md
new file mode 100644
index 0000000000..ceb9be6f91
--- /dev/null
+++ b/docs/start/framework/react/tutorial/learn-start.md
@@ -0,0 +1,24 @@
+---
+id: learn-start
+title: Learn TanStack Start by Building a Full Stack App
+description: Build one TanStack Start app through eight working checkpoints, from routing and PostgreSQL to forms, accounts, SEO, deployment, and tests.
+---
+
+Build **Field notes**, a notebook with private drafts and published pages. Each chapter adds to the same app and has a runnable checkpoint, so you can inspect working code when you get stuck.
+
+The course uses React, TanStack Start, PostgreSQL, Prisma, and Better Auth. You should be comfortable with React components, TypeScript, and a terminal. The first two chapters need no database or hosted account.
+
+| Chapter                                           | What you build                                                        |
+| ------------------------------------------------- | --------------------------------------------------------------------- |
+| [1. Setup](./learn-start/setup)                   | A server-rendered page, root document, and router.                    |
+| [2. Routes](./learn-start/routes)                 | Typed links, search parameters, note URLs, and 404s.                  |
+| [3. Data](./learn-start/data)                     | PostgreSQL reads through server functions and route loaders.          |
+| [4. Forms](./learn-start/forms)                   | Validated writes, transaction rollback, and refreshed data.           |
+| [5. Authentication](./learn-start/authentication) | Accounts, private drafts, ownership checks, and explicit publication. |
+| [6. SEO](./learn-start/seo)                       | Server-rendered metadata, canonical URLs, and a public sitemap.       |
+| [7. Deployment](./learn-start/deployment)         | A standalone Node build, runtime configuration, and readiness checks. |
+| [8. Tests](./learn-start/tests)                   | Browser and production checks against the complete app.               |
+
+Open the [complete example and checkpoints](https://github.com/TanStack/router/tree/main/examples/react/start-learn).
+
+Each checkpoint has its own source directory within one pnpm package. The anonymous database chapters and the account chapters use separate databases. The deployment chapter explains the remaining hosting and account-service configuration; local production tests do not verify a hosted release.
diff --git a/docs/start/framework/react/tutorial/learn-start/authentication.md b/docs/start/framework/react/tutorial/learn-start/authentication.md
new file mode 100644
index 0000000000..28eedbf1f2
--- /dev/null
+++ b/docs/start/framework/react/tutorial/learn-start/authentication.md
@@ -0,0 +1,81 @@
+---
+id: learn-start-authentication
+title: Learn Start, Accounts and Private Notes
+description: Add Better Auth accounts to TanStack Start, authorize database reads and writes, keep drafts private, and test session renewal and expiry.
+---
+
+Give each account its own drafts and let the owner choose which notes to publish. The [working checkpoint](https://github.com/TanStack/router/tree/main/examples/react/start-learn/checkpoints/05-authentication) is `checkpoints/05-authentication`.
+
+## Prepare a separate database
+
+The earlier checkpoints allow anonymous writes. Do not point them at a database containing private notes. Create a second PostgreSQL database, `learn_start_auth`, and add its connection string to the example's `.env`:
+
+```dotenv
+AUTH_DATABASE_URL="postgresql://start_demo:start_demo@localhost:5433/learn_start_auth"
+BETTER_AUTH_SECRET=""
+APP_ORIGIN="http://localhost:3144"
+```
+
+Use your actual database credentials and port. Keep `DATABASE_URL` pointing at the earlier `learn_start` database. Generate a secret with `openssl rand -base64 48` and paste it into `BETTER_AUTH_SECRET`. Keep `.env` out of Git.
+
+From `examples/react/start-learn`, run:
+
+```sh
+pnpm db:generate:05
+pnpm db:migrate:05
+pnpm db:seed:05
+pnpm exec vite checkpoints/05-authentication --port 3144
+```
+
+Open http://localhost:3144 and choose **My notes**. Create an account with a password of at least 12 characters. This checkpoint starts with two public sample notes; it does not transfer notes from the anonymous database.
+
+## Let the auth library own credentials
+
+`src/server/auth.server.ts` configures Better Auth with its Prisma adapter and email/password sign-in. The migration adds its user, account, session, and verification tables. `src/routes/api/auth/$.ts` forwards GET and POST requests to the library's handler.
+
+The login component uses Better Auth's browser client. It does not hash passwords, create session tokens, or store credentials itself. The `tanstackStartCookies()` plugin is last in the server configuration so cookies set during server-side session reads reach the browser, including renewed session cookies.
+
+The server requires an explicit `APP_ORIGIN` and a secret of at least 32 characters. Changing the port means updating the origin too. Later, use the deployment's HTTPS origin and a secret stored in the host's secret manager.
+
+## Authorize every data operation
+
+`currentUser()` reads the incoming session and returns only the user's ID, name, and email. It sets `Cache-Control: private, no-store`; session tokens stay on the server. `requireUser()` rejects unauthenticated requests with HTTP 401.
+
+The dashboard's `beforeLoad` redirects visitors to `/login`, but that redirect is only a navigation convenience. Each protected server function calls `requireUser()` independently:
+
+- Creating a note takes its owner ID from the session, never from submitted form data.
+- Listing drafts filters by that owner ID.
+- Reading a draft filters by both slug and owner ID.
+- Publishing or unpublishing updates only a row matching both slug and owner ID. No matching row produces HTTP 404.
+
+A second signed-in user cannot bypass these checks by copying the first user's request. The public list and detail functions read only rows where `isPublished` is true. New notes default to private.
+
+## Keep publication explicit
+
+Create a note from **My notes**. Its body is visible at its private draft URL, but `/notes/your-slug` returns 404 to an anonymous visitor. Choose **Publish**, then open that public URL in another browser session. Choose **Unpublish** and it returns 404 again.
+
+Private pages use `noindex` and `private, no-store`. Neither directive replaces authorization. The database query is what prevents another account from reading the draft.
+
+The private dashboard and draft loaders use `staleReloadMode: 'blocking'`. This prevents a previously visited private page from rendering cached data while a different account's request is checked. HTTP cache headers do not clear Router's in-memory loader data. Sign-in and sign-out invalidate the router so these loaders request the current account's data.
+
+Create, publish, unpublish, and sign-out controls share pending state. This prevents overlapping actions while the route data refreshes. Sign-out clears the session through the auth client, invalidates route data, and returns to the login page.
+
+## Keep origin checks and account checks separate
+
+The checkpoint's Start middleware rejects cross-site server-function requests. Better Auth handles its own auth endpoints and origin checks. An authenticated cross-site request still needs to fail: being signed in does not prove that the user intended a write.
+
+Conversely, an allowed same-origin request still needs an authenticated owner. A CSRF check cannot decide which note an account may edit.
+
+## Verify two accounts and expired sessions
+
+Stop the development server and run:
+
+```sh
+COURSE_CHECKPOINT=05-authentication pnpm test:e2e
+```
+
+The test creates two temporary accounts and checks private reads, public publication, unpublication, another owner's rejected write, authenticated cross-site rejection, and rejected requests after sign-out. It also moves a session near expiry to check cookie renewal, then expires a session to check the login redirect. Test accounts and their notes are removed afterward.
+
+This course uses local email/password accounts. Email verification, password recovery, mail delivery, and a deployment-wide rate-limit store are not configured here. Configure and test the account lifecycle your public service needs before opening registration to real users.
+
+Next: [Make published notes discoverable](./seo).
diff --git a/docs/start/framework/react/tutorial/learn-start/data.md b/docs/start/framework/react/tutorial/learn-start/data.md
new file mode 100644
index 0000000000..7d0d7e3675
--- /dev/null
+++ b/docs/start/framework/react/tutorial/learn-start/data.md
@@ -0,0 +1,81 @@
+---
+id: learn-start-data
+title: Learn Start, Read Notes from PostgreSQL
+description: Move the Field notes app from static data to PostgreSQL with Prisma migrations, server-only queries, loader dependencies, and repeatable checks.
+---
+
+Keep the URLs from the routing chapter and move the data into PostgreSQL. The [working checkpoint](https://github.com/TanStack/router/tree/main/examples/react/start-learn/checkpoints/03-data) is `checkpoints/03-data`.
+
+## Prepare a dedicated database
+
+Install PostgreSQL and make its `initdb`, `pg_ctl`, and `createdb` commands available. From `examples/react/start-learn`, create a local development cluster and database:
+
+```sh
+cp .env.example .env
+printf '%s\n' 'start_demo' > .postgres-password
+initdb -D .postgres -U start_demo --auth-local=trust --auth-host=scram-sha-256 --pwfile=.postgres-password
+pg_ctl -D .postgres -l .postgres/server.log -o '-p 5433 -h 127.0.0.1' start
+PGPASSWORD=start_demo createdb -h 127.0.0.1 -p 5433 -U start_demo learn_start
+```
+
+Run initialization once for a new cluster, not every time you open the project. The database listens on localhost:5433. If that port is occupied, choose another port and update `.env` too. If you already run PostgreSQL, create a separate `learn_start` database there and set its connection URL instead.
+
+These are local demo credentials. `.env`, `.postgres`, and the password file are ignored by Git. Stop this cluster with `pg_ctl -D .postgres stop` when you finish, and restart it with the same `pg_ctl ... start` command. Do not use a production database for course exercises.
+
+## Apply the schema and sample data
+
+```sh
+pnpm db:generate:03
+pnpm db:migrate:03
+pnpm db:seed:03
+```
+
+Generation produces this checkpoint's Prisma client. Migration applies the committed SQL. The seed inserts the two notes from the previous chapter and their category; rerunning it leaves existing records alone.
+
+Inspect `prisma/schema.prisma` in the checkpoint. `Note` has a unique `slug`, a `title`, a `body`, and a relation to `Category`. The relation keeps category references valid at the database boundary. The next chapter uses it to demonstrate transaction rollback.
+
+The Prisma configuration loads `DATABASE_URL` from the course environment and points to this checkpoint's schema and migrations. Keep schema changes and migration SQL together. Generating the client updates TypeScript code; it does not apply changes to the database.
+
+## Make the database module server-only
+
+`src/server/db.server.ts` imports the server-only marker and creates a Prisma client with the PostgreSQL adapter. It fails clearly if `DATABASE_URL` is missing. The pool is shared by requests within that module instance, while query results are returned per request.
+
+Import that module only from server implementations. The browser needs the selected note fields, not a database client or connection URL. The complete configuration follows the [PostgreSQL recipe](../../guide/databases).
+
+## Call server functions from loaders
+
+A route loader can run during browser navigation, so it must not connect to PostgreSQL directly. `listNotes` and `getNote` are server functions in `src/server/notes.ts`. They validate input and select only the fields the page uses.
+
+The index route now makes its dependency on search explicit:
+
+```tsx
+validateSearch: z.object({ q: z.string().max(200).catch('') }),
+loaderDeps: ({ search }) => ({ q: search.q }),
+loader: ({ deps }) => listNotes({ data: deps }),
+```
+
+Import `z` from `zod` and `listNotes` from `../server/notes`. The component reads `Route.useLoaderData()` instead of filtering a module-level array. PostgreSQL filters titles case-insensitively. An invalid search value falls back to the empty filter.
+
+The detail loader awaits `getNote({ data: params.slug })`. If no note exists, it throws `notFound()` just as the static version did. The page component still reads the loader result, so the database change does not require a new component data-fetching pattern.
+
+Both routes use `Cache-Control: no-store` in this checkpoint. `src/start.ts` enables Start's CSRF middleware for requests to server functions. These protections do not authenticate a user; this chapter only reads public sample content.
+
+## Verify the data path
+
+```sh
+pnpm exec vite checkpoints/03-data --port 3142
+```
+
+Open http://localhost:3142 and follow a note link. Reload the detail page. You should see the same content that the earlier chapter served from a file.
+
+Stop the development server, then run:
+
+```sh
+COURSE_CHECKPOINT=03-data pnpm test:e2e
+```
+
+The test writes a uniquely named record directly to the dedicated database, checks that its title appears in raw server HTML, opens its detail page, reloads it, and checks an unknown note's 404 response. It deletes only its own test records. That distinguishes a working database loader from an app that still displays its old static array.
+
+If the database is unavailable, the checkpoint displays a generic recovery page. Inspect the server terminal for connection details. Do not display credentials or raw database errors to a reader.
+
+Next: [Create notes with a validated form](./forms).
diff --git a/docs/start/framework/react/tutorial/learn-start/deployment.md b/docs/start/framework/react/tutorial/learn-start/deployment.md
new file mode 100644
index 0000000000..b48d7e6585
--- /dev/null
+++ b/docs/start/framework/react/tutorial/learn-start/deployment.md
@@ -0,0 +1,85 @@
+---
+id: learn-start-deployment
+title: Learn Start, Build and Deploy the Node Server
+description: Build a standalone TanStack Start Node server, apply database migrations, configure runtime secrets, and verify readiness and server-rendered pages.
+---
+
+Build the same notebook as a Node server. The [working checkpoint](https://github.com/TanStack/router/tree/main/examples/react/start-learn/checkpoints/07-deployment) is `checkpoints/07-deployment`. It adds an explicit Node output preset and a database readiness endpoint.
+
+## Build and run locally
+
+Keep the account database and secret from the previous chapter. From `examples/react/start-learn`, run:
+
+```sh
+pnpm db:generate:07
+pnpm db:migrate:07
+pnpm build:07
+APP_ORIGIN=http://localhost:3146 PORT=3146 node --env-file=.env checkpoints/07-deployment/.output/server/index.mjs
+```
+
+If the account database is empty, run `pnpm db:seed:07` before starting. The build runs Vite and TypeScript. The explicit environment variables above override the values in `.env`, while `--env-file` supplies the database connection and auth secret for this local run.
+
+Open http://localhost:3146 and sign in. Create a note, publish it, and open its public URL in another browser session. Restart the process and verify the note remains. PostgreSQL owns persistence; the build directory does not.
+
+`/healthz` returns `200 ok` only after a PostgreSQL query succeeds. A failed query returns `503 unavailable` without database details. Use it as a readiness check. A database outage should remove an instance from traffic, not cause an endless process-restart loop.
+
+## Deploy the complete output directory
+
+The checkpoint selects Nitro's Node server preset. Its output is `checkpoints/07-deployment/.output`, including the server and public assets. Copy that whole directory to a Node host, then start it with:
+
+```sh
+node .output/server/index.mjs
+```
+
+If the host runs from the source checkout instead, `pnpm start:07` starts the same entry point. It expects runtime environment variables to already be set. Do not copy your local `.env` into a public directory or bake credentials into the artifact.
+
+Nitro supports a standalone Node output and uses `PORT` for the listening port. Terminate HTTPS at the host's reverse proxy. See [Nitro's Node deployment reference](https://nitro.build/deploy/runtimes/node).
+
+Use a Node version supported by the repository's current toolchain and pin it in the host configuration. Match the version used for your build and tests. The repository is a pnpm workspace, so use the installation and package-build steps from the [setup chapter](./setup) before running this checkpoint's build command in a fresh checkout.
+
+## Configure the runtime and release job
+
+| Setting              | Value                                                                                   |
+| -------------------- | --------------------------------------------------------------------------------------- |
+| `AUTH_DATABASE_URL`  | The production PostgreSQL connection string, with the provider's required TLS settings. |
+| `BETTER_AUTH_SECRET` | A stable, random secret of at least 32 characters, stored in the host's secret manager. |
+| `APP_ORIGIN`         | The public HTTPS origin, without a trailing slash.                                      |
+| `PORT`               | The port assigned by the Node host.                                                     |
+| `NODE_ENV`           | `production`.                                                                           |
+
+Keep the database in a reachable region and size its connection capacity for all instances. Each instance's pool allows up to five connections. Multiple replicas multiply that limit.
+
+Run `pnpm db:migrate:07` once in the release job, using the source checkout, Prisma configuration, migration files, and production database credentials. The standalone output is the runtime artifact, not a migration runner. Apply migrations before routing traffic to code that needs them. Do not use the sample seed as a production release step.
+
+Keep the previous artifact available for rollback. Roll back application code only when it remains compatible with the current database schema. Database migrations require their own recovery plan and tested backups.
+
+## Verify the hosted application
+
+After deploying, check the actual HTTPS origin:
+
+1. `/healthz` returns 200, and a public note loads directly with its body and metadata in the HTML.
+2. Its canonical URL and `/sitemap.txt` use the production origin, not localhost or a preview hostname.
+3. Sign-in survives reload; creating, publishing, and unpublishing a note works.
+4. Another account cannot read a draft or change its publication state, and signed-out writes fail.
+5. Sign-out returns to the login page, and an unknown public note returns 404.
+
+These hosted checks are separate from a local production build. The included tests do not provision hosting, configure DNS or TLS, or verify a remote deployment.
+
+## Finish account operations before public registration
+
+This checkpoint retains the course's email/password configuration. Email verification and password recovery are not wired to a mail service. Configure and test the flows your service requires before opening registration to real users, or keep the deployed course behind your host's access controls.
+
+Review rate-limit storage and trusted client-IP handling for your host. Better Auth's default in-memory limits are per process; multiple instances need suitable shared storage and proxy configuration. See [Better Auth's rate-limit documentation](https://better-auth.com/docs/concepts/rate-limit). Check the APIs against the version installed in this example before changing its configuration.
+
+## Run the deployment checks
+
+Stop the local server, then run:
+
+```sh
+COURSE_CHECKPOINT=07-deployment pnpm test:e2e
+COURSE_PRODUCTION=1 COURSE_CHECKPOINT=07-deployment pnpm test:e2e
+```
+
+The production run checks readiness and direct server HTML, scans public assets for the configured secrets, and runs a copied artifact outside the repository against an unavailable database. It expects a generic 503 response. Run `pnpm build:07` again after source changes before repeating production tests.
+
+Next: [Test the complete application](./tests).
diff --git a/docs/start/framework/react/tutorial/learn-start/forms.md b/docs/start/framework/react/tutorial/learn-start/forms.md
new file mode 100644
index 0000000000..d1df194785
--- /dev/null
+++ b/docs/start/framework/react/tutorial/learn-start/forms.md
@@ -0,0 +1,62 @@
+---
+id: learn-start-forms
+title: Learn Start, Create Notes with a Validated Form
+description: Add a TanStack Start form with server validation, pending and error feedback, transaction rollback, CSRF protection, and refreshed loader data.
+---
+
+Add writes to the same notes database. The [working checkpoint](https://github.com/TanStack/router/tree/main/examples/react/start-learn/checkpoints/04-forms) is `checkpoints/04-forms`. This checkpoint is still a shared local notebook with no accounts. Keep it local until the authentication chapter adds endpoint authorization.
+
+## Prepare this checkpoint
+
+Keep the database and `.env` from the previous chapter. Generate the client for the new source directory and apply the same migration history:
+
+```sh
+pnpm db:generate:04
+pnpm db:migrate:04
+pnpm exec vite checkpoints/04-forms --port 3143
+```
+
+Open http://localhost:3143. The two seeded notes remain, and the list now has a **Create a note** form. If you started here with a new database, run `pnpm db:seed:04` too.
+
+## Validate at the endpoint
+
+The new `createNote` server function uses POST and a Zod validator. It accepts four fields:
+
+- `slug`: lowercase letters and digits separated by hyphens, at most 80 characters.
+- `title`: 1 to 120 characters after trimming.
+- `body`: 1 to 5,000 characters after trimming.
+- `category`: 1 to 40 characters after trimming.
+
+The form mirrors these limits where HTML can express them. The server validator remains necessary because callers can bypass the form. A title containing only spaces passes HTML's `required` check but must fail the server validator.
+
+The checkpoint's `src/start.ts` keeps CSRF middleware enabled for server-function requests. Same-origin form calls work; a replay marked as cross-site receives HTTP 403. Authentication in the next chapter will add a separate check for who may write.
+
+## Keep related writes in one transaction
+
+A note needs a category. The handler uses a Prisma transaction to upsert the category and then insert the note. If the note's slug already exists, the database rejects the second write and rolls back the first.
+
+Try creating a note with an existing slug and a new category name. The UI should say **That slug is already used. Choose another one.** The unused category should not remain in the database. This is why catching the error around two unrelated writes would be insufficient.
+
+Only the known unique-constraint error becomes that specific response. An unexpected database failure gets generic UI feedback, while the server can retain diagnostic information. Avoid returning raw exception objects to the browser.
+
+## Keep the form pending through the refresh
+
+The component calls `createNote` through `useServerFn`. On success it awaits `router.invalidate()` so the route's database loader refreshes before the form becomes available again. A successful request alone does not update Router-owned loader data.
+
+The handler captures `event.currentTarget` before awaiting anything, reads its `FormData`, and resets the form only after a successful write and refresh. Validation or duplicate-slug errors leave the entered values available for correction.
+
+The fieldset is disabled until hydration and while the mutation is pending. The form uses `method="post"` so native submission cannot put its values into the URL. This implementation requires JavaScript; a progressively enhanced form needs an explicit native POST response path.
+
+## Check success and failure
+
+Create a note, then reload the page and open its detail link. The new body should come from PostgreSQL. Try the same slug again with a different category, and then try a title made of spaces.
+
+Stop the development server and run:
+
+```sh
+COURSE_CHECKPOINT=04-forms pnpm test:e2e
+```
+
+The tests check persisted server HTML, reloads, duplicate-slug rollback, server-side whitespace validation, and cross-site rejection. They also check that the HTML does not contain the configured database URL or password. Build-time client asset inspection remains part of the deployment checks.
+
+Next: [Add accounts and protect writes](./authentication).
diff --git a/docs/start/framework/react/tutorial/learn-start/routes.md b/docs/start/framework/react/tutorial/learn-start/routes.md
new file mode 100644
index 0000000000..f226509802
--- /dev/null
+++ b/docs/start/framework/react/tutorial/learn-start/routes.md
@@ -0,0 +1,86 @@
+---
+id: learn-start-routes
+title: Learn Start, Give Notes Their Own URLs
+description: Add typed note links, route parameters, validated search values, and a real not-found response to the Field notes app.
+---
+
+This chapter turns the single page into a searchable list and a detail page. Use the [working checkpoint](https://github.com/TanStack/router/tree/main/examples/react/start-learn/checkpoints/02-routes) in `checkpoints/02-routes` as the reference. It still uses static data so you can check routing before introducing database failures.
+
+From `examples/react/start-learn`, start this checkpoint:
+
+```sh
+pnpm exec vite checkpoints/02-routes --port 3141
+```
+
+## Add the note data
+
+Create `src/notes.ts` with two entries. Each has a stable `slug`, a `title`, and a `body`. The checkpoint uses `first-route` and `server-html` as its slugs. The next chapter will move reads behind a server function; for now this file is safe to include in browser code because every field is public sample content.
+
+## Match a route parameter
+
+Add `src/routes/notes.$slug.tsx`. The `$slug` segment matches the part of the URL after `/notes/`. Its loader selects the matching note:
+
+```tsx
+export const Route = createFileRoute('/notes/$slug')({
+  loader: ({ params }) => {
+    const note = notes.find((item) => item.slug === params.slug)
+    if (!note) {
+      throw notFound()
+    }
+    return note
+  },
+  component: Note,
+})
+```
+
+Import `createFileRoute` and `notFound` from `@tanstack/react-router` and `notes` from `../notes`. The component reads its result with `Route.useLoaderData()` and renders the note's title and body. The complete route is in the checkpoint.
+
+Using `notFound()` means `/notes/does-not-exist` returns a missing-resource response. Do not return an ordinary successful page whose text happens to say “not found.” The root route provides the recovery link back to the list.
+
+## Link with typed parameters
+
+In the list, use `Link` rather than assembling a path by hand:
+
+```tsx
+
+  {note.title}
+
+```
+
+The route tree supplies the parameter types. Renaming a route or parameter gives TypeScript a chance to find its callers.
+
+## Put the filter in the URL
+
+The index route validates the search value before the component reads it:
+
+```tsx
+validateSearch: (search: Record) => ({
+  q: typeof search.q === 'string' ? search.q : '',
+}),
+```
+
+`Route.useSearch()` returns this validated value. Filter the list by title, and render a GET form with an input named `q`. Submitting that form produces a shareable URL such as `/?q=server`, with no custom event handler required. A query value with the wrong type falls back to an empty filter.
+
+The detail route links back with an explicit empty search value:
+
+```tsx
+
+  All notes
+
+```
+
+That link intentionally clears the filter. The browser Back button returns to the previous filtered URL instead.
+
+## Check the result
+
+Open `/?q=server`, choose **Reading server HTML**, and use Back. The filter should still be `server`. Then request `/notes/does-not-exist` and inspect the HTTP status, which should be 404.
+
+Stop the development server and run:
+
+```sh
+COURSE_CHECKPOINT=02-routes pnpm test:e2e
+```
+
+The test covers the filtered list, detail navigation, browser Back, and the raw 404 response. If navigation works but the status is 200, check that the loader throws `notFound()` before returning content.
+
+Next: [Read notes from PostgreSQL](./data).
diff --git a/docs/start/framework/react/tutorial/learn-start/seo.md b/docs/start/framework/react/tutorial/learn-start/seo.md
new file mode 100644
index 0000000000..6a3b771014
--- /dev/null
+++ b/docs/start/framework/react/tutorial/learn-start/seo.md
@@ -0,0 +1,81 @@
+---
+id: learn-start-seo
+title: Learn Start, SEO for Published Notes
+description: Render titles, descriptions, canonical URLs, and Open Graph tags in TanStack Start server HTML, and build a sitemap that excludes private drafts.
+---
+
+Add search metadata to published notes without exposing private drafts. The [working checkpoint](https://github.com/TanStack/router/tree/main/examples/react/start-learn/checkpoints/06-seo) is `checkpoints/06-seo`.
+
+## Run this checkpoint
+
+Keep the authentication database and secret from the previous chapter. Change `APP_ORIGIN` in `.env` to `http://localhost:3145`, then run:
+
+```sh
+pnpm db:generate:06
+pnpm db:migrate:06
+pnpm exec vite checkpoints/06-seo --port 3145
+```
+
+The schema is unchanged, so existing accounts and notes remain. If you started here with an empty account database, run `pnpm db:seed:06` to add the public samples.
+
+## Build metadata from loader data
+
+The public note server function still selects only published rows. It now returns a canonical URL alongside the note. The route's `head` function reads that loader data and produces:
+
+- A title containing the note title and site name.
+- A description from the first 160 characters of the note body after whitespace normalization.
+- An absolute canonical URL.
+- Open Graph and Twitter titles, descriptions, and a reachable social image, plus the Open Graph URL.
+- A CreativeWork JSON-LD object describing the note.
+
+The description length is this example's editorial choice, not a search-engine requirement. A larger publishing system can give authors a separate description field.
+
+`HeadContent` in the root document renders these tags into the server response. They are available before hydration. React escapes title and description text, including quotes and angle brackets; do not build raw HTML strings from note content.
+
+## Add structured data and a social image
+
+The note route uses Router's `script:ld+json` meta entry with the note's actual title, description, and canonical URL. Router serializes and escapes that object, including a note containing ``. Do not replace it with an unescaped HTML string. These short notes use [CreativeWork](https://schema.org/CreativeWork); the example does not invent an author or publication date and does not promise a Google rich result for that type.
+
+`public/images/field-notes-v1.png` is a shared notebook cover, not an image generated from each note's text. Open Graph and Twitter tags use its absolute URL, and Open Graph includes its 1200 by 630 pixel dimensions and alt text. The checked-in PNG needs no image server, credentials, or runtime transformation.
+
+To regenerate it after changing the original SVG, run `pnpm social:image` from the course directory. The build-time Sharp dependency writes the same cover into checkpoints 06, 07, and 08. The SVG and PNG are included under the repository's MIT license. Change the versioned filename and metadata together if you replace a cached cover. See [Images and Fonts](../../guide/images-and-fonts) for responsive page images, loading priority, and transformation services.
+
+## Choose the public origin explicitly
+
+`src/server/site.server.ts` validates `APP_ORIGIN` as an HTTP or HTTPS origin without a trailing slash. Canonical URLs and the sitemap use that configured origin, rather than copying the incoming host header.
+
+A published note opened with `?utm_source=newsletter` still points to the clean `/notes/your-slug` canonical URL. Google treats canonical annotations as signals when choosing between duplicate URLs, not as guaranteed indexing instructions. See [Google's canonical URL guidance](https://developers.google.com/search/docs/crawling-indexing/consolidate-duplicate-urls).
+
+The home page has its own canonical URL. Filtered search pages use `noindex` and omit a canonical annotation because their results can differ from the unfiltered home page. Note links are real anchors and remain usable without JavaScript.
+
+## List only public URLs
+
+`src/routes/sitemap[.]txt.ts` serves `/sitemap.txt`. The escaped dot in the filename keeps it a literal dot in the route URL. Its database query selects only published slugs, then writes one absolute URL per line, with the home page first. `/robots.txt` points to that sitemap.
+
+Google supports plain-text sitemaps for page URLs. A single sitemap is limited to 50,000 URLs or 50 MB uncompressed, so split the output before a larger site reaches either limit. Listing a URL does not guarantee indexing. See [Google's sitemap guidance](https://developers.google.com/search/docs/crawling-indexing/sitemaps/build-sitemap).
+
+The sitemap excludes account pages, private drafts, and search parameters. It uses `no-store` so a response does not keep advertising a note after unpublication. The public detail query independently checks publication state and returns a real HTTP 404 for a draft, an unpublished note, or an unknown slug.
+
+## Redirect moved URLs without exposing drafts
+
+`/old-notes/your-slug` demonstrates an old URL for the same published note. It checks publication state, then returns HTTP 308 to `/notes/your-slug`. Unknown slugs and private drafts return 404. The old paths stay out of the sitemap, and the destination supplies the canonical URL. These redirects use `no-store` so the example does not retain a redirect after a publication change.
+
+## Keep access control in the database query
+
+Private draft pages and the dashboard retain their session and ownership checks, `noindex`, and `private, no-store` responses. Robots directives do not protect private content. The auth checks from the previous chapter still run for every protected data operation.
+
+Unpublishing prevents subsequent public reads, but cannot retract copies that someone already downloaded or a search engine cached. Publish only content its owner intends to make public.
+
+## Inspect the HTML without JavaScript
+
+Open a published note, use **View Page Source**, and find its title, description, canonical link, and visible note body. Open `/sitemap.txt` and confirm the note is listed. Unpublish it from **My notes**, then verify that its public URL returns 404 and disappears from the sitemap.
+
+Stop the development server and run:
+
+```sh
+COURSE_CHECKPOINT=06-seo pnpm test:e2e
+```
+
+The test uses a crawler user agent with JavaScript disabled, checks every sitemap URL against its canonical, reads the PNG dimensions, and verifies redirects, metadata, structured data, draft exclusions, and unpublication. A normal browser also checks client navigation and script-like note text without executing it. The server HTML must not contain the database URL or auth secret.
+
+Next: [Build and deploy the application](./deployment).
diff --git a/docs/start/framework/react/tutorial/learn-start/setup.md b/docs/start/framework/react/tutorial/learn-start/setup.md
new file mode 100644
index 0000000000..b3de5f6c2c
--- /dev/null
+++ b/docs/start/framework/react/tutorial/learn-start/setup.md
@@ -0,0 +1,108 @@
+---
+id: learn-start-setup
+title: Learn Start, Set Up the App
+description: Run a small TanStack Start app and understand the router, root document, server HTML, and first route.
+---
+
+Build Field notes, an app for writing and sharing what you learn. This first checkpoint has one route and no database. Later chapters add URLs, storage, forms, accounts, metadata, deployment, and tests to the same app.
+
+## Run the first checkpoint
+
+You need Node.js and pnpm. Clone the [TanStack Router repository](https://github.com/TanStack/router) and complete its [dependency and framework build setup](https://github.com/TanStack/router/blob/main/CONTRIBUTING.md). The course checkpoints use the framework packages in that checkout so the code and APIs stay together.
+
+```sh
+cd examples/react/start-learn
+pnpm dev
+```
+
+Open http://localhost:3140. You should see **Field notes** and **Keep a record of what you learn.** The [working checkpoint](https://github.com/TanStack/router/tree/main/examples/react/start-learn/checkpoints/01-setup) is in `checkpoints/01-setup`. Each checkpoint has its own source directory and Vite configuration; the course directory supplies their shared dependencies.
+
+## Follow a request through the app
+
+`src/router.tsx` creates the router from the generated route tree:
+
+```tsx
+import { createRouter } from '@tanstack/react-router'
+import { routeTree } from './routeTree.gen'
+
+export function getRouter() {
+  return createRouter({ routeTree })
+}
+```
+
+Start calls `getRouter` for an incoming server-rendered request and creates a router for the browser. Keep request-specific state inside that lifecycle. Do not edit `routeTree.gen.ts`; the route plugin generates it from your route files.
+
+`src/routes/__root.tsx` supplies the HTML document. `HeadContent` renders the route metadata, and `Scripts` loads the client code. Both belong in the document:
+
+```tsx
+import { HeadContent, 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: 'Field notes | Learn Start' },
+    ],
+  }),
+  shellComponent: ({ children }: { children: ReactNode }) => (
+    
+      
+        
+      
+      
+        {children}
+        
+      
+    
+  ),
+  notFoundComponent: () => (
+    
+  ),
+})
+```
+
+The checkpoint's root route supplies that component through `shellComponent`. Its `head` option sets the character encoding, viewport, and page title. Its not-found component will also provide a recovery page when the next chapter adds note URLs.
+
+Finally, `src/routes/index.tsx` matches `/`:
+
+```tsx
+import { createFileRoute } from '@tanstack/react-router'
+
+export const Route = createFileRoute('/')({ component: Home })
+
+function Home() {
+  return (
+    
+

Field notes

+

Keep a record of what you learn.

+
+ ) +} +``` + +Change the paragraph and watch the page update. There is no manual route registration: the file generates the route entry. + +## Check the server response + +With the development server running: + +```sh +curl http://localhost:3140/ +``` + +The response should contain the paragraph you just edited, not only an empty root element. Browser source inspection shows the same distinction. This verifies server-rendered content; it does not by itself prove every client interaction works. + +Stop the development server before running the checkpoint test, because the test starts its own server: + +```sh +pnpm exec playwright install chromium +COURSE_CHECKPOINT=01-setup pnpm test:e2e +``` + +The test requests the raw HTML and opens the page in a browser. If the page is empty, inspect the terminal first, then check `HeadContent`, `Scripts`, and the generated route tree against the checkpoint. + +Next: [Give notes their own URLs](./routes). diff --git a/docs/start/framework/react/tutorial/learn-start/tests.md b/docs/start/framework/react/tutorial/learn-start/tests.md new file mode 100644 index 0000000000..3400755c36 --- /dev/null +++ b/docs/start/framework/react/tutorial/learn-start/tests.md @@ -0,0 +1,69 @@ +--- +id: learn-start-tests +title: Learn Start, Test the Complete Application +description: Test a complete TanStack Start app with Playwright, covering accounts, ownership, database rollback, server HTML, SEO, and production deployment behavior. +--- + +Run the earlier checks against one complete application. The [working checkpoint](https://github.com/TanStack/router/tree/main/examples/react/start-learn/checkpoints/08-tests) is `checkpoints/08-tests`. It preserves the deployment chapter's app and adds the combined tests in `tests/final-*.spec.ts`. + +## Prepare the final checkpoint + +Keep the account database and secret. Set `APP_ORIGIN` in `.env` to `http://localhost:3147` for manual development, then run: + +```sh +pnpm db:generate:08 +pnpm db:migrate:08 +pnpm db:seed:08 +COURSE_CHECKPOINT=08-tests pnpm test:e2e +pnpm build:08 +COURSE_PRODUCTION=1 COURSE_CHECKPOINT=08-tests pnpm test:e2e +``` + +Run these commands from `examples/react/start-learn`. Install Playwright's Chromium browser with `pnpm exec playwright install chromium` if it is not already installed. Stop any manually started checkpoint server before running tests; Playwright owns the server for each test run. + +The schema is unchanged from the account chapter. The seed adds public sample notes if they are absent. Use a disposable local or test database, not a production database. Tests create and remove temporary records, and they deliberately alter their test accounts' session expiry times. + +## Check boundaries, not only button clicks + +| Test file | What it proves | +| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `final-authentication.spec.ts` | Account creation and sign-in, private drafts, owner-filtered reads and writes, publication, cross-site rejection, sign-out, renewal, expiry, duplicate-slug transaction rollback, and server-side validation. | +| `final-seo.spec.ts` | Titles, descriptions, canonical URLs, links, and content without JavaScript; sitemap exclusions; real 404s; unpublication; private redirect caching. | +| `final-deployment.spec.ts` | Database readiness and direct server HTML; public-asset secret checks and copied-artifact startup in production mode. | + +The account test replays actual browser requests. It sends an authenticated write with cross-site metadata, then repeats an owner's request from another signed-in account. Those checks distinguish CSRF protection from ownership authorization. A test that only checks for a login redirect would miss both failures. + +The duplicate-slug check submits a new category with an existing slug, then queries PostgreSQL to prove the transaction rolled the new category back. A visible error alone would not prove that the database stayed consistent. + +The SEO test disables JavaScript. The deployment test starts the generated Node entry point. Development-only browser success does not prove either server HTML or production behavior. + +## Keep test data separate + +Tests use unique record names and remove their own accounts, notes, and categories in `finally` blocks. Earlier anonymous checkpoints use `DATABASE_URL`; account checkpoints use `AUTH_DATABASE_URL`. Keep those databases separate so an earlier anonymous app cannot expose private data created later. + +Do not point a test suite at a hosted customer database. If a test fails before cleanup completes, use its unique record prefix to inspect and remove its fixtures from the test database. + +## Run an earlier checkpoint independently + +`COURSE_CHECKPOINT` selects one server and its matching test files. It does not start every chapter's app. + +| Checkpoint | Port | Test command | +| ------------------- | ---- | --------------------------------------------------- | +| `01-setup` | 3140 | `COURSE_CHECKPOINT=01-setup pnpm test:e2e` | +| `02-routes` | 3141 | `COURSE_CHECKPOINT=02-routes pnpm test:e2e` | +| `03-data` | 3142 | `COURSE_CHECKPOINT=03-data pnpm test:e2e` | +| `04-forms` | 3143 | `COURSE_CHECKPOINT=04-forms pnpm test:e2e` | +| `05-authentication` | 3144 | `COURSE_CHECKPOINT=05-authentication pnpm test:e2e` | +| `06-seo` | 3145 | `COURSE_CHECKPOINT=06-seo pnpm test:e2e` | +| `07-deployment` | 3146 | `COURSE_CHECKPOINT=07-deployment pnpm test:e2e` | +| `08-tests` | 3147 | `COURSE_CHECKPOINT=08-tests pnpm test:e2e` | + +Before testing a database chapter, run its client generation and migration commands. Before adding `COURSE_PRODUCTION=1`, build that checkpoint. For example, checkpoint 04 uses `pnpm exec vite build checkpoints/04-forms` followed by `pnpm exec tsc -p checkpoints/04-forms`. + +The deployment artifact check also uses port 3148 for its temporary server. It runs only in production mode, so the development suite reports that check as skipped. + +## Make changes with a failing case in mind + +When changing publication rules, add an assertion for a note that must remain private. When changing sessions, check a revoked or expired session. When changing a loader, inspect its direct HTML response as well as client navigation. Add a test because it catches a plausible failure, not because a new function needs a matching test file. + +Return to the [course index](../learn-start) before extending the app for real users. Hosted deployment and account operations still need the checks described in the [deployment chapter](./deployment). diff --git a/docs/start/framework/react/tutorial/reading-writing-file.md b/docs/start/framework/react/tutorial/reading-writing-file.md index f4af4480f1..78e60683d0 100644 --- a/docs/start/framework/react/tutorial/reading-writing-file.md +++ b/docs/start/framework/react/tutorial/reading-writing-file.md @@ -3,6 +3,8 @@ id: reading-and-writing-file title: Building a Full Stack DevJokes App with TanStack Start --- +For a course that adds routing, a database, accounts, SEO, deployment, and tests to one app, see [Learn Start](./learn-start). + 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 React components. Here's a demo of the app in action: diff --git a/docs/start/framework/solid/guide/authentication.md b/docs/start/framework/solid/guide/authentication.md index 460a58747c..4460e853ae 100644 --- a/docs/start/framework/solid/guide/authentication.md +++ b/docs/start/framework/solid/guide/authentication.md @@ -35,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 server functions, request and cookie utilities, and route protection. Session storage and authentication come from your application or a library you choose. +TanStack Start provides the tools for both through server functions, sessions, and route protection. > 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. @@ -48,7 +48,6 @@ 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' }) @@ -62,9 +61,11 @@ export const loginFn = createServerFn({ method: 'POST' }) } // Create session - const session = await getAppSession() - session.userId = user.id - await session.save() + const session = await useAppSession() + await session.update({ + userId: user.id, + email: user.email, + }) // Redirect to protected area throw redirect({ to: '/dashboard' }) @@ -72,16 +73,16 @@ export const loginFn = createServerFn({ method: 'POST' }) // Logout server function export const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await getAppSession() - session.destroy() + const session = await useAppSession() + await session.clear() throw redirect({ to: '/' }) }) // Get current user export const getCurrentUserFn = createServerFn({ method: 'GET' }).handler( async () => { - const session = await getAppSession() - const userId = session.userId + const session = await useAppSession() + const userId = session.get('userId') if (!userId) { return null @@ -95,53 +96,33 @@ export const getCurrentUserFn = createServerFn({ method: 'GET' }).handler( ### 2. Session Management -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. +TanStack Start provides secure HTTP-only cookie sessions: ```tsx -// utils/session.ts — import only from server code -import { getIronSession } from 'iron-session' -import { getCookie, setCookie } from '@tanstack/solid-start/server' +// utils/session.ts +import { useSession } from '@tanstack/solid-start/server' type SessionData = { - userId: string - oauthState: string + userId?: string + email?: string + role?: string } -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: '/', - }, +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, }, - ) + }) } ``` -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 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`. @@ -273,9 +254,8 @@ export const registerFn = createServerFn({ method: 'POST' }) }) // Create session - const session = await getAppSession() - session.userId = user.id - await session.save() + const session = await useAppSession() + await session.update({ userId: user.id }) return { success: true, user: { id: user.id, email: user.email } } }) @@ -343,9 +323,8 @@ export const initiateOAuthFn = createServerFn({ method: 'POST' }) const state = generateRandomState() // Store state in session for CSRF protection - const session = await getAppSession() - session.oauthState = state - await session.save() + const session = await useAppSession() + await session.update({ oauthState: state }) // Generate OAuth URL const authUrl = generateOAuthUrl(provider, state) @@ -408,9 +387,21 @@ const hashedPassword = await bcrypt.hash(password, saltRounds) ### 2. Session Security -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. +```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 + }, + }) +} +``` ### 3. Rate Limiting @@ -590,14 +581,16 @@ 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 ttl = data.rememberMe ? 30 * 24 * 60 * 60 : 8 * 60 * 60 - const session = await getAppSession(ttl) - session.userId = user.id - await session.save() + 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 + }, + ) return { success: true } }) @@ -617,6 +610,7 @@ 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/migrate-from-release-candidate.md b/docs/start/framework/solid/migrate-from-release-candidate.md deleted file mode 100644 index 9f988a14fc..0000000000 --- a/docs/start/framework/solid/migrate-from-release-candidate.md +++ /dev/null @@ -1,8 +0,0 @@ ---- -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/e2e/AGENTS.md b/e2e/AGENTS.md deleted file mode 100644 index f373ecba4f..0000000000 --- a/e2e/AGENTS.md +++ /dev/null @@ -1,9 +0,0 @@ -# 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 deleted file mode 100644 index f92ec840e5..0000000000 --- a/e2e/e2e-utils/mock-api.mjs +++ /dev/null @@ -1,4 +0,0 @@ -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 fcfa5f8dc0..127f9a01f2 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": "vitest run" + "test:unit": "exit 0; vitest --typecheck" }, "type": "module", "types": "dist/types/index.d.ts", @@ -22,8 +22,7 @@ "default": "./dist/cjs/index.cjs" } }, - "./package.json": "./package.json", - "./mock-api": "./mock-api.mjs" + "./package.json": "./package.json" }, "sideEffects": false, "files": [ @@ -31,14 +30,13 @@ "src" ], "engines": { - "node": "^22.18.0 || >=24.0.0" + "node": ">=20.19" }, + "dependencies": {}, "devDependencies": { - "@msw/playwright": "0.6.7", - "msw": "2.15.0", - "rimraf": "catalog:", + "get-port-please": "^3.2.0", "vite": "^8.0.14", "vite-plugin-dts": "^4.5.4", - "vitest": "catalog:" + "rimraf": "catalog:" } } diff --git a/e2e/e2e-utils/src/api-fixture.ts b/e2e/e2e-utils/src/api-fixture.ts deleted file mode 100644 index 90ca1912a3..0000000000 --- a/e2e/e2e-utils/src/api-fixture.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 4e2c0498f4..0000000000 --- a/e2e/e2e-utils/src/api-handlers.ts +++ /dev/null @@ -1,32 +0,0 @@ -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 new file mode 100644 index 0000000000..3ecb86cb53 --- /dev/null +++ b/e2e/e2e-utils/src/derivePort.ts @@ -0,0 +1,27 @@ +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 new file mode 100644 index 0000000000..d1acf4740e --- /dev/null +++ b/e2e/e2e-utils/src/e2eSetupTeardown.ts @@ -0,0 +1,16 @@ +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 960a01a9be..17e58f82e5 100644 --- a/e2e/e2e-utils/src/index.ts +++ b/e2e/e2e-utils/src/index.ts @@ -1,9 +1,10 @@ -export { apiTest } from './api-fixture' +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 { 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 { resolveRuntimeSuffix } from './resolve-runtime-suffix' -export { toRuntimePath } from './to-runtime-path' -export { appServerReady, appServerReadyPattern } from './webServer' +export { collectBrowserErrors, test } from './fixture' diff --git a/e2e/e2e-utils/src/localDummyServer.ts b/e2e/e2e-utils/src/localDummyServer.ts new file mode 100644 index 0000000000..d452f54c59 --- /dev/null +++ b/e2e/e2e-utils/src/localDummyServer.ts @@ -0,0 +1,128 @@ +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 deleted file mode 100644 index 77536e4c69..0000000000 --- a/e2e/e2e-utils/src/webServer.ts +++ /dev/null @@ -1,9 +0,0 @@ -// 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 deleted file mode 100644 index ba25c1254d..0000000000 --- a/e2e/e2e-utils/tests/mock-api.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -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 deleted file mode 100644 index fd3a8b239c..0000000000 --- a/e2e/e2e-utils/tests/webServer.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 5561f5d28f..9b21ee123b 100644 --- a/e2e/e2e-utils/tsconfig.json +++ b/e2e/e2e-utils/tsconfig.json @@ -1,7 +1,4 @@ { "extends": "../../tsconfig.json", - "include": ["src", "vite.config.ts", "tests"], - "compilerOptions": { - "rewriteRelativeImportExtensions": true - } + "include": ["src", "vite.config.ts", "tests"] } diff --git a/e2e/react-router/basepath-file-based/package.json b/e2e/react-router/basepath-file-based/package.json index 3dfbb58180..a155cc2173 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", diff --git a/e2e/react-router/basepath-file-based/playwright.config.ts b/e2e/react-router/basepath-file-based/playwright.config.ts index 4eead86444..6069bbe59f 100644 --- a/e2e/react-router/basepath-file-based/playwright.config.ts +++ b/e2e/react-router/basepath-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', }, 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 d6a50de840..06b90f6528 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,41 +1,5 @@ -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([]) -} +/* eslint-disable */ +import { expect, test } from '@playwright/test' test.describe('Scroll Restoration with Session Storage Error', () => { test('should not crash when sessionStorage.setItem throws an error', async ({ @@ -45,12 +9,22 @@ test.describe('Scroll Restoration with Session Storage Error', () => { await page.waitForLoadState('networkidle') await page.evaluate(() => { - Storage.prototype.setItem = () => { + sessionStorage.setItem = () => { throw new Error('Test Error') } }) - await reloadAfterStorageFailure(page) + 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) }) test('should not crash when sessionStorage quota is exceeded', async ({ @@ -73,6 +47,16 @@ test.describe('Scroll Restoration with Session Storage Error', () => { } }) - await reloadAfterStorageFailure(page) + 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) }) }) 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/basepath-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/basepath-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 59210c24d7..9421e4666c 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", 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 a38252921f..ca0fb7a1da 100644 --- a/e2e/react-router/basic-esbuild-file-based/playwright.config.ts +++ b/e2e/react-router/basic-esbuild-file-based/playwright.config.ts @@ -1,8 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' - -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } +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. @@ -13,15 +17,18 @@ 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\\"`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 954ddc026f..5f0f4fce03 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,5 +2,9 @@ import { tanstackRouter } from '@tanstack/router-plugin/esbuild' export default { // ... - plugins: [tanstackRouter()], + plugins: [ + tanstackRouter({ + autoCodeSplitting: true, + }), + ], } 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 97c96d77eb..8f74b8c9aa 100644 --- a/e2e/react-router/basic-esbuild-file-based/src/posts.tsx +++ b/e2e/react-router/basic-esbuild-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (process.env.NODE_ENV === 'test') { + queryURL = `http://localhost:${process.env.EXTERNAL_PORT}` +} 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 c52191a7d4..7b322a8b1d 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/basic-esbuild-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/basic-esbuild-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 82ebb90e93..8355ed79ab 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", 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 4eead86444..22c9bdcd7e 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,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 97c96d77eb..ae7142c5b6 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,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) 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 fbf093cd51..3e5a69ccaa 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 fd17fcc47b..0bc3265760 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/basic-file-based-code-splitting/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/basic-file-based-code-splitting/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 2ad4ec3e78..512943c10d 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 0f3d243432..9868755b87 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": "playwright test --project=chromium" + "test:e2e:default": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/react-router/basic-file-based/playwright.config.ts b/e2e/react-router/basic-file-based/playwright.config.ts index ea3ef9ffec..6e4e1d7703 100644 --- a/e2e/react-router/basic-file-based/playwright.config.ts +++ b/e2e/react-router/basic-file-based/playwright.config.ts @@ -1,9 +1,14 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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}` -const command = `pnpm build && pnpm preview --host 0.0.0.0 --port ${PORT}` +const command = `pnpm build && pnpm preview --port ${PORT}` console.info('Running with mode: ', process.env.MODE || 'default') @@ -16,6 +21,9 @@ 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, @@ -23,12 +31,15 @@ export default defineConfig({ webServer: { command, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, 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 deleted file mode 100644 index 3b4062b778..0000000000 --- a/e2e/react-router/basic-file-based/public/external.html +++ /dev/null @@ -1,9 +0,0 @@ - - - - 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 d6a5aef382..f16505bf21 100644 --- a/e2e/react-router/basic-file-based/src/main.tsx +++ b/e2e/react-router/basic-file-based/src/main.tsx @@ -27,7 +27,9 @@ const router = createRouter({ rewrite: { output: ({ url }) => { if (url.pathname === '/document-navigation-target') { - return new URL(`http://127.0.0.1:${window.location.port}/external.html`) + return new URL( + `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}/`, + ) } return url }, diff --git a/e2e/react-router/basic-file-based/src/posts.tsx b/e2e/react-router/basic-file-based/src/posts.tsx index 97c96d77eb..ae7142c5b6 100644 --- a/e2e/react-router/basic-file-based/src/posts.tsx +++ b/e2e/react-router/basic-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 = 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 83b504992f..0d17f94eb0 100644 --- a/e2e/react-router/basic-file-based/src/routeTree.gen.ts +++ b/e2e/react-router/basic-file-based/src/routeTree.gen.ts @@ -1711,7 +1711,7 @@ declare module '@tanstack/react-router' { '/(group)/_layout': { id: '/(group)/_layout' path: '' - fullPath: '/' + fullPath: '' preLoaderRoute: typeof groupLayoutRouteImport parentRoute: typeof rootRouteImport } 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 index 66c2b704d1..65c43d8809 100644 --- a/e2e/react-router/basic-file-based/src/routes/document-navigation.tsx +++ b/e2e/react-router/basic-file-based/src/routes/document-navigation.tsx @@ -5,7 +5,7 @@ export const Route = createFileRoute('/document-navigation')({ component: DocumentNavigation, }) -const adminHref = `http://127.0.0.1:${window.location.port}/external.html` +const adminHref = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}/` function DocumentNavigation() { const navigate = Route.useNavigate() 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 bd9c365484..ae87d350ce 100644 --- a/e2e/react-router/basic-file-based/tests/app.spec.ts +++ b/e2e/react-router/basic-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import type { Page } from '@playwright/test' test.beforeEach(async ({ page }) => { diff --git a/e2e/react-router/basic-file-based/tests/document-navigation.spec.ts b/e2e/react-router/basic-file-based/tests/document-navigation.spec.ts index bd81eaa44b..80cb110e8a 100644 --- a/e2e/react-router/basic-file-based/tests/document-navigation.spec.ts +++ b/e2e/react-router/basic-file-based/tests/document-navigation.spec.ts @@ -1,8 +1,9 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' +import { getDummyServerPort } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } -const appPort = Number(process.env.E2E_APP_PORT ?? 0) -const adminHref = `http://127.0.0.1:${appPort}/external.html` +const externalPort = await getDummyServerPort(packageJson.name) +const adminHref = `http://localhost:${externalPort}/` for (const role of ['button', 'link'] as const) { for (const { name, href, replace } of [ @@ -23,7 +24,7 @@ for (const role of ['button', 'link'] as const) { await page.goto('/') await page.goto('/document-navigation') const historyLength = await page.evaluate(() => window.history.length) - const response = page.waitForResponse(href.split('#')[0]) + const response = page.waitForResponse(href.split('#')[0]!) const control = page.getByRole(role, { name, exact: true }) if (role === 'link') { 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 8f4df9f966..d1bd9c1c41 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 index df1f863a03..244456a2ab 100644 --- a/e2e/react-router/basic-file-based/tests/history-blocking.spec.ts +++ b/e2e/react-router/basic-file-based/tests/history-blocking.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import type { Page } from '@playwright/test' async function prepareDocumentTraversal(page: Page, delta: number) { 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 1263faf391..b090c2a6b7 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 d5076a5854..1b77760de6 100644 --- a/e2e/react-router/basic-file-based/tests/mask.spec.ts +++ b/e2e/react-router/basic-file-based/tests/mask.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 ea0e585c75..dccdfd4acf 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 bbb2dac7a1..2f0fe256cd 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.describe('Open redirect prevention', () => { test.describe('CRLF injection attacks', () => { diff --git a/e2e/react-router/basic-file-based/tests/params.spec.ts b/e2e/react-router/basic-file-based/tests/params.spec.ts index fa0377f3ca..a867696ff8 100644 --- a/e2e/react-router/basic-file-based/tests/params.spec.ts +++ b/e2e/react-router/basic-file-based/tests/params.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 aaa9c1a6b6..1845cc16a4 100644 --- a/e2e/react-router/basic-file-based/tests/redirect.spec.ts +++ b/e2e/react-router/basic-file-based/tests/redirect.spec.ts @@ -1,13 +1,17 @@ import queryString from 'node:querystring' -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 = Number(process.env.E2E_APP_PORT ?? 0) -const EXTERNAL_ORIGIN = `http://127.0.0.1:${PORT}` +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_HOST_PORT = await getDummyServerPort(packageJson.name) test.describe('redirects', () => { const internalNavigationTestMatrix = combinate({ @@ -35,7 +39,7 @@ test.describe('redirects', () => { const requestPromise = new Promise((resolve) => { page.on('request', (request) => { if ( - request.url() === 'https://jsonplaceholder.typicode.com/posts' + request.url() === `http://localhost:${EXTERNAL_HOST_PORT}/posts` ) { requestHappened = true resolve() @@ -104,7 +108,7 @@ test.describe('redirects', () => { await page.waitForLoadState('networkidle') const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, }) if (scenario === 'navigate') { @@ -114,7 +118,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/external/via-${thrower}?${q}`) } - const url = `${EXTERNAL_ORIGIN}/` + const url = `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) @@ -180,7 +184,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, }) if (scenario === 'navigate') { @@ -193,7 +197,7 @@ test.describe('redirects', () => { ) } - const url = `${EXTERNAL_ORIGIN}/` + const url = `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) }) @@ -250,7 +254,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, }) if (scenario === 'navigate') { @@ -263,7 +267,7 @@ test.describe('redirects', () => { ) } - const url = `${EXTERNAL_ORIGIN}/` + const url = `http://localhost:${EXTERNAL_HOST_PORT}/` 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 f62c248680..4850d3630d 100644 --- a/e2e/react-router/basic-file-based/tests/relative.spec.ts +++ b/e2e/react-router/basic-file-based/tests/relative.spec.ts @@ -1,11 +1,12 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) 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 68dfededc2..d14c2d156b 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import type { Page } from '@playwright/test' const anchors = { 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 a99488a47a..d6307cbcf8 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/basic-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/basic-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 3a90a3cd6d..568313a6c3 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", 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 fbda9bd451..f3083ff8b6 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,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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}` /** @@ -12,15 +17,17 @@ 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: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 1f6cb8e308..1becc2c242 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,7 +8,11 @@ export type PostType = { export class PostNotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +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 = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) 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 2b42d6d589..d80e8dada5 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,23 +1,24 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' +import { getDummyServerPort } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } test.beforeEach(async ({ page }) => { await page.goto('/') }) -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) +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() + 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/basic-react-query-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/basic-react-query-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 8f28340f56..a0af3b6c21 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/react-router/basic-react-query/playwright.config.ts b/e2e/react-router/basic-react-query/playwright.config.ts index 4eead86444..ab42c7c607 100644 --- a/e2e/react-router/basic-react-query/playwright.config.ts +++ b/e2e/react-router/basic-react-query/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 ffc5a274b7..5e2a2d3aa3 100644 --- a/e2e/react-router/basic-react-query/src/posts.ts +++ b/e2e/react-router/basic-react-query/src/posts.ts @@ -9,7 +9,11 @@ type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} 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 fbf093cd51..3e5a69ccaa 100644 --- a/e2e/react-router/basic-react-query/tests/app.spec.ts +++ b/e2e/react-router/basic-react-query/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/basic-react-query/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/basic-react-query/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 c13e92cec8..2ddbafc37f 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/react-router/basic-scroll-restoration/playwright.config.ts b/e2e/react-router/basic-scroll-restoration/playwright.config.ts index 6a684ac89e..0c5cee43e4 100644 --- a/e2e/react-router/basic-scroll-restoration/playwright.config.ts +++ b/e2e/react-router/basic-scroll-restoration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, 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 0343de0846..65122dd2a7 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", 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 4eead86444..c5de6b5611 100644 --- a/e2e/react-router/basic-virtual-file-based/playwright.config.ts +++ b/e2e/react-router/basic-virtual-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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,10 +22,13 @@ export default defineConfig({ baseURL, }, + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 cc3cb0f9c8..01831e335c 100644 --- a/e2e/react-router/basic-virtual-file-based/src/posts.tsx +++ b/e2e/react-router/basic-virtual-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) 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 fbf093cd51..3e5a69ccaa 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/basic-virtual-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/basic-virtual-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 6bdb1248f6..7738971eb6 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", 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 4eead86444..ab42c7c607 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,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 97c96d77eb..ae7142c5b6 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,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 = 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 7d2074182f..0aedada786 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 4ff68f5cda..6eba409188 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -17,8 +17,7 @@ "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "catalog:", - "tailwindcss": "^4.2.2", - "zod": "catalog:" + "tailwindcss": "^4.2.2" }, "devDependencies": { "@playwright/test": "^1.61.0", diff --git a/e2e/react-router/basic/playwright.config.ts b/e2e/react-router/basic/playwright.config.ts index 4eead86444..22c9bdcd7e 100644 --- a/e2e/react-router/basic/playwright.config.ts +++ b/e2e/react-router/basic/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', }, diff --git a/e2e/react-router/basic/src/main.tsx b/e2e/react-router/basic/src/main.tsx index 49fa054776..36e5106654 100644 --- a/e2e/react-router/basic/src/main.tsx +++ b/e2e/react-router/basic/src/main.tsx @@ -1,5 +1,3 @@ -import { useState } from 'react' -import { createPortal } from 'react-dom' import ReactDOM from 'react-dom/client' import { ErrorComponent, @@ -11,19 +9,12 @@ import { createRouter, redirect, } from '@tanstack/react-router' -import { - TanStackRouterDevtoolsInProd as TanStackRouterDevtools, - TanStackRouterDevtoolsPanelInProd as TanStackRouterDevtoolsPanel, -} from '@tanstack/react-router-devtools' -import { z } from 'zod' +import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' 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 ( @@ -36,8 +27,6 @@ const rootRoute = createRootRoute({ }) function RootComponent() { - const { devtools } = rootRoute.useSearch() - return ( <>
@@ -97,57 +86,12 @@ function RootComponent() {
-
- Devtools: - {(['floating', 'panel', 'shadow'] as const).map((mode) => ( - ({ - ...prev, - devtools: mode === 'floating' ? undefined : mode, - })} - className={ - (devtools ?? 'floating') === mode ? 'font-bold' : undefined - } - > - {mode} - - ))} -
- {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 f72d16fee3..e859645746 100644 --- a/e2e/react-router/basic/src/posts.ts +++ b/e2e/react-router/basic/src/posts.ts @@ -8,7 +8,11 @@ type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 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 9c0a6b6901..ec0e24d8a4 100644 --- a/e2e/react-router/basic/tests/app.spec.ts +++ b/e2e/react-router/basic/tests/app.spec.ts @@ -1,7 +1,8 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) 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 deleted file mode 100644 index b8a7e803e6..0000000000 --- a/e2e/react-router/basic/tests/devtools.spec.ts +++ /dev/null @@ -1,42 +0,0 @@ -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 f673138047..ac18f39864 100644 --- a/e2e/react-router/basic/tests/params.spec.ts +++ b/e2e/react-router/basic/tests/params.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/basic/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/basic/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 af401c49d3..71a3cb08ca 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": "playwright test --project=chromium" + "test:e2e:default": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", diff --git a/e2e/react-router/escaped-special-strings/playwright.config.ts b/e2e/react-router/escaped-special-strings/playwright.config.ts index 629ddefccf..6e4e1d7703 100644 --- a/e2e/react-router/escaped-special-strings/playwright.config.ts +++ b/e2e/react-router/escaped-special-strings/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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}` const command = `pnpm build && pnpm preview --port ${PORT}` @@ -16,6 +21,9 @@ 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, @@ -23,12 +31,15 @@ export default defineConfig({ webServer: { command, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, 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/tests/setup/global.setup.ts b/e2e/react-router/escaped-special-strings/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/escaped-special-strings/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/escaped-special-strings/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 159ba05500..f7ff46d958 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/react-router/generator-cli-only/playwright.config.ts b/e2e/react-router/generator-cli-only/playwright.config.ts index 4eead86444..c9d9a76ae7 100644 --- a/e2e/react-router/generator-cli-only/playwright.config.ts +++ b/e2e/react-router/generator-cli-only/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 f72d16fee3..e859645746 100644 --- a/e2e/react-router/generator-cli-only/src/posts.ts +++ b/e2e/react-router/generator-cli-only/src/posts.ts @@ -8,7 +8,11 @@ type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 fetchPosts = async () => { console.info('Fetching posts...') 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 ced5ac9310..5a83a314f2 100644 --- a/e2e/react-router/generator-cli-only/tests/app.spec.ts +++ b/e2e/react-router/generator-cli-only/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/generator-cli-only/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/generator-cli-only/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 d1af160f10..a100d58e85 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -29,23 +29,5 @@ "@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 8e94d5f9a1..91ef8fbd9f 100644 --- a/e2e/react-router/i18n-paraglide/playwright.config.ts +++ b/e2e/react-router/i18n-paraglide/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/issue-4759/package.json b/e2e/react-router/issue-4759/package.json index ee6a105ad5..91a7a5053e 100644 --- a/e2e/react-router/issue-4759/package.json +++ b/e2e/react-router/issue-4759/package.json @@ -8,7 +8,7 @@ "dev:e2e": "vite", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", diff --git a/e2e/react-router/issue-4759/playwright.config.ts b/e2e/react-router/issue-4759/playwright.config.ts index a301f62881..b5e8249edc 100644 --- a/e2e/react-router/issue-4759/playwright.config.ts +++ b/e2e/react-router/issue-4759/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -11,8 +12,8 @@ export default defineConfig({ use: { baseURL }, webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, projects: [ diff --git a/e2e/react-router/issue-7120/package.json b/e2e/react-router/issue-7120/package.json index 979b32556c..a16155eb61 100644 --- a/e2e/react-router/issue-7120/package.json +++ b/e2e/react-router/issue-7120/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", diff --git a/e2e/react-router/issue-7120/playwright.config.ts b/e2e/react-router/issue-7120/playwright.config.ts index a8ba116fb4..61a995a815 100644 --- a/e2e/react-router/issue-7120/playwright.config.ts +++ b/e2e/react-router/issue-7120/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -11,8 +12,8 @@ export default defineConfig({ use: { baseURL }, webServer: { command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, projects: [ diff --git a/e2e/react-router/issue-7457/package.json b/e2e/react-router/issue-7457/package.json index 838f5173e2..3220a4dbb4 100644 --- a/e2e/react-router/issue-7457/package.json +++ b/e2e/react-router/issue-7457/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-query": "^5.99.0", diff --git a/e2e/react-router/issue-7457/playwright.config.ts b/e2e/react-router/issue-7457/playwright.config.ts index a8ba116fb4..61a995a815 100644 --- a/e2e/react-router/issue-7457/playwright.config.ts +++ b/e2e/react-router/issue-7457/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -11,8 +12,8 @@ export default defineConfig({ use: { baseURL }, webServer: { command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, projects: [ diff --git a/e2e/react-router/js-only-file-based/package.json b/e2e/react-router/js-only-file-based/package.json index 39742d9c84..a8fbe87b8f 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", 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 0925936d55..4f93bc1413 100644 --- a/e2e/react-router/js-only-file-based/playwright.config.ts +++ b/e2e/react-router/js-only-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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}` /** @@ -13,15 +18,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 36c1c281f6..979e5e381c 100644 --- a/e2e/react-router/js-only-file-based/src/posts.js +++ b/e2e/react-router/js-only-file-based/src/posts.js @@ -2,7 +2,11 @@ import axios from 'redaxios' export class NotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +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 fetchPosts = async () => { console.info('Fetching posts...') 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 ced5ac9310..5a83a314f2 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/js-only-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/js-only-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 908be67a9d..3282e5e5c2 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", diff --git a/e2e/react-router/match-params/playwright.config.ts b/e2e/react-router/match-params/playwright.config.ts index 9e8c1fab2b..246cf40060 100644 --- a/e2e/react-router/match-params/playwright.config.ts +++ b/e2e/react-router/match-params/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -13,8 +14,8 @@ export default defineConfig({ }, webServer: { command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, projects: [ diff --git a/e2e/react-router/react-compiler/package.json b/e2e/react-router/react-compiler/package.json index 82e6fbf86b..d4d0e6473a 100644 --- a/e2e/react-router/react-compiler/package.json +++ b/e2e/react-router/react-compiler/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", diff --git a/e2e/react-router/react-compiler/playwright.config.ts b/e2e/react-router/react-compiler/playwright.config.ts index a8ba116fb4..61a995a815 100644 --- a/e2e/react-router/react-compiler/playwright.config.ts +++ b/e2e/react-router/react-compiler/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -11,8 +12,8 @@ export default defineConfig({ use: { baseURL }, webServer: { command: `VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, projects: [ diff --git a/e2e/react-router/rspack-basic-file-based/package.json b/e2e/react-router/rspack-basic-file-based/package.json index 5ec9ed9862..af7c78ec7b 100644 --- a/e2e/react-router/rspack-basic-file-based/package.json +++ b/e2e/react-router/rspack-basic-file-based/package.json @@ -7,7 +7,7 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -18,7 +18,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", "@tailwindcss/postcss": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", 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 4eead86444..decceaef2f 100644 --- a/e2e/react-router/rspack-basic-file-based/playwright.config.ts +++ b/e2e/react-router/rspack-basic-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 97c96d77eb..a1225b7fe7 100644 --- a/e2e/react-router/rspack-basic-file-based/src/posts.tsx +++ b/e2e/react-router/rspack-basic-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.PUBLIC_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` +} 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 d230263bfe..10beff655f 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/rspack-basic-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/rspack-basic-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 30c62d0af1..07daac365c 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,7 +7,7 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -18,7 +18,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", "@tailwindcss/postcss": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", 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 1c1d021f2f..bf3adc082c 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,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm start --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 cc3cb0f9c8..b196982420 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,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.PUBLIC_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` +} 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 8b808782f6..a689f459e3 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 51e9e70cc5..a4ad2e8121 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": "pnpm run test:e2e:browser && pnpm run test:e2e:hash" + "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:browser && pnpm run test:e2e:hash" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -31,15 +31,5 @@ "@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 eb31d94080..972124647c 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,7 +1,15 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, + resolveRuntimeSuffix, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + packageJson.name + `-${resolveRuntimeSuffix('browser')}`, +) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,15 +21,18 @@ 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_APP_HISTORY=browser pnpm build && VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 6b160e3908..a6fa77afbf 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,7 +1,15 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, + resolveRuntimeSuffix, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + packageJson.name + `-${resolveRuntimeSuffix('hash')}`, +) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,15 +21,18 @@ 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_APP_HISTORY=hash vite build --outDir dist-hash && VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 c4a2d0dcca..e45ef52969 100644 --- a/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx +++ b/e2e/react-router/scroll-restoration-sandbox-vite/src/posts.tsx @@ -10,7 +10,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export class PostNotFoundError extends Error {} 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 e396c28686..9c2d944dd5 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import { linkOptions } from '@tanstack/react-router' import { toRuntimePath } from '@tanstack/router-e2e-utils' diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/tests/issue-7040.repro.spec.ts b/e2e/react-router/scroll-restoration-sandbox-vite/tests/issue-7040.repro.spec.ts index 2db25517c8..db335f8e2e 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import type { Page } from '@playwright/test' import { toRuntimePath } from '@tanstack/router-e2e-utils' @@ -27,7 +26,7 @@ type ReproAttempt = { async function openFreshSourcePage(page: Page) { await page.goto(toRuntimePath('/issue-7040-source')) - await expect(page.getByTestId('issue-7040-source-top')).toBeVisible() + await page.waitForLoadState('networkidle') await page.evaluate(() => { sessionStorage.clear() @@ -35,7 +34,7 @@ async function openFreshSourcePage(page: Page) { }) await page.reload() - await expect(page.getByTestId('issue-7040-source-top')).toBeVisible() + await page.waitForLoadState('networkidle') } async function fastScrollSourcePage(page: Page) { @@ -97,7 +96,7 @@ async function clickTargetLinkImmediatelyAfterScroll(page: Page) { async function waitForTargetPageToSettle(page: Page) { await page.waitForURL('**/issue-7040-target') - await expect(page.getByTestId('issue-7040-target-top')).toBeVisible() + await page.waitForLoadState('networkidle') 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 5d58406b2e..f33b5a7aa3 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", "dist-hash"] + "exclude": ["node_modules", "dist"] } diff --git a/e2e/react-router/sentry-integration/package.json b/e2e/react-router/sentry-integration/package.json index 5ebbdf31d9..b136e4f9a4 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@sentry/react": "^10.32.0", diff --git a/e2e/react-router/sentry-integration/playwright.config.ts b/e2e/react-router/sentry-integration/playwright.config.ts index 6a684ac89e..0c5cee43e4 100644 --- a/e2e/react-router/sentry-integration/playwright.config.ts +++ b/e2e/react-router/sentry-integration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-router/view-transitions/package.json b/e2e/react-router/view-transitions/package.json index e2d7a181e1..03ed5c3be9 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/react-router/view-transitions/playwright.config.ts b/e2e/react-router/view-transitions/playwright.config.ts index 4eead86444..c5de6b5611 100644 --- a/e2e/react-router/view-transitions/playwright.config.ts +++ b/e2e/react-router/view-transitions/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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,10 +22,13 @@ export default defineConfig({ baseURL, }, + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', }, diff --git a/e2e/react-router/view-transitions/tests/app.spec.ts b/e2e/react-router/view-transitions/tests/app.spec.ts index 6c1ccf1a6e..472bd6ed0b 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 { apiTest as test } from '@tanstack/router-e2e-utils' +import { test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-router/view-transitions/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-router/view-transitions/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 f7ff609e76..b434d3f305 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; pnpm run prisma-generate && playwright test --project=chromium" + "test:e2e": "exit 0; rm -rf port*.txt; pnpm run prisma-generate && playwright test --project=chromium" }, "dependencies": { "@libsql/client": "^0.15.15", @@ -19,7 +19,6 @@ "@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": "catalog:", diff --git a/e2e/react-start/basic-auth/playwright.config.ts b/e2e/react-start/basic-auth/playwright.config.ts index 82678ac00b..18b8905468 100644 --- a/e2e/react-start/basic-auth/playwright.config.ts +++ b/e2e/react-start/basic-auth/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/basic-auth/src/routes/__root.tsx b/e2e/react-start/basic-auth/src/routes/__root.tsx index fb7868435d..76e5f8b1d6 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 { getAppSession } from '~/utils/session.js' +import { useAppSession } 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 getAppSession() + const session = await useAppSession() - if (!session.userEmail) { + if (!session.data.userEmail) { return null } return { - email: session.userEmail, + email: session.data.userEmail, } }) diff --git a/e2e/react-start/basic-auth/src/routes/_authed.tsx b/e2e/react-start/basic-auth/src/routes/_authed.tsx index fe73185136..0d87cfbacb 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 { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST', @@ -37,11 +37,12 @@ export const loginFn = createServerFn({ } // Create a session - const session = await getAppSession() + const session = await useAppSession() // Store the user's email in the session - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) }) export const Route = createFileRoute('/_authed')({ diff --git a/e2e/react-start/basic-auth/src/routes/logout.tsx b/e2e/react-start/basic-auth/src/routes/logout.tsx index 0f86b0d4e3..a08f9c737e 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 { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await getAppSession() + const session = await useAppSession() - session.destroy() + session.clear() 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 d7d5d40129..817362dc05 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 { getAppSession } from '~/utils/session' +import { useAppSession } 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 getAppSession() + const session = await useAppSession() if (found) { if (found.password !== password) { @@ -36,8 +36,9 @@ export const signupFn = createServerFn({ } // Store the user's email in the session - session.userEmail = found.email - await session.save() + await session.update({ + userEmail: found.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -54,8 +55,9 @@ export const signupFn = createServerFn({ }) // Store the user's email in the session - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) // 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 f1deacf85b..c38bac1e48 100644 --- a/e2e/react-start/basic-auth/src/utils/session.ts +++ b/e2e/react-start/basic-auth/src/utils/session.ts @@ -1,25 +1,13 @@ -import { getIronSession } from 'iron-session' -import { getCookie, setCookie } from '@tanstack/react-start/server' +// src/services/session.server.ts +import { useSession } from '@tanstack/react-start/server' import type { User } from '@prisma/client' type SessionUser = { userEmail: User['email'] } -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: '/', - }, - }, - ) +export function useAppSession() { + return useSession({ + password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', + }) } diff --git a/e2e/react-start/basic-cloudflare/package.json b/e2e/react-start/basic-cloudflare/package.json index b9b8031ac4..7baa24073b 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -33,15 +33,5 @@ "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 0925936d55..a545dff891 100644 --- a/e2e/react-start/basic-cloudflare/playwright.config.ts +++ b/e2e/react-start/basic-cloudflare/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,6 +14,9 @@ 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, @@ -20,8 +24,8 @@ export default defineConfig({ webServer: { command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/basic-cloudflare/tests/app.spec.ts b/e2e/react-start/basic-cloudflare/tests/app.spec.ts index c9497070dd..add28cb73e 100644 --- a/e2e/react-start/basic-cloudflare/tests/app.spec.ts +++ b/e2e/react-start/basic-cloudflare/tests/app.spec.ts @@ -1,5 +1,3 @@ -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' @@ -31,19 +29,3 @@ 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-start/basic-cloudflare/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/basic-cloudflare/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 ee37b82ba6..87789282ec 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-query": "^5.90.0", @@ -32,7 +32,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/react-start/basic-react-query/playwright.config.ts b/e2e/react-start/basic-react-query/playwright.config.ts index 216fade4d5..fd2150e435 100644 --- a/e2e/react-start/basic-react-query/playwright.config.ts +++ b/e2e/react-start/basic-react-query/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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}` /** @@ -13,19 +18,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: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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/routes/api.users.ts b/e2e/react-start/basic-react-query/src/routes/api.users.ts index 924c5b6860..bb37c6e68d 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,7 +2,11 @@ import { createFileRoute } from '@tanstack/react-router' import axios from 'redaxios' import type { User } from '../utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +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: { 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 febea309ea..e11e039652 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,7 +2,11 @@ import { createFileRoute } from '@tanstack/react-router' import axios from 'redaxios' import type { User } from '../../utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +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: { 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 abb6e95b92..3fd16db69a 100644 --- a/e2e/react-start/basic-react-query/src/utils/posts.tsx +++ b/e2e/react-start/basic-react-query/src/utils/posts.tsx @@ -9,7 +9,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 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 15216680e9..26b934fcb3 100644 --- a/e2e/react-start/basic-react-query/src/utils/users.tsx +++ b/e2e/react-start/basic-react-query/src/utils/users.tsx @@ -1,6 +1,4 @@ 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 = { @@ -9,16 +7,17 @@ export type User = { email: string } -const getOrigin = createIsomorphicFn() - .server(() => getRequestUrl().origin) - .client(() => window.location.origin) +const PORT = + import.meta.env.VITE_SERVER_PORT || process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` export const usersQueryOptions = () => queryOptions({ queryKey: ['users'], queryFn: () => axios - .get>(getOrigin() + '/api/users') + .get>(DEPLOY_URL + '/api/users') .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch users') @@ -30,7 +29,7 @@ export const userQueryOptions = (id: string) => queryKey: ['users', id], queryFn: () => axios - .get(getOrigin() + '/api/users/' + id) + .get(DEPLOY_URL + '/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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-start/basic-react-query/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/basic-react-query/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 99e681ac9d..6aaacfefd4 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -21,7 +21,7 @@ "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@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-tsr-config/playwright.config.ts b/e2e/react-start/basic-tsr-config/playwright.config.ts index 82678ac00b..18b8905468 100644 --- a/e2e/react-start/basic-tsr-config/playwright.config.ts +++ b/e2e/react-start/basic-tsr-config/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/basic/package.json b/e2e/react-start/basic/package.json index 3a1a4ea9c8..f0a15aa274 100644 --- a/e2e/react-start/basic/package.json +++ b/e2e/react-start/basic/package.json @@ -14,6 +14,8 @@ "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": { @@ -22,7 +24,6 @@ "@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", @@ -31,7 +32,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", "@tailwindcss/postcss": "^4.2.2", "@tailwindcss/vite": "^4.2.2", @@ -42,7 +43,7 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", @@ -50,18 +51,6 @@ "zod": "^4.4.3" }, "nx": { - "targets": { - "test:e2e--vite-spa--dev": { - "dependsOn": [ - "^build" - ] - }, - "test:e2e--rsbuild-spa--dev": { - "dependsOn": [ - "^build" - ] - } - }, "metadata": { "playwrightModes": [ { @@ -74,18 +63,7 @@ }, { "toolchain": "vite", - "mode": "spa", - "name": "dev", - "env": { - "E2E_DEV_SERVER": "true" - } - }, - { - "toolchain": "vite", - "mode": "prerender", - "env": { - "NODE_OPTIONS": "--import=@tanstack/router-e2e-utils/mock-api" - } + "mode": "prerender" }, { "toolchain": "vite", @@ -109,18 +87,7 @@ }, { "toolchain": "rsbuild", - "mode": "spa", - "name": "dev", - "env": { - "E2E_DEV_SERVER": "true" - } - }, - { - "toolchain": "rsbuild", - "mode": "prerender", - "env": { - "NODE_OPTIONS": "--import=@tanstack/router-e2e-utils/mock-api" - } + "mode": "prerender" }, { "toolchain": "rsbuild", diff --git a/e2e/react-start/basic/playwright.config.ts b/e2e/react-start/basic/playwright.config.ts index bb4c2cb761..db07d18608 100644 --- a/e2e/react-start/basic/playwright.config.ts +++ b/e2e/react-start/basic/playwright.config.ts @@ -1,42 +1,48 @@ +import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } 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' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +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 baseURL = `http://localhost:${PORT}` const previewCommand = toolchain === 'rsbuild' - ? `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' + ? `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` /** * 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, @@ -44,16 +50,19 @@ export default defineConfig({ webServer: { command: commandByMode, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, MODE: mode, E2E_TOOLCHAIN: toolchain, - START_PORT: '0', + VITE_NODE_ENV: 'test', + VITE_EXTERNAL_PORT: String(EXTERNAL_PORT), + VITE_SERVER_PORT: String(PORT), + START_PORT: String(START_PORT), 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/server.js b/e2e/react-start/basic/server.js index 3e1ddab400..69c1e4ca91 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 = Number(process.env.PORT ?? 3000) +const port = process.env.PORT || 3000 -const startPort = Number(process.env.START_PORT ?? 0) +const startPort = process.env.START_PORT || 3001 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(backendPort) { +export async function createSpaServer() { const app = express() app.use( '/api', createProxyMiddleware({ - target: `http://localhost:${backendPort}/api`, // Replace with your target server's URL + target: `http://localhost:${startPort}/api`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -63,7 +63,7 @@ export async function createSpaServer(backendPort) { app.use( '/_serverFn', createProxyMiddleware({ - target: `http://localhost:${backendPort}/_serverFn`, // Replace with your target server's URL + target: `http://localhost:${startPort}/_serverFn`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -71,28 +71,31 @@ export async function createSpaServer(backendPort) { app.use(express.static(distClientDir)) app.get('/{*splat}', (req, res) => { - res.sendFile('index.html', { root: distClientDir }) + res.sendFile(path.resolve(distClientDir, 'index.html')) }) return { app } } -// 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}`) - } -}) +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}`) + }), + ) +} diff --git a/e2e/react-start/basic/src/routeTree.gen.ts b/e2e/react-start/basic/src/routeTree.gen.ts index b6603dd01d..d5416aa352 100644 --- a/e2e/react-start/basic/src/routeTree.gen.ts +++ b/e2e/react-start/basic/src/routeTree.gen.ts @@ -15,8 +15,6 @@ 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' @@ -115,16 +113,6 @@ const DeferredRoute = DeferredRouteImport.update({ 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', @@ -491,8 +479,6 @@ export interface FileRoutesByFullPath { '/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 @@ -565,8 +551,6 @@ export interface FileRoutesByTo { '/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 @@ -636,8 +620,6 @@ export interface FileRoutesById { '/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 @@ -715,8 +697,6 @@ export interface FileRouteTypes { | '/auth-docs' | '/client-only' | '/deferred' - | '/execution-local' - | '/execution-rpc' | '/inline-scripts' | '/links' | '/plain-ts-type-assertion' @@ -789,8 +769,6 @@ export interface FileRouteTypes { | '/auth-docs' | '/client-only' | '/deferred' - | '/execution-local' - | '/execution-rpc' | '/inline-scripts' | '/links' | '/plain-ts-type-assertion' @@ -859,8 +837,6 @@ export interface FileRouteTypes { | '/auth-docs' | '/client-only' | '/deferred' - | '/execution-local' - | '/execution-rpc' | '/inline-scripts' | '/links' | '/plain-ts-type-assertion' @@ -938,8 +914,6 @@ export interface RootRouteChildren { AuthDocsRoute: typeof AuthDocsRouteWithChildren ClientOnlyRoute: typeof ClientOnlyRoute DeferredRoute: typeof DeferredRoute - ExecutionLocalRoute: typeof ExecutionLocalRoute - ExecutionRpcRoute: typeof ExecutionRpcRoute InlineScriptsRoute: typeof InlineScriptsRoute LinksRoute: typeof LinksRoute PlainTsTypeAssertionRoute: typeof PlainTsTypeAssertionRoute @@ -1005,20 +979,6 @@ declare module '@tanstack/react-router' { 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' @@ -1769,8 +1729,6 @@ const rootRouteChildren: RootRouteChildren = { AuthDocsRoute: AuthDocsRouteWithChildren, ClientOnlyRoute: ClientOnlyRoute, DeferredRoute: DeferredRoute, - ExecutionLocalRoute: ExecutionLocalRoute, - ExecutionRpcRoute: ExecutionRpcRoute, InlineScriptsRoute: InlineScriptsRoute, LinksRoute: LinksRoute, PlainTsTypeAssertionRoute: PlainTsTypeAssertionRoute, diff --git a/e2e/react-start/basic/src/routes/__root.tsx b/e2e/react-start/basic/src/routes/__root.tsx index ed521817d6..d8fc0d3b24 100644 --- a/e2e/react-start/basic/src/routes/__root.tsx +++ b/e2e/react-start/basic/src/routes/__root.tsx @@ -197,9 +197,6 @@ function RootDocument({ children }: { children: React.ReactNode }) { > Client Only {' '} - - Server function loader - {' '} { console.info('Fetching users... @', request.url) - const res = await axios.get>( - 'https://jsonplaceholder.typicode.com/users', - ) + const res = await axios.get>(`${queryURL}/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 797dffb637..ac665381f1 100644 --- a/e2e/react-start/basic/src/routes/api/users.$id.ts +++ b/e2e/react-start/basic/src/routes/api/users.$id.ts @@ -2,15 +2,19 @@ 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( - `https://jsonplaceholder.typicode.com/users/${params.id}`, - ) + const res = await axios.get(`${queryURL}/users/` + params.id) return Response.json({ id: res.data.id, diff --git a/e2e/react-start/basic/src/routes/execution-local.tsx b/e2e/react-start/basic/src/routes/execution-local.tsx deleted file mode 100644 index 477cd81740..0000000000 --- a/e2e/react-start/basic/src/routes/execution-local.tsx +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index f934015522..0000000000 --- a/e2e/react-start/basic/src/routes/execution-rpc.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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/utils/auth-docs.ts b/e2e/react-start/basic/src/utils/auth-docs.ts index 22b36ee808..c5f0f11645 100644 --- a/e2e/react-start/basic/src/utils/auth-docs.ts +++ b/e2e/react-start/basic/src/utils/auth-docs.ts @@ -1,29 +1,18 @@ 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' +import { useSession } from '@tanstack/react-start/server' 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: '/', - }, - }, - ) + return useSession<{ email?: string }>({ + name: 'auth-docs-test', + password: 'authentication-docs-browser-test-secret-only-2026', + }) } export const getCurrentUserFn = createServerFn({ method: 'GET' }).handler( async () => { const session = await getSession() - return session.email ? { email: session.email } : null + return session.data.email ? { email: session.data.email } : null }, ) @@ -38,21 +27,20 @@ export const loginFn = createServerFn({ method: 'POST' }) return { error: 'Invalid credentials' } } const session = await getSession() - session.email = data.email - await session.save() + await session.update({ email: data.email }) throw redirect({ to: '/auth-docs/private' }) }) export const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { const session = await getSession() - session.destroy() + await session.clear() throw redirect({ to: '/auth-docs' }) }) export const getPrivateDataFn = createServerFn({ method: 'GET' }).handler( async () => { const session = await getSession() - if (!session.email) { + if (!session.data.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 deleted file mode 100644 index 97e66573d8..0000000000 --- a/e2e/react-start/basic/src/utils/execution-functions.ts +++ /dev/null @@ -1,5 +0,0 @@ -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 9fdff27673..4cc5dcc4c6 100644 --- a/e2e/react-start/basic/src/utils/posts.tsx +++ b/e2e/react-start/basic/src/utils/posts.tsx @@ -8,12 +8,18 @@ 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(`https://jsonplaceholder.typicode.com/posts/${postId}`) + .get(`${queryURL}/posts/${postId}`) .then((r) => r.data) .catch((err) => { console.error(err) @@ -30,7 +36,7 @@ export const fetchPosts = createServerFn({ method: 'GET' }).handler( async () => { console.info('Fetching posts...') return axios - .get>('https://jsonplaceholder.typicode.com/posts') + .get>(`${queryURL}/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 7ba645b383..46be4b1580 100644 --- a/e2e/react-start/basic/src/utils/users.tsx +++ b/e2e/react-start/basic/src/utils/users.tsx @@ -3,3 +3,7 @@ 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/client-only.spec.ts b/e2e/react-start/basic/tests/client-only.spec.ts index 299744f636..a3b6f99442 100644 --- a/e2e/react-start/basic/tests/client-only.spec.ts +++ b/e2e/react-start/basic/tests/client-only.spec.ts @@ -1,6 +1,5 @@ import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' -import { isSpaMode } from './utils/isSpaMode' /** * These tests verify the compiler optimization. @@ -16,15 +15,7 @@ import { isSpaMode } from './utils/isSpaMode' 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 deleted file mode 100644 index 410b1d999e..0000000000 --- a/e2e/react-start/basic/tests/environment-functions.spec.ts +++ /dev/null @@ -1,46 +0,0 @@ -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 deleted file mode 100644 index 6c9b26dc4c..0000000000 --- a/e2e/react-start/basic/tests/fixture-api.spec.ts +++ /dev/null @@ -1,11 +0,0 @@ -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/redirect.spec.ts b/e2e/react-start/basic/tests/redirect.spec.ts index 010ecec155..34ba7b6ea9 100644 --- a/e2e/react-start/basic/tests/redirect.spec.ts +++ b/e2e/react-start/basic/tests/redirect.spec.ts @@ -1,15 +1,20 @@ import queryString from 'node:querystring' -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' +import { expect, type Page } from '@playwright/test' import combinateImport from 'combinate' -import type { Page } from '@playwright/test' +import { + getDummyServerPort, + getTestServerPort, + test, +} from '@tanstack/router-e2e-utils' +import { getE2EPortKey } from './utils/getE2EPortKey.ts' // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport +const e2ePortKey = getE2EPortKey() -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(e2ePortKey) -const EXTERNAL_ORIGIN = `http://127.0.0.1:${PORT}` +const EXTERNAL_HOST_PORT = await getDummyServerPort(e2ePortKey) const POSTS_URL = `http://localhost:${PORT}/posts` async function waitForRouterIdle(page: Page) { @@ -106,7 +111,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, }) if (scenario === 'navigate') { @@ -119,7 +124,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/external/via-${thrower}?${q}`) } - const url = `${EXTERNAL_ORIGIN}/` + const url = `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) @@ -142,7 +147,7 @@ test.describe('redirects', () => { }) => { let fullPageLoad = false const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, reloadDocument, }) @@ -165,7 +170,10 @@ test.describe('redirects', () => { await page.goto(`/redirect/${target}/serverFn/via-${thrower}?${q}`) } - const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` + const url = + target === 'internal' + ? POSTS_URL + : `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) @@ -194,7 +202,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, reloadDocument, }) @@ -211,7 +219,10 @@ test.describe('redirects', () => { await button.click() - const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` + const url = + target === 'internal' + ? POSTS_URL + : `http://localhost:${EXTERNAL_HOST_PORT}/` 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 deleted file mode 100644 index d16ff0bb54..0000000000 --- a/e2e/react-start/basic/tests/setup/dev-server.setup.ts +++ /dev/null @@ -1,19 +0,0 @@ -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 new file mode 100644 index 0000000000..cd38c35885 --- /dev/null +++ b/e2e/react-start/basic/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..36e5c92858 --- /dev/null +++ b/e2e/react-start/basic/tests/setup/global.teardown.ts @@ -0,0 +1,8 @@ +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 new file mode 100644 index 0000000000..88c18fd79e --- /dev/null +++ b/e2e/react-start/basic/tests/setup/waitForDummyServer.ts @@ -0,0 +1,24 @@ +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 deleted file mode 100644 index f42195e762..0000000000 --- a/e2e/react-start/basic/tests/spa-shell.spec.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' -import { isSpaMode } from './utils/isSpaMode' - -// The prod SPA run and the dev SPA runs (`E2E_DEV_SERVER`) all run this file. -// The dev runs run nothing else. -test.skip(!isSpaMode, 'only SPA mode answers documents with the shell') - -// Its loader and beforeLoad report where they ran. -const searchRoute = '/specialChars/search?searchParam=shell' - -test('a document request gets the shell, not the rendered route', async ({ - request, -}) => { - const response = await request.get(searchRoute) - - expect(response.status()).toBe(200) - const html = await response.text() - // The root route's document renders... - expect(html).toContain('This Route Does Not Exist') - // ...but not the matched route, nor its loader's output. - expect(html).not.toContain('special-search-loaded-info') - expect(html).not.toContain('Loaded on: server') -}) - -test('the route loads in the browser', async ({ page }) => { - await page.goto(searchRoute) - - await expect(page.getByTestId('special-search-loaded-info')).toHaveText( - 'Loaded on: client', - ) - await expect(page.getByTestId('special-search-before-load-info')).toHaveText( - 'Before load on: client', - ) - await expect(page.getByTestId('special-search-param')).toHaveText('shell') -}) - -test('client navigation works from the shell', async ({ page }) => { - await page.goto('/') - await expect(page.getByRole('heading')).toContainText('Welcome Home') - await expect(page.getByTestId('router-status')).toHaveText('idle') - - // A full page load would drop this. - await page.evaluate(() => { - ;(window as any).__spaShellPage = true - }) - await page.getByRole('link', { name: 'Posts' }).click() - await page.waitForURL('/posts') - await expect( - page.getByRole('link', { name: 'sunt aut facere repe' }), - ).toBeVisible() - expect(await page.evaluate(() => (window as any).__spaShellPage)).toBe(true) -}) diff --git a/e2e/react-start/basic/tests/utils/getE2EPortKey.ts b/e2e/react-start/basic/tests/utils/getE2EPortKey.ts new file mode 100644 index 0000000000..48be6a9027 --- /dev/null +++ b/e2e/react-start/basic/tests/utils/getE2EPortKey.ts @@ -0,0 +1,5 @@ +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 7838b4cee1..65f405eb69 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; playwright test --project=chromium" + "test:e2e": "exit 0; rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@clerk/tanstack-react-start": "^0.19.0", diff --git a/e2e/react-start/clerk-basic/playwright.config.ts b/e2e/react-start/clerk-basic/playwright.config.ts index 82678ac00b..18b8905468 100644 --- a/e2e/react-start/clerk-basic/playwright.config.ts +++ b/e2e/react-start/clerk-basic/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/csp/package.json b/e2e/react-start/csp/package.json index fd8987bcef..bbe4df9bbc 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -22,7 +22,7 @@ "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@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 87b32e1f50..5f9de5709e 100644 --- a/e2e/react-start/csp/playwright.config.ts +++ b/e2e/react-start/csp/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/css-inline/package.json b/e2e/react-start/css-inline/package.json index 6c5dd031c6..7d9c0520fc 100644 --- a/e2e/react-start/css-inline/package.json +++ b/e2e/react-start/css-inline/package.json @@ -20,11 +20,11 @@ "express": "^5.2.1", "react": "^19.0.0", "react-dom": "^19.0.0", - "srvx": "^1.0.0" + "srvx": "^0.11.9" }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", @@ -38,47 +38,7 @@ "nx": { "targets": { "test:e2e": { - "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" - ] + "parallelism": false } }, "metadata": { diff --git a/e2e/react-start/css-inline/playwright.config.ts b/e2e/react-start/css-inline/playwright.config.ts index 78e7b75252..b5d78f3608 100644 --- a/e2e/react-start/css-inline/playwright.config.ts +++ b/e2e/react-start/css-inline/playwright.config.ts @@ -1,5 +1,7 @@ +import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } const toolchain = process.env.E2E_TOOLCHAIN ?? 'vite' const inlineCssTransformAssets = @@ -16,8 +18,15 @@ 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}` -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +if (process.env.TEST_WORKER_INDEX === undefined) { + fs.rmSync(`port-${e2ePortKey}.txt`, { force: true }) +} + +const PORT = await getTestServerPort(e2ePortKey) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -31,8 +40,8 @@ export default defineConfig({ webServer: { command: `pnpm build:${toolchain} && pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { E2E_DIST_DIR: distDir, diff --git a/e2e/react-start/css-inline/server.js b/e2e/react-start/css-inline/server.js index 27b2357284..fcdec3b888 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 = Number(process.env.PORT ?? 3000) +const port = process.env.PORT || 3000 const distDir = process.env.E2E_DIST_DIR || 'dist-vite-ssr' const distClientDir = path.resolve(distDir, 'client') @@ -37,10 +37,8 @@ async function createStartServer() { } createStartServer().then((app) => { - const httpServer = app.listen(port, (error) => { - if (error) { - throw error - } - console.info(`E2E app: http://localhost:${httpServer.address().port}`) + app.listen(port, (error) => { + if (error) throw error + console.info(`Start Server: http://localhost:${port}`) }) }) diff --git a/e2e/react-start/css-modules/.gitignore b/e2e/react-start/css-modules/.gitignore index a1fbca128d..229709a89d 100644 --- a/e2e/react-start/css-modules/.gitignore +++ b/e2e/react-start/css-modules/.gitignore @@ -3,4 +3,3 @@ 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 deleted file mode 100644 index e2bd5e13f1..0000000000 --- a/e2e/react-start/css-modules/cloudflare.config.ts +++ /dev/null @@ -1,11 +0,0 @@ -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 25c11d7321..2591161d66 100644 --- a/e2e/react-start/css-modules/package.json +++ b/e2e/react-start/css-modules/package.json @@ -12,8 +12,6 @@ "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", @@ -21,16 +19,13 @@ "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": "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" + "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" }, "dependencies": { "@tanstack/react-router": "workspace:*", @@ -41,36 +36,17 @@ "devDependencies": { "@cloudflare/vite-plugin": "^1.29.0", "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", - "@rsbuild/plugin-react": "^2.0.0", - "@rsbuild/plugin-sass": "^2.0.1", "@tanstack/router-e2e-utils": "workspace:*", "@types/node": "^22.10.2", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", - "@typescript/native": "npm:typescript@^7.0.2", "@vitejs/plugin-react": "^6.0.1", - "cf": "1.0.0-beta.28", - "nitro": "^3.0.260903-beta", - "rsbuild-plugin-cloudflare": "^0.0.4", + "nitro": "^3.0.260311-beta", "sass": "^1.97.2", - "srvx": "^1.0.0", + "srvx": "^0.11.9", + "@typescript/native": "npm:typescript@^7.0.2", "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 7e7ad3d9b3..644798ca99 100644 --- a/e2e/react-start/css-modules/playwright.config.ts +++ b/e2e/react-start/css-modules/playwright.config.ts @@ -1,41 +1,37 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +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 distDir = process.env.E2E_DIST_DIR const viteConfig = process.env.VITE_CONFIG // 'nitro' | 'basepath' | 'cloudflare' | undefined -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + viteConfig ? `${packageJson.name}-${viteConfig}` : packageJson.name, +) // 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 --port 0' +const devCommand = viteConfig ? `pnpm dev:e2e:${viteConfig}` : 'pnpm dev:e2e' 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 - : distDir - ? `pnpm exec srvx --prod --dir=. -s ${distDir}/client --entry ${distDir}/server/server.js` - : `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: isDev ? devCommand : `pnpm build && PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, 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 deleted file mode 100644 index 499ed67ebc..0000000000 --- a/e2e/react-start/css-modules/rsbuild.config.ts +++ /dev/null @@ -1,63 +0,0 @@ -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 deleted file mode 100644 index e6878a5410..0000000000 --- a/e2e/react-start/css-modules/src/components/Header.module.css +++ /dev/null @@ -1,14 +0,0 @@ -.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 deleted file mode 100644 index f16b12e8ff..0000000000 --- a/e2e/react-start/css-modules/src/components/Header.tsx +++ /dev/null @@ -1,11 +0,0 @@ -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 2789a3490a..822118990d 100644 --- a/e2e/react-start/css-modules/src/routeTree.gen.ts +++ b/e2e/react-start/css-modules/src/routeTree.gen.ts @@ -10,9 +10,6 @@ import { Route as rootRouteImport } from './routes/__root' 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' @@ -22,21 +19,6 @@ const IndexRoute = IndexRouteImport.update({ path: '/', getParentRoute: () => rootRouteImport, } as any) -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({ id: '/modules', path: '/modules', @@ -55,18 +37,12 @@ const SassMixinRoute = SassMixinRouteImport.update({ 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 @@ -74,36 +50,20 @@ 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: - '/' | '/alpha' | '/beta' | '/gamma' | '/modules' | '/quotes' | '/sass-mixin' + fullPaths: '/' | '/modules' | '/quotes' | '/sass-mixin' fileRoutesByTo: FileRoutesByTo - to: - '/' | '/alpha' | '/beta' | '/gamma' | '/modules' | '/quotes' | '/sass-mixin' - id: - | '__root__' - | '/' - | '/alpha' - | '/beta' - | '/gamma' - | '/modules' - | '/quotes' - | '/sass-mixin' + to: '/' | '/modules' | '/quotes' | '/sass-mixin' + id: '__root__' | '/' | '/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 @@ -118,27 +78,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof IndexRouteImport parentRoute: typeof rootRouteImport } - '/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': { id: '/modules' path: '/modules' @@ -165,9 +104,6 @@ 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 deleted file mode 100644 index e894cd758f..0000000000 --- a/e2e/react-start/css-modules/src/routes/alpha.tsx +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index 4f139ac41a..0000000000 --- a/e2e/react-start/css-modules/src/routes/beta.tsx +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index a8e036b85f..0000000000 --- a/e2e/react-start/css-modules/src/routes/gamma.tsx +++ /dev/null @@ -1,8 +0,0 @@ -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 deleted file mode 100644 index 12a606a8d3..0000000000 --- a/e2e/react-start/css-modules/src/styles/alpha.module.css +++ /dev/null @@ -1,4 +0,0 @@ -.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 deleted file mode 100644 index 719686a76b..0000000000 --- a/e2e/react-start/css-modules/src/styles/beta.module.css +++ /dev/null @@ -1,4 +0,0 @@ -.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 deleted file mode 100644 index d0325ac63e..0000000000 --- a/e2e/react-start/css-modules/src/utils/formatTitle.ts +++ /dev/null @@ -1,3 +0,0 @@ -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 7c0fce762a..e8879c0165 100644 --- a/e2e/react-start/css-modules/tests/setup/global.setup.ts +++ b/e2e/react-start/css-modules/tests/setup/global.setup.ts @@ -1,10 +1,20 @@ -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' +import { + e2eStartDummyServer, + getTestServerPort, + preOptimizeDevServer, + waitForServer, +} from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } 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 = Number(process.env.E2E_APP_PORT ?? 0) + const port = await getTestServerPort( + viteConfig ? `${packageJson.name}-${viteConfig}` : packageJson.name, + ) 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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/css-modules/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 deleted file mode 100644 index 9a9595f819..0000000000 --- a/e2e/react-start/css-modules/tests/shared-css.prod.spec.ts +++ /dev/null @@ -1,94 +0,0 @@ -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 c9c27f7f9a..9923ab3384 100644 --- a/e2e/react-start/css-modules/vite.config.ts +++ b/e2e/react-start/css-modules/vite.config.ts @@ -21,7 +21,6 @@ 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 b9bf393466..1884c5eb5a 100644 --- a/e2e/react-start/custom-basepath/express-server.ts +++ b/e2e/react-start/custom-basepath/express-server.ts @@ -1,6 +1,5 @@ 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' @@ -41,11 +40,7 @@ if (DEVELOPMENT) { }) } -const httpServer = app.listen(PORT, (error) => { - if (error) { - throw error - } - console.log( - `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, - ) +app.listen(PORT, (error) => { + if (error) throw error + console.log(`Server is running on http://localhost:${PORT}`) }) diff --git a/e2e/react-start/custom-basepath/package.json b/e2e/react-start/custom-basepath/package.json index e93949eea2..f665ba0598 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -29,7 +29,7 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "cross-env": "^10.0.0", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "tsx": "^4.20.3", "@typescript/native": "npm:typescript@^7.0.2", diff --git a/e2e/react-start/custom-basepath/playwright.config.ts b/e2e/react-start/custom-basepath/playwright.config.ts index e113ce64ad..5095425f47 100644 --- a/e2e/react-start/custom-basepath/playwright.config.ts +++ b/e2e/react-start/custom-basepath/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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}/custom/basepath` /** @@ -13,19 +18,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: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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/routes/api.users.ts b/e2e/react-start/custom-basepath/src/routes/api.users.ts index 6fc8cde830..9e055549ef 100644 --- a/e2e/react-start/custom-basepath/src/routes/api.users.ts +++ b/e2e/react-start/custom-basepath/src/routes/api.users.ts @@ -3,7 +3,11 @@ import axios from 'redaxios' import type { User } from '~/utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +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: { 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 81c071afb5..57682660fd 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,7 +2,11 @@ import axios from 'redaxios' import type { User } from '~/utils/users' import { createFileRoute } from '@tanstack/react-router' -const queryURL = 'https://jsonplaceholder.typicode.com' +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: { diff --git a/e2e/react-start/custom-basepath/src/utils/posts.tsx b/e2e/react-start/custom-basepath/src/utils/posts.tsx index d9b98a8c9c..4cc5dcc4c6 100644 --- a/e2e/react-start/custom-basepath/src/utils/posts.tsx +++ b/e2e/react-start/custom-basepath/src/utils/posts.tsx @@ -8,7 +8,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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) diff --git a/e2e/react-start/custom-basepath/src/utils/users.tsx b/e2e/react-start/custom-basepath/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/react-start/custom-basepath/src/utils/users.tsx +++ b/e2e/react-start/custom-basepath/src/utils/users.tsx @@ -3,3 +3,7 @@ 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-start/custom-basepath/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/custom-basepath/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 68537956b4..23784f2efc 100644 --- a/e2e/react-start/custom-server-rsbuild/express-server.ts +++ b/e2e/react-start/custom-server-rsbuild/express-server.ts @@ -1,6 +1,5 @@ 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' @@ -59,13 +58,9 @@ if (DEVELOPMENT) { }) const httpServer = app.listen(PORT, async (error) => { - if (error) { - throw error - } + if (error) throw error await devServer.afterListen() - console.log( - `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, - ) + console.log(`Server is running on http://localhost:${PORT}`) }) devServer.connectWebSocket({ server: httpServer }) } else { @@ -80,12 +75,8 @@ if (DEVELOPMENT) { next(error) } }) - const httpServer = app.listen(PORT, (error) => { - if (error) { - throw error - } - console.log( - `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, - ) + app.listen(PORT, (error) => { + if (error) throw error + console.log(`Server is running on http://localhost:${PORT}`) }) } diff --git a/e2e/react-start/custom-server-rsbuild/package.json b/e2e/react-start/custom-server-rsbuild/package.json index 1c5b3af393..865e424daa 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": "pnpm run test:e2e:dev && pnpm run test:e2e:prod" + "test:e2e": "rm -rf port*.txt && pnpm run test:e2e:dev && pnpm run test:e2e:prod" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -21,7 +21,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", "@tailwindcss/postcss": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", @@ -30,7 +30,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "cross-env": "^10.0.0", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "tsx": "^4.20.3", "@typescript/native": "npm:typescript@^7.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 f0542500fd..eb8b43f648 100644 --- a/e2e/react-start/custom-server-rsbuild/playwright.config.ts +++ b/e2e/react-start/custom-server-rsbuild/playwright.config.ts @@ -1,9 +1,11 @@ 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 = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(`${packageJson.name}-${mode}`) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -13,8 +15,8 @@ export default defineConfig({ use: { baseURL }, webServer: { command: isDev ? 'pnpm dev:e2e' : 'pnpm build && pnpm start', - wait: { stdout: /E2E app: http:\/\/localhost:(?\d+)/ }, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { PORT: String(PORT), diff --git a/e2e/react-start/deferred-hydration/package.json b/e2e/react-start/deferred-hydration/package.json index 5a33407435..fb8a99c8e3 100644 --- a/e2e/react-start/deferred-hydration/package.json +++ b/e2e/react-start/deferred-hydration/package.json @@ -26,14 +26,14 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@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": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" @@ -42,12 +42,6 @@ "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 d88c59fc9d..0125792d4b 100644 --- a/e2e/react-start/deferred-hydration/playwright.config.ts +++ b/e2e/react-start/deferred-hydration/playwright.config.ts @@ -1,9 +1,12 @@ +import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } 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' @@ -11,7 +14,11 @@ const startCommand = `pnpm exec srvx --prod --dir=. -s ${distDir}/client --entry const devCommand = toolchain === 'rsbuild' ? 'pnpm dev:rsbuild' : 'pnpm dev:vite' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +if (process.env.TEST_WORKER_INDEX === undefined) { + fs.rmSync(`port-${e2ePortKey}.txt`, { force: true }) +} + +const PORT = await getTestServerPort(e2ePortKey) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -19,11 +26,12 @@ 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, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { E2E_DIST_DIR: distDir, @@ -32,6 +40,7 @@ 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/tests/setup/global.setup.ts b/e2e/react-start/deferred-hydration/tests/setup/global.setup.ts index 704bbef3e2..1117664a14 100644 --- a/e2e/react-start/deferred-hydration/tests/setup/global.setup.ts +++ b/e2e/react-start/deferred-hydration/tests/setup/global.setup.ts @@ -1,11 +1,24 @@ -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' +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}` +} export default async function setup() { - if (process.env.MODE !== 'dev') { - return - } + if (process.env.MODE !== 'dev') return - const port = Number(process.env.E2E_APP_PORT ?? 0) + const e2ePortKey = getE2EPortKey() + + await e2eStartDummyServer(e2ePortKey) + + const port = await getTestServerPort(e2ePortKey) 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 new file mode 100644 index 0000000000..df79f50e82 --- /dev/null +++ b/e2e/react-start/deferred-hydration/tests/setup/global.teardown.ts @@ -0,0 +1,13 @@ +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 a5300e836e..c9c14943d4 100644 --- a/e2e/react-start/dev-ssr-styles/package.json +++ b/e2e/react-start/dev-ssr-styles/package.json @@ -22,9 +22,13 @@ "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": "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" + "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" }, "dependencies": { "@tanstack/react-router": "workspace:*", @@ -40,8 +44,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "nitro": "^3.0.260903-beta", - "srvx": "^1.0.0", + "nitro": "^3.0.260311-beta", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", diff --git a/e2e/react-start/dev-ssr-styles/playwright.config.ts b/e2e/react-start/dev-ssr-styles/playwright.config.ts index 71cc8ed2da..a1fdd7c3ef 100644 --- a/e2e/react-start/dev-ssr-styles/playwright.config.ts +++ b/e2e/react-start/dev-ssr-styles/playwright.config.ts @@ -1,5 +1,6 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } import { ssrStylesMode, useNitro, viteBundledDev } from './env' const mode = process.env.MODE ?? 'prod' @@ -8,13 +9,24 @@ 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 = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(getPortKey()) 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') { @@ -32,6 +44,7 @@ export default defineConfig({ reporter: [['line']], globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', use: { baseURL, @@ -39,8 +52,8 @@ export default defineConfig({ webServer: { command: isDev ? getDevCommand() : `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, 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 deleted file mode 100644 index 49d2f96c39..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/components/CodeSplitStyledBox.tsx +++ /dev/null @@ -1,9 +0,0 @@ -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 96c0a37142..dceedffdc1 100644 --- a/e2e/react-start/dev-ssr-styles/src/routeTree.gen.ts +++ b/e2e/react-start/dev-ssr-styles/src/routeTree.gen.ts @@ -10,63 +10,33 @@ 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: '/' | '/css-import-order' | '/inline-css' | '/module-state' + fullPaths: '/' fileRoutesByTo: FileRoutesByTo - to: '/' | '/css-import-order' | '/inline-css' | '/module-state' - id: '__root__' | '/' | '/css-import-order' | '/inline-css' | '/module-state' + to: '/' + id: '__root__' | '/' fileRoutesById: FileRoutesById } export interface RootRouteChildren { IndexRoute: typeof IndexRoute - CssImportOrderRoute: typeof CssImportOrderRoute - InlineCssRoute: typeof InlineCssRoute - ModuleStateRoute: typeof ModuleStateRoute } declare module '@tanstack/react-router' { @@ -78,35 +48,11 @@ 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 deleted file mode 100644 index 345254bb8c..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/routes/css-import-order.tsx +++ /dev/null @@ -1,17 +0,0 @@ -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 62fb237750..f5fadf464d 100644 --- a/e2e/react-start/dev-ssr-styles/src/routes/index.tsx +++ b/e2e/react-start/dev-ssr-styles/src/routes/index.tsx @@ -1,5 +1,4 @@ import { createFileRoute } from '@tanstack/react-router' -import { CodeSplitStyledBox } from '../components/CodeSplitStyledBox' export const Route = createFileRoute('/')({ component: Home, @@ -9,7 +8,9 @@ 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 deleted file mode 100644 index ffc59128e0..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/routes/inline-css.tsx +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index 546217efc3..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/routes/module-state.ts +++ /dev/null @@ -1,11 +0,0 @@ -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 4285da0c86..06b48f8a7c 100644 --- a/e2e/react-start/dev-ssr-styles/src/styles/app.css +++ b/e2e/react-start/dev-ssr-styles/src/styles/app.css @@ -5,10 +5,9 @@ body { background-color: #f0f4f8; } -@layer utilities { - .inline-css-layout { - margin: 12px; - padding: 24px; - border: 3px solid black; - } +.styled-box { + background-color: #3b82f6; + color: white; + padding: 24px; + border-radius: 12px; } 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 deleted file mode 100644 index d6a50211ee..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/styles/code-split-route.module.css +++ /dev/null @@ -1,7 +0,0 @@ -.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 deleted file mode 100644 index 4f73ddab9c..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/styles/css-import-base.css +++ /dev/null @@ -1,5 +0,0 @@ -.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 deleted file mode 100644 index afcb4797d9..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/styles/css-import-order.css +++ /dev/null @@ -1,7 +0,0 @@ -@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 deleted file mode 100644 index 13810d6c98..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/styles/embedded-preflight.css +++ /dev/null @@ -1,6 +0,0 @@ -* { - --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 deleted file mode 100644 index 171ed5e174..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/styles/embedded-theme.css +++ /dev/null @@ -1,3 +0,0 @@ -: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 deleted file mode 100644 index 01f81c3b86..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/styles/embedded-utilities.css +++ /dev/null @@ -1,3 +0,0 @@ -.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 deleted file mode 100644 index 7b6b68c48d..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/styles/embedded.css +++ /dev/null @@ -1,3 +0,0 @@ -@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 deleted file mode 100644 index 7916b3ef16..0000000000 --- a/e2e/react-start/dev-ssr-styles/src/styles/ssr-background.svg +++ /dev/null @@ -1 +0,0 @@ - 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 f5b72a1bca..cb1ba0b29b 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 { createHmrFileEditor, test } from '@tanstack/router-e2e-utils' +import { test } from '@tanstack/router-e2e-utils' import { ssrStylesMode } from '../env' // Whitelist errors that can occur in CI: @@ -14,60 +14,14 @@ 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 }) @@ -98,9 +52,7 @@ test.describe(`dev.ssrStyles (mode=${ssrStylesMode})`, () => { expect(href).toMatch(/^\/@tanstack-start\/styles\.css/) }) - test('CSS from a code-split route component is applied during SSR', async ({ - page, - }) => { + test('CSS is applied on initial page load (SSR)', async ({ page }) => { await page.goto('/') const element = page.getByTestId('styled-box') @@ -112,81 +64,6 @@ 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 deleted file mode 100644 index c564a9977a..0000000000 --- a/e2e/react-start/dev-ssr-styles/tests/inline-css.spec.ts +++ /dev/null @@ -1,35 +0,0 @@ -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 43fad46254..2bfd33163d 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,45 +1,39 @@ -import { chromium, expect } from '@playwright/test' -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' -import { ssrStylesMode } from '../../env' +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 +} export default async function setup() { - if (process.env.MODE !== 'dev') { - return - } + const portKey = getPortKey() - const port = Number(process.env.E2E_APP_PORT ?? 0) + await e2eStartDummyServer(portKey) + + if (process.env.MODE !== 'dev') return + + const port = await getTestServerPort(portKey) const baseURL = `http://localhost:${port}` await waitForServer(baseURL) - - // 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' }) + 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 new file mode 100644 index 0000000000..0e44fca325 --- /dev/null +++ b/e2e/react-start/dev-ssr-styles/tests/setup/global.teardown.ts @@ -0,0 +1,21 @@ +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 df5ea34504..555137b543 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: { bundledDev: viteBundledDev }, + experimental: viteBundledDev ? { bundledDev: true } : undefined, server: { port: 3000, }, diff --git a/e2e/react-start/early-hints/package.json b/e2e/react-start/early-hints/package.json index 1615b99430..2945148950 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -27,20 +27,10 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "node-forge": "^1.3.1", - "srvx": "^1.0.0", + "srvx": "0.11.15", "tsx": "4.20.3", "@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 b3606d5586..a2435bcf7b 100644 --- a/e2e/react-start/early-hints/playwright.config.ts +++ b/e2e/react-start/early-hints/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `https://localhost:${PORT}` export default defineConfig({ @@ -16,8 +17,8 @@ export default defineConfig({ webServer: { command: `pnpm build && pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', ignoreHTTPSErrors: true, env: { 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 6d2d31d836..df0984079e 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,5 +1,7 @@ -import { connect } from 'node:http2' 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 type { IncomingHttpHeaders } from 'node:http2' type Http2Response = { @@ -46,14 +48,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 = Number(process.env.E2E_APP_PORT ?? 0) + const PORT = await getTestServerPort(packageJson.name) baseURL = `https://localhost:${PORT}` }) @@ -103,9 +105,7 @@ 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;\s*fetchpriority=low/, - ) + expect(link).toMatch(/<[^>]+>;\s*rel=modulepreload;\s*as=script/) }) 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; fetchpriority=low') + expect(link).toContain('rel=modulepreload; as=script') expect(link).toContain('; rel=preconnect') }) diff --git a/e2e/react-start/flamegraph-bench/package.json b/e2e/react-start/flamegraph-bench/package.json index 72410b13e1..eb72de699a 100644 --- a/e2e/react-start/flamegraph-bench/package.json +++ b/e2e/react-start/flamegraph-bench/package.json @@ -14,12 +14,12 @@ "@tanstack/react-start": "workspace:*", "react": "^19.0.0", "react-dom": "^19.0.0", - "srvx": "^1.0.0" + "srvx": "^0.11.9" }, "devDependencies": { "@platformatic/flame": "latest", "@vitejs/plugin-react": "^6.0.1", - "nitro": "^3.0.260903-beta", + "nitro": "^3.0.260311-beta", "autocannon": "^8.0.0", "concurrently": "9.2.1", "@typescript/native": "npm:typescript@^7.0.2", diff --git a/e2e/react-start/hmr/package.json b/e2e/react-start/hmr/package.json index 76a5d86b1f..7a6dc23f76 100644 --- a/e2e/react-start/hmr/package.json +++ b/e2e/react-start/hmr/package.json @@ -21,7 +21,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", "@tailwindcss/postcss": "^4.2.2", "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/react-start/hmr/playwright.config.ts b/e2e/react-start/hmr/playwright.config.ts index 5840ec157a..c159aad328 100644 --- a/e2e/react-start/hmr/playwright.config.ts +++ b/e2e/react-start/hmr/playwright.config.ts @@ -1,11 +1,13 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } 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 = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(e2ePortKey) const baseURL = `http://localhost:${PORT}` const devCommand = toolchain === 'rsbuild' ? 'pnpm dev:rsbuild' : 'pnpm dev:vite' @@ -16,6 +18,7 @@ export default defineConfig({ reporter: [['line']], globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', use: { baseURL, @@ -23,14 +26,15 @@ export default defineConfig({ webServer: { command: `${devCommand} --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, 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/tests/app.spec.ts b/e2e/react-start/hmr/tests/app.spec.ts index 645c9b06f3..fe6dd99389 100644 --- a/e2e/react-start/hmr/tests/app.spec.ts +++ b/e2e/react-start/hmr/tests/app.spec.ts @@ -607,18 +607,8 @@ 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') @@ -932,7 +922,6 @@ 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( diff --git a/e2e/react-start/hmr/tests/setup/global.setup.ts b/e2e/react-start/hmr/tests/setup/global.setup.ts index 32207ab79f..fb9aad22ae 100644 --- a/e2e/react-start/hmr/tests/setup/global.setup.ts +++ b/e2e/react-start/hmr/tests/setup/global.setup.ts @@ -1,7 +1,22 @@ -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' +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}` +} export default async function setup() { - const port = Number(process.env.E2E_APP_PORT ?? 0) + const e2ePortKey = getE2EPortKey() + + await e2eStartDummyServer(e2ePortKey) + + const port = await getTestServerPort(e2ePortKey) 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 new file mode 100644 index 0000000000..e17856dd82 --- /dev/null +++ b/e2e/react-start/hmr/tests/setup/global.teardown.ts @@ -0,0 +1,11 @@ +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 ca65ead76d..5b525891a6 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -30,23 +30,5 @@ "@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 972522350e..38690f09d8 100644 --- a/e2e/react-start/i18n-paraglide/playwright.config.ts +++ b/e2e/react-start/i18n-paraglide/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/import-protection-custom-config/package.json b/e2e/react-start/import-protection-custom-config/package.json index c088eff106..25ff3f2738 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": "playwright test --project=chromium", - "test:e2e:errorMode": "BEHAVIOR=error playwright test --project=chromium", + "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": "pnpm run test:e2e:mockMode && pnpm run test:e2e:errorMode" }, "dependencies": { @@ -25,23 +25,9 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@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 ab90f2911f..31a55ba3bc 100644 --- a/e2e/react-start/import-protection-custom-config/playwright.config.ts +++ b/e2e/react-start/import-protection-custom-config/playwright.config.ts @@ -1,8 +1,9 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' import { isErrorMode } from './tests/utils/isErrorMode' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` console.log('running in error mode:', isErrorMode.toString()) @@ -26,8 +27,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`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', cwd: import.meta.dirname, }, 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 5032988d0c..3e666ca1df 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 { stripVTControlCharacters } from 'node:util' -import { appServerReadyPattern } from '@tanstack/router-e2e-utils' -import { chromium, expect } from '@playwright/test' +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 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,7 +84,8 @@ function captureBuild(cwd: string): void { } async function captureDevErrors(cwd: string): Promise { - const port = 0 + const port = await getTestServerPort(`${packageJson.name}_error_dev`) + const baseURL = `http://localhost:${port}` const logChunks: Array = [] const child = spawn('pnpm', ['exec', 'vite', 'dev', '--port', String(port)], { @@ -98,23 +99,10 @@ 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 89c8bb2b9a..c5187fe074 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 { stripVTControlCharacters } from 'node:util' -import { chromium, expect } from '@playwright/test' -import { appServerReadyPattern } from '@tanstack/router-e2e-utils' +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 { extractViolationsFromLog } from './violations.utils' import type { FullConfig } from '@playwright/test' @@ -12,6 +12,7 @@ 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}`) @@ -118,6 +119,7 @@ async function runDevPass( cwd: string, port: number, ): Promise> { + const baseURL = `http://localhost:${port}` const logChunks: Array = [] const child = startDevServer(cwd, port) @@ -125,19 +127,6 @@ 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() @@ -157,7 +146,7 @@ async function runDevPass( } async function captureDevViolations(cwd: string): Promise { - const port = 0 + const port = await getTestServerPort(`${packageJson.name}_dev`) 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 ad06ba41ea..5459b84437 100644 --- a/e2e/react-start/import-protection/package.json +++ b/e2e/react-start/import-protection/package.json @@ -22,14 +22,14 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@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": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" diff --git a/e2e/react-start/import-protection/playwright.config.ts b/e2e/react-start/import-protection/playwright.config.ts index 6a3df630c3..778e865125 100644 --- a/e2e/react-start/import-protection/playwright.config.ts +++ b/e2e/react-start/import-protection/playwright.config.ts @@ -1,12 +1,16 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' import { isErrorMode } from './tests/utils/isErrorMode' import { getViolationArtifactName } from './tests/violations.utils' +import packageJson from './package.json' with { type: 'json' } +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 = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(e2ePortKey) const baseURL = `http://localhost:${PORT}` const violationArtifacts = [ getViolationArtifactName('build'), @@ -38,14 +42,15 @@ export default defineConfig({ : { webServer: { command: `rm -f webserver-dev.log ${violationArtifacts} && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, 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 ef8544dc3c..c05ed1a7e3 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, useHydrated } from '@tanstack/react-router' +import { createFileRoute } 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,12 +25,10 @@ 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/violations/cross-boundary-safe/session-util.ts b/e2e/react-start/import-protection/src/violations/cross-boundary-safe/session-util.ts index d74bc6430b..ab44237539 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 -// `getCookie` from `@tanstack/react-start/server`. +// `useSession` from `@tanstack/react-start/server`. export function getSessionData() { const req = getRequest() return { method: req.method } 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 e562128eea..c844d59e73 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 { stripVTControlCharacters } from 'node:util' -import { appServerReadyPattern } from '@tanstack/router-e2e-utils' -import { chromium, expect } from '@playwright/test' +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 type { FullConfig } from '@playwright/test' /** @@ -20,10 +20,14 @@ 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}`) @@ -118,7 +122,8 @@ async function captureDev(cwd: string): Promise { if (fs.existsSync(p)) fs.unlinkSync(p) } - const port = 0 + const port = await getTestServerPort(`${e2ePortKey}-error-dev`) + const baseURL = `http://localhost:${port}` const logFile = path.resolve(cwd, 'error-dev.log') const out = fs.createWriteStream(logFile) @@ -140,28 +145,10 @@ async function captureDev(cwd: string): Promise { stdio: ['ignore', 'pipe', 'pipe'], }) - const logChunks: Array = [] - const record = (data: Buffer) => { - logChunks.push(data.toString()) - out.write(data) - } - child.stdout.on('data', record) - child.stderr.on('data', record) + child.stdout?.on('data', (d: Buffer) => out.write(d)) + child.stderr?.on('data', (d: Buffer) => out.write(d)) 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/violations.setup.ts b/e2e/react-start/import-protection/tests/violations.setup.ts index d0f4f70d03..2f863b398e 100644 --- a/e2e/react-start/import-protection/tests/violations.setup.ts +++ b/e2e/react-start/import-protection/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 { stripVTControlCharacters } from 'node:util' -import { chromium, expect } from '@playwright/test' -import { appServerReadyPattern } from '@tanstack/router-e2e-utils' +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 { extractViolationsFromLog, @@ -12,11 +12,16 @@ import { 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}`) @@ -172,20 +177,6 @@ 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 @@ -223,6 +214,7 @@ async function runDevPass( cwd: string, port: number, ): Promise> { + const baseURL = `http://localhost:${port}` const logChunks: Array = [] const child = startDevServer(cwd, port) @@ -230,19 +222,6 @@ 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() @@ -268,7 +247,10 @@ async function runDevPass( * modules are pre-transformed so resolveId/transform paths differ. */ async function captureDevViolations(cwd: string): Promise { - const coldViolations = await runDevPass(cwd, 0) + const coldViolations = await runDevPass( + cwd, + await getTestServerPort(`${e2ePortKey}-violations-cold`), + ) fs.writeFileSync( path.resolve(cwd, getViolationArtifactName('dev')), @@ -280,7 +262,10 @@ async function captureDevViolations(cwd: string): Promise { ) // Warm pass: the .vite cache from the cold run is still on disk. - const warmViolations = await runDevPass(cwd, 0) + const warmViolations = await runDevPass( + cwd, + await getTestServerPort(`${e2ePortKey}-violations-warm`), + ) fs.writeFileSync( path.resolve(cwd, getViolationArtifactName('dev.warm')), diff --git a/e2e/react-start/issue-8049/package.json b/e2e/react-start/issue-8049/package.json index be848d434c..d76b23fc3b 100644 --- a/e2e/react-start/issue-8049/package.json +++ b/e2e/react-start/issue-8049/package.json @@ -6,7 +6,7 @@ "build": "vite build && tsc --noEmit", "dev": "vite dev --port 3000", "dev:e2e": "vite dev", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", diff --git a/e2e/react-start/issue-8049/playwright.config.ts b/e2e/react-start/issue-8049/playwright.config.ts index 46bfbe552e..04fa904ba6 100644 --- a/e2e/react-start/issue-8049/playwright.config.ts +++ b/e2e/react-start/issue-8049/playwright.config.ts @@ -1,8 +1,10 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } const PORT = - Number(process.env.VITE_SERVER_PORT) || Number(process.env.E2E_APP_PORT ?? 0) + Number(process.env.VITE_SERVER_PORT) || + (await getTestServerPort(packageJson.name)) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -12,8 +14,8 @@ export default defineConfig({ use: { baseURL }, webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, projects: [ diff --git a/e2e/react-start/query-integration/package.json b/e2e/react-start/query-integration/package.json index 694289ccc2..4ad1839537 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-query": "^5.90.0", diff --git a/e2e/react-start/query-integration/playwright.config.ts b/e2e/react-start/query-integration/playwright.config.ts index 82678ac00b..4d86a1dbe7 100644 --- a/e2e/react-start/query-integration/playwright.config.ts +++ b/e2e/react-start/query-integration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { derivePort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await derivePort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/response-reconciliation/.gitignore b/e2e/react-start/response-reconciliation/.gitignore deleted file mode 100644 index 16187ac1de..0000000000 --- a/e2e/react-start/response-reconciliation/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -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 deleted file mode 100644 index 40a96e8819..0000000000 --- a/e2e/react-start/response-reconciliation/.prettierignore +++ /dev/null @@ -1,4 +0,0 @@ -**/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 deleted file mode 100644 index 7ba0224962..0000000000 --- a/e2e/react-start/response-reconciliation/package.json +++ /dev/null @@ -1,84 +0,0 @@ -{ - "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 deleted file mode 100644 index d4c9c58f43..0000000000 --- a/e2e/react-start/response-reconciliation/playwright.config.ts +++ /dev/null @@ -1,37 +0,0 @@ -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 deleted file mode 100644 index 38f44ef9fb..0000000000 --- a/e2e/react-start/response-reconciliation/rsbuild.config.ts +++ /dev/null @@ -1,20 +0,0 @@ -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 deleted file mode 100644 index 324a462bec..0000000000 --- a/e2e/react-start/response-reconciliation/server.js +++ /dev/null @@ -1,62 +0,0 @@ -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 deleted file mode 100644 index f3d691814f..0000000000 --- a/e2e/react-start/response-reconciliation/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,20 +0,0 @@ -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 deleted file mode 100644 index 0b720f0e37..0000000000 --- a/e2e/react-start/response-reconciliation/src/components/NotFound.tsx +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index db9733d5e6..0000000000 --- a/e2e/react-start/response-reconciliation/src/response-wrapper.ts +++ /dev/null @@ -1,33 +0,0 @@ -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 deleted file mode 100644 index 3dbb6301c3..0000000000 --- a/e2e/react-start/response-reconciliation/src/routeTree.gen.ts +++ /dev/null @@ -1,625 +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 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 deleted file mode 100644 index c5c2209e5a..0000000000 --- a/e2e/react-start/response-reconciliation/src/router.tsx +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index a562991887..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/__root.tsx +++ /dev/null @@ -1,57 +0,0 @@ -/// -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 deleted file mode 100644 index 54082c10f6..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/-response.ts +++ /dev/null @@ -1,85 +0,0 @@ -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 deleted file mode 100644 index 1ccde76367..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/-tracked-streams.ts +++ /dev/null @@ -1,2 +0,0 @@ -// 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 deleted file mode 100644 index 0018376035..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/-upstream.ts +++ /dev/null @@ -1,14 +0,0 @@ -// 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 deleted file mode 100644 index 62f706a9f1..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/base.ts +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index db7ded6c54..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/bulk-headers.ts +++ /dev/null @@ -1,19 +0,0 @@ -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 deleted file mode 100644 index fd3b88c172..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/clear-returned-headers.ts +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index 96823887e5..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/direct-mutation-visible.ts +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 3ea2bc6d75..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/explicit-set-cookie-header.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index baeab15780..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/framing-error.ts +++ /dev/null @@ -1,16 +0,0 @@ -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 deleted file mode 100644 index b597882ff6..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/get-response-header-helper.ts +++ /dev/null @@ -1,17 +0,0 @@ -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 deleted file mode 100644 index 168d38bad4..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/get-response-headers-helper.ts +++ /dev/null @@ -1,20 +0,0 @@ -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 deleted file mode 100644 index eebf7a167e..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/multiple-cookies.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 deleted file mode 100644 index d11056e7a8..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/null-body-status.ts +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 7b42955052..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/readonly-after-next.ts +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 5b0072f35a..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/redirect-with-cookies.ts +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index 96f82bf98d..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/remove-returned-header.ts +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index 890280483d..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/replace-after-direct-mutation.ts +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 97df27d915..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/replace-explicit-set-cookie.ts +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index 7d3650147f..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/route-after-next.ts +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index b52c7642af..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/route-before-next.ts +++ /dev/null @@ -1,11 +0,0 @@ -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 deleted file mode 100644 index 7ac086d652..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/same-boundary-conflict.ts +++ /dev/null @@ -1,21 +0,0 @@ -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 deleted file mode 100644 index 43fd72ec07..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/status-contracts.ts +++ /dev/null @@ -1,42 +0,0 @@ -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 deleted file mode 100644 index 9d93d75b61..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/throw-after-status.ts +++ /dev/null @@ -1,26 +0,0 @@ -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 deleted file mode 100644 index 1aaffd8d36..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/tracked-stream-status.ts +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index 640074a035..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/tracked-stream.ts +++ /dev/null @@ -1,23 +0,0 @@ -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 deleted file mode 100644 index f433778fd8..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/api/two-returned-responses.ts +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index ab938397e9..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/index.tsx +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index 580309b31e..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/server-functions.tsx +++ /dev/null @@ -1,285 +0,0 @@ -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 deleted file mode 100644 index c0cb69c8ec..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/ssr.tsx +++ /dev/null @@ -1,29 +0,0 @@ -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 deleted file mode 100644 index 8d6a6227cd..0000000000 --- a/e2e/react-start/response-reconciliation/src/routes/streamed.tsx +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index cbee8ad31a..0000000000 --- a/e2e/react-start/response-reconciliation/src/server-entry.ts +++ /dev/null @@ -1,84 +0,0 @@ -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 deleted file mode 100644 index 2ac158b799..0000000000 --- a/e2e/react-start/response-reconciliation/src/start.ts +++ /dev/null @@ -1,170 +0,0 @@ -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 deleted file mode 100644 index a38fb439a6..0000000000 --- a/e2e/react-start/response-reconciliation/src/styles/app.css +++ /dev/null @@ -1,12 +0,0 @@ -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 deleted file mode 100644 index 728b0782c5..0000000000 --- a/e2e/react-start/response-reconciliation/tests/response-reconciliation.spec.ts +++ /dev/null @@ -1,1038 +0,0 @@ -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 deleted file mode 100644 index 3824b148e1..0000000000 --- a/e2e/react-start/response-reconciliation/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "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 deleted file mode 100644 index 355e12a2f7..0000000000 --- a/e2e/react-start/response-reconciliation/vite.config.ts +++ /dev/null @@ -1,19 +0,0 @@ -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/package.json b/e2e/react-start/root-document-hydration/package.json index 9dcfcb6fbc..d69ddfc0bf 100644 --- a/e2e/react-start/root-document-hydration/package.json +++ b/e2e/react-start/root-document-hydration/package.json @@ -10,7 +10,7 @@ "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" + "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:dev && pnpm run test:e2e:prod" }, "dependencies": { "@tanstack/react-router": "workspace:*", @@ -25,7 +25,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" diff --git a/e2e/react-start/root-document-hydration/playwright.config.ts b/e2e/react-start/root-document-hydration/playwright.config.ts index 13dda4e328..18abea0ab1 100644 --- a/e2e/react-start/root-document-hydration/playwright.config.ts +++ b/e2e/react-start/root-document-hydration/playwright.config.ts @@ -1,8 +1,9 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } const isDev = process.env.MODE === 'dev' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -15,11 +16,9 @@ export default defineConfig({ }, webServer: { - command: isDev - ? 'pnpm dev:e2e --port 0' - : `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: isDev ? 'pnpm dev:e2e' : `pnpm build && PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { PORT: String(PORT), diff --git a/e2e/react-start/rsbuild/package.json b/e2e/react-start/rsbuild/package.json index d03ef22542..d0b7566489 100644 --- a/e2e/react-start/rsbuild/package.json +++ b/e2e/react-start/rsbuild/package.json @@ -8,7 +8,7 @@ "dev:e2e": "rsbuild dev --port $PORT", "build": "rsbuild build && tsc --noEmit", "start": "node server.js", - "test:e2e-full": "pnpm build && playwright test --project=chromium" + "test:e2e-full": "pnpm build && sh -c 'rm -f \"port-${E2E_PORT_KEY:-$npm_package_name}.txt\" \"port-${E2E_PORT_KEY:-$npm_package_name}-syntax-error-overlay.txt\"' && playwright test --project=chromium" }, "nx": { "metadata": { @@ -28,13 +28,13 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@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", - "srvx": "^1.0.0", + "srvx": "^0.10.0", "typescript": "^5.7.2" } } diff --git a/e2e/react-start/rsbuild/playwright.config.ts b/e2e/react-start/rsbuild/playwright.config.ts index e5c9004335..6e8f176361 100644 --- a/e2e/react-start/rsbuild/playwright.config.ts +++ b/e2e/react-start/rsbuild/playwright.config.ts @@ -1,4 +1,17 @@ +import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' +import packageJson from './package.json' with { type: 'json' } + +const e2ePortKey = process.env.E2E_PORT_KEY ?? packageJson.name + +if (process.env.TEST_WORKER_INDEX === undefined) { + for (const portFile of [ + `port-${e2ePortKey}.txt`, + `port-${e2ePortKey}-syntax-error-overlay.txt`, + ]) { + fs.rmSync(portFile, { force: true }) + } +} export default defineConfig({ testDir: './tests', diff --git a/e2e/react-start/rsbuild/tests/error-overlay.spec.ts b/e2e/react-start/rsbuild/tests/error-overlay.spec.ts index d90647314a..5d6497f740 100644 --- a/e2e/react-start/rsbuild/tests/error-overlay.spec.ts +++ b/e2e/react-start/rsbuild/tests/error-overlay.spec.ts @@ -1,11 +1,12 @@ -import { spawn } from 'node:child_process' import fs from 'node:fs' import path from 'node:path' -import { stripVTControlCharacters } from 'node:util' -import { appServerReadyPattern, test } from '@tanstack/router-e2e-utils' +import { spawn } from 'node:child_process' import { expect } from '@playwright/test' +import { getTestServerPort, test } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } import type { Page } from '@playwright/test' +const e2ePortKey = process.env.E2E_PORT_KEY ?? packageJson.name const fixtureRoot = path.resolve(import.meta.dirname, '..') const workspaceRoot = path.resolve(import.meta.dirname, '../../../..') const errorOverlaySelector = 'rsbuild-error-overlay' @@ -14,7 +15,7 @@ const syntaxErrorRoutePatch = '\nexport const broken = ;\n' const devServerTimeout = 30_000 class DevServer { - url = '' + readonly url: string private stopPromise: Promise | null = null private startupError: Error | null = null private readonly startupErrorPromise: Promise @@ -23,16 +24,7 @@ class DevServer { readonly port: number, private readonly childProcess: ReturnType, ) { - let log = '' - const captureAddress = (data: Buffer) => { - log += data.toString() - const match = appServerReadyPattern.exec(stripVTControlCharacters(log)) - if (match?.groups?.E2E_APP_PORT) { - this.url = `http://localhost:${match.groups.E2E_APP_PORT}` - } - } - this.childProcess.stdout?.on('data', captureAddress) - this.childProcess.stderr?.on('data', captureAddress) + this.url = `http://localhost:${port}` this.startupErrorPromise = new Promise((_, reject) => { this.childProcess.once('error', (error) => { this.startupError = error @@ -53,7 +45,7 @@ class DevServer { VITE_SERVER_PORT: String(port), VITE_NODE_ENV: 'test', }, - stdio: ['ignore', 'pipe', 'pipe'], + stdio: 'ignore', }), ) @@ -359,7 +351,7 @@ test('shows a module syntax error through the error overlay', async ({ }) => { const homeRouteFile = path.resolve(fixtureRoot, 'src/routes/index.tsx') const originalSource = await fs.promises.readFile(homeRouteFile, 'utf-8') - const port = 0 + const port = await getTestServerPort(`${e2ePortKey}-syntax-error-overlay`) await using devServer = await DevServer.start(port) try { diff --git a/e2e/react-start/rsc-deferred-hydration/package.json b/e2e/react-start/rsc-deferred-hydration/package.json index 06317e59d0..434cabb24b 100644 --- a/e2e/react-start/rsc-deferred-hydration/package.json +++ b/e2e/react-start/rsc-deferred-hydration/package.json @@ -22,14 +22,6 @@ "shards": 1 } ] - }, - "targets": { - "test:e2e--vite-ssr": { - "outputs": [ - "...", - "{projectRoot}/dist-vite-ssr" - ] - } } }, "dependencies": { @@ -45,8 +37,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "@vitejs/plugin-rsc": "^0.5.39", - "srvx": "^1.0.0", + "@vitejs/plugin-rsc": "^0.5.30", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" diff --git a/e2e/react-start/rsc-deferred-hydration/playwright.config.ts b/e2e/react-start/rsc-deferred-hydration/playwright.config.ts index f3a22f1fff..10f41cd911 100644 --- a/e2e/react-start/rsc-deferred-hydration/playwright.config.ts +++ b/e2e/react-start/rsc-deferred-hydration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` const mode = process.env.MODE ?? 'prod' const isDev = mode === 'dev' @@ -11,11 +12,12 @@ export default defineConfig({ workers: 1, reporter: [['line']], globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', use: { baseURL }, webServer: { - command: isDev ? 'pnpm dev:e2e --port 0' : 'pnpm build && pnpm start', - wait: appServerReady, - reuseExistingServer: false, + command: isDev ? 'pnpm dev:e2e' : 'pnpm build && pnpm start', + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { VITE_NODE_ENV: 'test', diff --git a/e2e/react-start/rsc-deferred-hydration/tests/setup/global.setup.ts b/e2e/react-start/rsc-deferred-hydration/tests/setup/global.setup.ts index 40acaec113..3d1579ee87 100644 --- a/e2e/react-start/rsc-deferred-hydration/tests/setup/global.setup.ts +++ b/e2e/react-start/rsc-deferred-hydration/tests/setup/global.setup.ts @@ -1,9 +1,17 @@ -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' +import { + e2eStartDummyServer, + getTestServerPort, + preOptimizeDevServer, + waitForServer, +} from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } export default async function setup() { + await e2eStartDummyServer(packageJson.name) + if (process.env.MODE !== 'dev') return - const port = Number(process.env.E2E_APP_PORT ?? 0) + const port = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${port}` await waitForServer(baseURL) diff --git a/e2e/react-start/rsc-deferred-hydration/tests/setup/global.teardown.ts b/e2e/react-start/rsc-deferred-hydration/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/rsc-deferred-hydration/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/rsc-query/package.json b/e2e/react-start/rsc-query/package.json index 68a99cd432..24c7b488f6 100644 --- a/e2e/react-start/rsc-query/package.json +++ b/e2e/react-start/rsc-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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-query": "^5.90.0", @@ -28,8 +28,8 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "@vitejs/plugin-rsc": "^0.5.39", - "srvx": "^1.0.0", + "@vitejs/plugin-rsc": "^0.5.30", + "srvx": "^0.10.0", "typescript": "^5.7.2", "vite": "^8.0.14" } diff --git a/e2e/react-start/rsc-query/playwright.config.ts b/e2e/react-start/rsc-query/playwright.config.ts index 235a59f889..2cf7c1fe9b 100644 --- a/e2e/react-start/rsc-query/playwright.config.ts +++ b/e2e/react-start/rsc-query/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -9,15 +10,18 @@ export default defineConfig({ workers: 1, reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { baseURL, }, webServer: { // RSC production builds are not yet supported, use dev mode - command: `pnpm dev:e2e --port 0`, - wait: appServerReady, - reuseExistingServer: false, + command: `pnpm dev:e2e`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { VITE_NODE_ENV: 'test', diff --git a/e2e/react-start/rsc-query/tests/setup/global.setup.ts b/e2e/react-start/rsc-query/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-start/rsc-query/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/rsc-query/tests/setup/global.teardown.ts b/e2e/react-start/rsc-query/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/rsc-query/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/rsc-rsbuild/package.json b/e2e/react-start/rsc-rsbuild/package.json index 067394fc08..e3800f291a 100644 --- a/e2e/react-start/rsc-rsbuild/package.json +++ b/e2e/react-start/rsc-rsbuild/package.json @@ -8,7 +8,7 @@ "dev:e2e": "rsbuild dev --port $PORT", "build": "rsbuild build && tsc --noEmit", "start": "node server.js", - "test:e2e-full": "pnpm build && playwright test --project=chromium" + "test:e2e-full": "pnpm build && sh -c 'rm -f \"port-${E2E_PORT_KEY:-$npm_package_name}.txt\" \"port-${E2E_PORT_KEY:-$npm_package_name}-external.txt\"' && playwright test --project=chromium" }, "nx": { "metadata": { @@ -28,13 +28,13 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@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", - "srvx": "^1.0.0", + "srvx": "^0.10.0", "typescript": "^5.7.2" } } diff --git a/e2e/react-start/rsc-rsbuild/playwright.config.ts b/e2e/react-start/rsc-rsbuild/playwright.config.ts index dd356709b8..9bb7586df5 100644 --- a/e2e/react-start/rsc-rsbuild/playwright.config.ts +++ b/e2e/react-start/rsc-rsbuild/playwright.config.ts @@ -1,9 +1,25 @@ +import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } +const e2ePortKey = process.env.E2E_PORT_KEY ?? packageJson.name const distDir = process.env.E2E_DIST_DIR ?? 'dist' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +if (process.env.TEST_WORKER_INDEX === undefined) { + for (const portFile of [ + `port-${e2ePortKey}.txt`, + `port-${e2ePortKey}-external.txt`, + ]) { + fs.rmSync(portFile, { force: true }) + } +} + +const PORT = await getTestServerPort(e2ePortKey) +const EXTERNAL_PORT = await getDummyServerPort(e2ePortKey) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -11,18 +27,23 @@ export default defineConfig({ workers: 1, reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { baseURL, }, webServer: { command: 'pnpm start', - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { PORT: String(PORT), E2E_DIST_DIR: distDir, + E2E_PORT_KEY: e2ePortKey, + EXTERNAL_SERVER_URL: `http://localhost:${EXTERNAL_PORT}`, }, }, diff --git a/e2e/react-start/rsc-rsbuild/tests/setup/global.setup.ts b/e2e/react-start/rsc-rsbuild/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3def5f6941 --- /dev/null +++ b/e2e/react-start/rsc-rsbuild/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(process.env.E2E_PORT_KEY ?? packageJson.name) +} diff --git a/e2e/react-start/rsc-rsbuild/tests/setup/global.teardown.ts b/e2e/react-start/rsc-rsbuild/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..a9ad1445f7 --- /dev/null +++ b/e2e/react-start/rsc-rsbuild/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(process.env.E2E_PORT_KEY ?? packageJson.name) +} diff --git a/e2e/react-start/rsc/package.json b/e2e/react-start/rsc/package.json index a30227d509..0e7414e2aa 100644 --- a/e2e/react-start/rsc/package.json +++ b/e2e/react-start/rsc/package.json @@ -13,8 +13,7 @@ "build:vite": "vite build && tsc --noEmit", "preview": "vite preview", "start": "node server.js", - "test:e2e-full": "pnpm build && playwright test --project=chromium", - "test:e2e:dev:rsbuild": "MODE=dev E2E_TOOLCHAIN=rsbuild playwright test --project=chromium" + "test:e2e-full": "pnpm build && sh -c 'rm -f \"port-${E2E_PORT_KEY:-$npm_package_name}.txt\" \"port-${E2E_PORT_KEY:-$npm_package_name}-external.txt\"' && playwright test --project=chromium" }, "nx": { "metadata": { @@ -41,7 +40,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", "@tanstack/eslint-plugin-start": "workspace:^", "@tanstack/router-e2e-utils": "workspace:^", @@ -50,9 +49,9 @@ "@types/react-dom": "^19.0.3", "@typescript-eslint/parser": "^8.23.0", "@vitejs/plugin-react": "^6.0.1", - "@vitejs/plugin-rsc": "^0.5.39", + "@vitejs/plugin-rsc": "^0.5.30", "eslint": "^9.22.0", - "srvx": "^1.0.0", + "srvx": "^0.10.0", "typescript": "^5.7.2", "vite": "^8.0.14" } diff --git a/e2e/react-start/rsc/playwright.config.ts b/e2e/react-start/rsc/playwright.config.ts index 075efdc5b9..9bb7586df5 100644 --- a/e2e/react-start/rsc/playwright.config.ts +++ b/e2e/react-start/rsc/playwright.config.ts @@ -1,11 +1,25 @@ +import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } +const e2ePortKey = process.env.E2E_PORT_KEY ?? packageJson.name const distDir = process.env.E2E_DIST_DIR ?? 'dist' -// MODE=dev runs the suite against the Rsbuild dev server instead of a build -const isRsbuildDev = process.env.MODE === 'dev' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +if (process.env.TEST_WORKER_INDEX === undefined) { + for (const portFile of [ + `port-${e2ePortKey}.txt`, + `port-${e2ePortKey}-external.txt`, + ]) { + fs.rmSync(portFile, { force: true }) + } +} + +const PORT = await getTestServerPort(e2ePortKey) +const EXTERNAL_PORT = await getDummyServerPort(e2ePortKey) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -13,19 +27,23 @@ export default defineConfig({ workers: 1, reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { baseURL, }, webServer: { - command: isRsbuildDev ? 'pnpm dev:rsbuild --port 0' : 'pnpm start', - wait: appServerReady, - reuseExistingServer: false, + command: 'pnpm start', + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, PORT: String(PORT), E2E_DIST_DIR: distDir, + E2E_PORT_KEY: e2ePortKey, + EXTERNAL_SERVER_URL: `http://localhost:${EXTERNAL_PORT}`, }, }, diff --git a/e2e/react-start/rsc/src/routes/rsc-external.tsx b/e2e/react-start/rsc/src/routes/rsc-external.tsx index 352f086b60..d6da119b26 100644 --- a/e2e/react-start/rsc/src/routes/rsc-external.tsx +++ b/e2e/react-start/rsc/src/routes/rsc-external.tsx @@ -109,7 +109,11 @@ const getExternalDataServerComponent = createServerFn({ method: 'GET' }) ) }) -const EXTERNAL_SERVER_URL = 'https://jsonplaceholder.typicode.com' +// The external server URL is provided by the e2e test setup +const EXTERNAL_SERVER_URL = + typeof process !== 'undefined' && process.env.EXTERNAL_SERVER_URL + ? process.env.EXTERNAL_SERVER_URL + : 'http://localhost:65003' export const Route = createFileRoute('/rsc-external')({ loader: async () => { diff --git a/e2e/react-start/rsc/tests/rsc-css-preload-complex.spec.ts b/e2e/react-start/rsc/tests/rsc-css-preload-complex.spec.ts index 35db86eca9..f5d8e04928 100644 --- a/e2e/react-start/rsc/tests/rsc-css-preload-complex.spec.ts +++ b/e2e/react-start/rsc/tests/rsc-css-preload-complex.spec.ts @@ -116,16 +116,15 @@ test.describe('RSC Complex CSS Preload Tests', () => { test('CSS module classes are scoped for all widgets', async ({ page }) => { await page.goto('/rsc-css-preload-complex') - // Widget A classes should be hashed (accept Vite `_widget_xxx`, Rspack - // `widget-xxx`, and Rsbuild dev `src-...-module__widget-xxx` scoped names) + // Widget A classes should be hashed (accept Vite `_widget_xxx` or Rspack `widget-xxx` scoped names) const widgetA = page.locator('[data-testid="client-widget-a"]') const widgetAClass = await widgetA.getAttribute('class') - expect(widgetAClass).toMatch(/(^|\s|__)(_widget_|widget[-_])[\w-]+/) + expect(widgetAClass).toMatch(/(^|\s)(_widget_|widget[-_])[\w-]+/) // Widget B classes should be hashed const widgetB = page.locator('[data-testid="client-widget-b"]') const widgetBClass = await widgetB.getAttribute('class') - expect(widgetBClass).toMatch(/(^|\s|__)(_widget_|widget[-_])[\w-]+/) + expect(widgetBClass).toMatch(/(^|\s)(_widget_|widget[-_])[\w-]+/) // Classes should be different (different modules) expect(widgetAClass).not.toBe(widgetBClass) diff --git a/e2e/react-start/rsc/tests/rsc-external.spec.ts b/e2e/react-start/rsc/tests/rsc-external.spec.ts index ae16ef7c43..7ce4bd3c18 100644 --- a/e2e/react-start/rsc/tests/rsc-external.spec.ts +++ b/e2e/react-start/rsc/tests/rsc-external.spec.ts @@ -19,9 +19,13 @@ test.describe('RSC External API Tests - External data fetching', () => { await page.goto('/rsc-external') await page.waitForURL(/\/rsc-external/) - await expect(page.getByTestId('external-server-url')).toHaveText( - 'https://jsonplaceholder.typicode.com', - ) + // Verify the external server URL contains expected pattern + const serverUrl = await page + .getByTestId('external-server-url') + .textContent() + expect(serverUrl).toBeTruthy() + // Should be localhost with a port + expect(serverUrl).toMatch(/localhost:\d+/) }) test('Loader timestamp is present', async ({ page }) => { diff --git a/e2e/react-start/rsc/tests/rsc-stream-generator.spec.ts b/e2e/react-start/rsc/tests/rsc-stream-generator.spec.ts index 842c9358c0..5faa6b1508 100644 --- a/e2e/react-start/rsc/tests/rsc-stream-generator.spec.ts +++ b/e2e/react-start/rsc/tests/rsc-stream-generator.spec.ts @@ -67,22 +67,29 @@ test.describe('RSC Stream Generator Tests - Streaming RSCs via async generator', // Start streaming await page.getByTestId('start-stream-btn').click() - const notifications = page + // First 3 should appear quickly (initial batch) + await expect(page.getByTestId('notification-list')).toBeVisible() + + // Wait a bit and check that notifications are accumulating + await page.waitForTimeout(500) + const initialCount = await page .getByTestId('notification-list') .locator('[data-testid^="notification-notif_"]') + .count() + expect(initialCount).toBeGreaterThanOrEqual(3) - // The initial batch of 3 renders while the stream is still open - await expect(notifications.nth(2)).toBeVisible() - await expect(page.getByTestId('streaming-status')).toBeVisible() - const initialCount = await notifications.count() - expect(initialCount).toBeLessThan(7) + // Wait for more to stream in + await page.waitForTimeout(2000) + const laterCount = await page + .getByTestId('notification-list') + .locator('[data-testid^="notification-notif_"]') + .count() + expect(laterCount).toBeGreaterThan(initialCount) - // The remaining notifications stream in afterwards - await expect(notifications.nth(initialCount)).toBeVisible() + // Wait for completion await expect(page.getByTestId('stream-complete')).toBeVisible({ timeout: 10000, }) - await expect(notifications).toHaveCount(7) }) test('Each notification is a complete RSC with server data', async ({ diff --git a/e2e/react-start/rsc/tests/rsc-stream-readable.spec.ts b/e2e/react-start/rsc/tests/rsc-stream-readable.spec.ts index dc21f8d9c5..356907e311 100644 --- a/e2e/react-start/rsc/tests/rsc-stream-readable.spec.ts +++ b/e2e/react-start/rsc/tests/rsc-stream-readable.spec.ts @@ -67,22 +67,29 @@ test.describe('RSC Stream Readable Tests - Streaming RSCs via ReadableStream', ( // Start streaming await page.getByTestId('start-stream-btn').click() - const notifications = page + // First 3 should appear quickly (initial batch) + await expect(page.getByTestId('notification-list')).toBeVisible() + + // Wait a bit and check that notifications are accumulating + await page.waitForTimeout(500) + const initialCount = await page .getByTestId('notification-list') .locator('[data-testid^="notification-notif_"]') + .count() + expect(initialCount).toBeGreaterThanOrEqual(3) - // The initial batch of 3 renders while the stream is still open - await expect(notifications.nth(2)).toBeVisible() - await expect(page.getByTestId('streaming-status')).toBeVisible() - const initialCount = await notifications.count() - expect(initialCount).toBeLessThan(7) + // Wait for more to stream in + await page.waitForTimeout(2000) + const laterCount = await page + .getByTestId('notification-list') + .locator('[data-testid^="notification-notif_"]') + .count() + expect(laterCount).toBeGreaterThan(initialCount) - // The remaining notifications stream in afterwards - await expect(notifications.nth(initialCount)).toBeVisible() + // Wait for completion await expect(page.getByTestId('stream-complete')).toBeVisible({ timeout: 10000, }) - await expect(notifications).toHaveCount(7) }) test('Each notification is a complete RSC with server data', async ({ diff --git a/e2e/react-start/rsc/tests/setup/global.setup.ts b/e2e/react-start/rsc/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3def5f6941 --- /dev/null +++ b/e2e/react-start/rsc/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +import { e2eStartDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function setup() { + await e2eStartDummyServer(process.env.E2E_PORT_KEY ?? packageJson.name) +} diff --git a/e2e/react-start/rsc/tests/setup/global.teardown.ts b/e2e/react-start/rsc/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..a9ad1445f7 --- /dev/null +++ b/e2e/react-start/rsc/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +import { e2eStopDummyServer } from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } + +export default async function teardown() { + await e2eStopDummyServer(process.env.E2E_PORT_KEY ?? packageJson.name) +} diff --git a/e2e/react-start/scroll-restoration/package.json b/e2e/react-start/scroll-restoration/package.json index 9e90871158..17bf2b2449 100644 --- a/e2e/react-start/scroll-restoration/package.json +++ b/e2e/react-start/scroll-restoration/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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -30,7 +30,7 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/react-start/scroll-restoration/playwright.config.ts b/e2e/react-start/scroll-restoration/playwright.config.ts index 1862174905..1e33c9ae5e 100644 --- a/e2e/react-start/scroll-restoration/playwright.config.ts +++ b/e2e/react-start/scroll-restoration/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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}` /** @@ -13,19 +18,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: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/react-start/scroll-restoration/src/client.tsx b/e2e/react-start/scroll-restoration/src/client.tsx deleted file mode 100644 index 25a0ebf7e7..0000000000 --- a/e2e/react-start/scroll-restoration/src/client.tsx +++ /dev/null @@ -1,23 +0,0 @@ -import { StrictMode, startTransition } from 'react' -import { hydrateRoot } from 'react-dom/client' -import { StartClient } from '@tanstack/react-start/client' - -async function bootstrap() { - // Fixture-only gate: leave SSR markup, CSS and inline restoration intact. - // Waiting here allows load to finish before StartClient constructs the router. - if ((window as any).__holdScrollBootstrap) { - await new Promise((resolve) => { - ;(window as any).__releaseScrollBootstrap = resolve - }) - } - startTransition(() => { - hydrateRoot( - document, - - - , - ) - }) -} - -void bootstrap() diff --git a/e2e/react-start/scroll-restoration/src/routes/__root.tsx b/e2e/react-start/scroll-restoration/src/routes/__root.tsx index 875bff34e0..563d9208ec 100644 --- a/e2e/react-start/scroll-restoration/src/routes/__root.tsx +++ b/e2e/react-start/scroll-restoration/src/routes/__root.tsx @@ -65,10 +65,6 @@ export const Route = createRootRoute({ }) function RootComponent() { - React.useEffect(() => { - dispatchEvent(new Event('test-scroll-hydrated')) - }, []) - return ( diff --git a/e2e/react-start/scroll-restoration/src/utils/posts.tsx b/e2e/react-start/scroll-restoration/src/utils/posts.tsx index bc56dff904..c6cba486ab 100644 --- a/e2e/react-start/scroll-restoration/src/utils/posts.tsx +++ b/e2e/react-start/scroll-restoration/src/utils/posts.tsx @@ -12,7 +12,11 @@ export type PostType = { export class PostNotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +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 = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-start/scroll-restoration/src/utils/users.tsx b/e2e/react-start/scroll-restoration/src/utils/users.tsx index 7ba645b383..79b45867d5 100644 --- a/e2e/react-start/scroll-restoration/src/utils/users.tsx +++ b/e2e/react-start/scroll-restoration/src/utils/users.tsx @@ -3,3 +3,8 @@ export type User = { name: string email: string } + +const PORT = + import.meta.env.VITE_SERVER_PORT || process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` diff --git a/e2e/react-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts b/e2e/react-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts deleted file mode 100644 index 6c1e1693b6..0000000000 --- a/e2e/react-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { writeFile } from 'node:fs/promises' -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' -import { scrollRestorationLifecycleTests } from '../../../scroll-restoration-lifecycle' - -scrollRestorationLifecycleTests(test) - -test('hands native scroll restoration back to the browser on reload', async ({ - page, -}, testInfo) => { - const errors: Array = [] - page.on('pageerror', (error) => errors.push(error.message)) - const key = 'test-scroll-pagehide' - const token = testInfo.testId - await page.addInitScript(() => { - ;(window as any).__initialScrollRestoration = history.scrollRestoration - }) - await page.goto('/') - await page.getByRole('link', { name: '/reset-scroll-false-a' }).click() - await page.waitForLoadState('networkidle') - expect(await page.evaluate(() => history.scrollRestoration)).toBe('manual') - - const position = await page.evaluate( - async ({ key, token }) => { - sessionStorage.removeItem(key) - const scrolled = new Promise((resolve) => { - addEventListener('scroll', () => resolve(), { once: true }) - }) - scrollTo(0, 500) - await scrolled - // Registered after router setup, so this observes the router's handoff. - window.addEventListener( - 'pagehide', - (event) => { - sessionStorage.setItem( - key, - JSON.stringify({ - token, - mode: history.scrollRestoration, - persisted: (event as PageTransitionEvent).persisted, - trusted: event.isTrusted, - x: scrollX, - y: scrollY, - }), - ) - }, - { once: true }, - ) - return { x: scrollX, y: scrollY } - }, - { key, token }, - ) - expect(position.y).toBeGreaterThan(0) - - await page.reload() - const observation = await page.evaluate( - (key) => ({ - outgoing: JSON.parse(sessionStorage.getItem(key)!), - initialMode: (window as any).__initialScrollRestoration, - }), - key, - ) - const snapshotPath = testInfo.outputPath('reload-handoff.json') - await writeFile( - snapshotPath, - JSON.stringify({ ...observation, errors }, null, 2), - ) - await testInfo.attach('reload-handoff', { - path: snapshotPath, - contentType: 'application/json', - }) - expect(observation.outgoing).toMatchObject({ - token, - trusted: true, - mode: 'auto', - }) - expect(observation.initialMode).toBe('auto') - expect(Math.abs(observation.outgoing.x - position.x)).toBeLessThanOrEqual(1) - expect(Math.abs(observation.outgoing.y - position.y)).toBeLessThanOrEqual(1) - await expect - .poll(() => page.evaluate(() => history.scrollRestoration)) - .toBe('manual') - await expect.poll(() => page.evaluate(() => scrollY)).toBe(position.y) - expect(errors).toEqual([]) -}) diff --git a/e2e/react-start/scroll-restoration/tests/scroll-restoration-reload.spec.ts b/e2e/react-start/scroll-restoration/tests/scroll-restoration-reload.spec.ts deleted file mode 100644 index 767f02a39c..0000000000 --- a/e2e/react-start/scroll-restoration/tests/scroll-restoration-reload.spec.ts +++ /dev/null @@ -1,191 +0,0 @@ -import { writeFile } from 'node:fs/promises' -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' - -// A frame recorder is diagnostic evidence, not proof of compositor-frame pixels. -for (const holdBootstrap of [false, true]) { - test(`reload keeps rendered SSR scroll stable (bootstrap held=${holdBootstrap})`, async ({ - page, - }, testInfo) => { - const errors: Array = [] - page.on('pageerror', (error) => errors.push(error.message)) - await page.addInitScript(() => { - const holdKey = 'test-hold-scroll-bootstrap' - ;(window as any).__holdScrollBootstrap = - sessionStorage.getItem(holdKey) === 'true' - sessionStorage.removeItem(holdKey) - const samples: Array<{ - time: number - phase: string - x: number - y: number - mode: ScrollRestoration - scrollHeight: number - viewportHeight: number - anchorTop: number | null - visibility: DocumentVisibilityState - }> = [] - let phase = 'initial' - let frame = 0 - const sample = () => { - samples.push({ - time: performance.now(), - phase, - x: scrollX, - y: scrollY, - mode: history.scrollRestoration, - scrollHeight: document.documentElement?.scrollHeight ?? 0, - viewportHeight: innerHeight, - anchorTop: - document - .querySelector('[data-testid="reset-scroll-false-link-6"]') - ?.getBoundingClientRect().top ?? null, - visibility: document.visibilityState, - }) - } - const mark = (next: string) => { - phase = next - sample() - } - const tick = () => { - sample() - if (samples.length < 600) { - frame = requestAnimationFrame(tick) - } - } - sample() - frame = requestAnimationFrame(tick) - for (const event of [ - 'DOMContentLoaded', - 'load', - 'pageshow', - 'test-scroll-hydrated', - 'test-scroll-bootstrap-release', - ]) { - addEventListener(event, () => mark(event)) - } - ;(window as any).__scrollProbe = { - samples, - stop: () => { - cancelAnimationFrame(frame) - return { - samples, - paints: performance - .getEntriesByType('paint') - .map(({ name, startTime }) => ({ name, startTime })), - } - }, - } - }) - await page.goto('/') - await page.getByRole('link', { name: '/reset-scroll-false-a' }).click() - await page.waitForLoadState('networkidle') - const before = await page.evaluate(async (holdBootstrap) => { - scrollTo(0, 500) - await new Promise((resolve) => - requestAnimationFrame(() => requestAnimationFrame(() => resolve())), - ) - sessionStorage.setItem( - 'test-hold-scroll-bootstrap', - String(holdBootstrap), - ) - return { - y: scrollY, - anchorTop: document - .querySelector('[data-testid="reset-scroll-false-link-6"]')! - .getBoundingClientRect().top, - } - }, holdBootstrap) - expect(before.y).toBeGreaterThan(0) - await page.reload() - // This window starts at document readiness, independently of scroll correctness. - await page.evaluate(async () => { - await Promise.all( - Array.from( - document.querySelectorAll('link[rel="stylesheet"]'), - (link) => { - if (link.sheet) { - return - } - return new Promise((resolve) => - link.addEventListener('load', () => resolve(), { once: true }), - ) - }, - ), - ) - for (let i = 0; i < 4; i++) { - await new Promise((resolve) => - requestAnimationFrame(() => resolve()), - ) - } - }) - if (holdBootstrap) { - expect( - await page.evaluate( - () => typeof (window as any).__releaseScrollBootstrap, - ), - ).toBe('function') - expect( - await page.evaluate(() => - (window as any).__scrollProbe.samples.some( - (sample: any) => sample.phase === 'test-scroll-hydrated', - ), - ), - ).toBe(false) - } - const screenshotPath = testInfo.outputPath('SSR-viewport.png') - await page.screenshot({ path: screenshotPath }) - await testInfo.attach('SSR-viewport', { - path: screenshotPath, - contentType: 'image/png', - }) - const held = await page.evaluate(() => ({ - y: scrollY, - anchorTop: document - .querySelector('[data-testid="reset-scroll-false-link-6"]')! - .getBoundingClientRect().top, - })) - if (holdBootstrap) { - await page.evaluate(() => { - dispatchEvent(new Event('test-scroll-bootstrap-release')) - ;(window as any).__releaseScrollBootstrap() - }) - } - await expect - .poll(() => page.evaluate(() => history.scrollRestoration)) - .toBe('manual') - await page.waitForLoadState('networkidle') - await page.evaluate(async () => { - for (let i = 0; i < 8; i++) { - await new Promise((resolve) => - requestAnimationFrame(() => resolve()), - ) - } - }) - const timeline = await page.evaluate(() => - (window as any).__scrollProbe.stop(), - ) - const timelinePath = testInfo.outputPath('scroll-timeline.json') - await writeFile( - timelinePath, - JSON.stringify({ before, held, ...timeline, errors }, null, 2), - ) - await testInfo.attach('scroll-timeline', { - path: timelinePath, - contentType: 'application/json', - }) - expect(held.y).toBe(before.y) - expect(held.anchorTop).toBeCloseTo(before.anchorTop, 0) - const renderedSamples = timeline.samples.filter( - (sample: any) => sample.phase !== 'initial' && sample.anchorTop !== null, - ) - expect(renderedSamples.length).toBeGreaterThan(0) - for (const sample of renderedSamples) { - expect(Math.abs(sample.y - before.y)).toBeLessThanOrEqual(1) - expect(Math.abs(sample.anchorTop - before.anchorTop)).toBeLessThanOrEqual( - 1, - ) - } - expect(errors).toEqual([]) - }) -} diff --git a/e2e/react-start/scroll-restoration/tests/setup/global.setup.ts b/e2e/react-start/scroll-restoration/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-start/scroll-restoration/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/scroll-restoration/tests/setup/global.teardown.ts b/e2e/react-start/scroll-restoration/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/scroll-restoration/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/selective-ssr/package.json b/e2e/react-start/selective-ssr/package.json index 87e8e3cf42..1eb903c183 100644 --- a/e2e/react-start/selective-ssr/package.json +++ b/e2e/react-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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -26,7 +26,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/react-start/selective-ssr/playwright.config.ts b/e2e/react-start/selective-ssr/playwright.config.ts index 630989e41f..badd6db0eb 100644 --- a/e2e/react-start/selective-ssr/playwright.config.ts +++ b/e2e/react-start/selective-ssr/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/serialization-adapters/package.json b/e2e/react-start/serialization-adapters/package.json index 5bf4b29a80..0e0d157733 100644 --- a/e2e/react-start/serialization-adapters/package.json +++ b/e2e/react-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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -26,7 +26,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/react-start/serialization-adapters/playwright.config.ts b/e2e/react-start/serialization-adapters/playwright.config.ts index 630989e41f..badd6db0eb 100644 --- a/e2e/react-start/serialization-adapters/playwright.config.ts +++ b/e2e/react-start/serialization-adapters/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/server-functions-global-middleware/package.json b/e2e/react-start/server-functions-global-middleware/package.json index 4aab99e22c..5898097c81 100644 --- a/e2e/react-start/server-functions-global-middleware/package.json +++ b/e2e/react-start/server-functions-global-middleware/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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -25,7 +25,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/react-start/server-functions-global-middleware/playwright.config.ts b/e2e/react-start/server-functions-global-middleware/playwright.config.ts index 7b9ac2ceb5..8330e023ee 100644 --- a/e2e/react-start/server-functions-global-middleware/playwright.config.ts +++ b/e2e/react-start/server-functions-global-middleware/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -export const PORT = Number(process.env.E2E_APP_PORT ?? 0) +export const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/server-functions-global-middleware/src/routeTree.gen.ts b/e2e/react-start/server-functions-global-middleware/src/routeTree.gen.ts index e909a808f2..739df05d7a 100644 --- a/e2e/react-start/server-functions-global-middleware/src/routeTree.gen.ts +++ b/e2e/react-start/server-functions-global-middleware/src/routeTree.gen.ts @@ -13,7 +13,6 @@ import { Route as IndexRouteImport } from './routes/index' import { Route as ContextCollisionRouteImport } from './routes/context-collision' import { Route as MultipleServerFunctionsRouteImport } from './routes/multiple-server-functions' import { Route as PathnameMiddlewareRouteImport } from './routes/pathname-middleware' -import { Route as SendContextContractRouteImport } from './routes/send-context-contract' import { Route as SimpleRouteImport } from './routes/simple' const IndexRoute = IndexRouteImport.update({ @@ -36,11 +35,6 @@ const PathnameMiddlewareRoute = PathnameMiddlewareRouteImport.update({ path: '/pathname-middleware', getParentRoute: () => rootRouteImport, } as any) -const SendContextContractRoute = SendContextContractRouteImport.update({ - id: '/send-context-contract', - path: '/send-context-contract', - getParentRoute: () => rootRouteImport, -} as any) const SimpleRoute = SimpleRouteImport.update({ id: '/simple', path: '/simple', @@ -52,7 +46,6 @@ export interface FileRoutesByFullPath { '/context-collision': typeof ContextCollisionRoute '/multiple-server-functions': typeof MultipleServerFunctionsRoute '/pathname-middleware': typeof PathnameMiddlewareRoute - '/send-context-contract': typeof SendContextContractRoute '/simple': typeof SimpleRoute } export interface FileRoutesByTo { @@ -60,7 +53,6 @@ export interface FileRoutesByTo { '/context-collision': typeof ContextCollisionRoute '/multiple-server-functions': typeof MultipleServerFunctionsRoute '/pathname-middleware': typeof PathnameMiddlewareRoute - '/send-context-contract': typeof SendContextContractRoute '/simple': typeof SimpleRoute } export interface FileRoutesById { @@ -69,7 +61,6 @@ export interface FileRoutesById { '/context-collision': typeof ContextCollisionRoute '/multiple-server-functions': typeof MultipleServerFunctionsRoute '/pathname-middleware': typeof PathnameMiddlewareRoute - '/send-context-contract': typeof SendContextContractRoute '/simple': typeof SimpleRoute } export interface FileRouteTypes { @@ -79,7 +70,6 @@ export interface FileRouteTypes { | '/context-collision' | '/multiple-server-functions' | '/pathname-middleware' - | '/send-context-contract' | '/simple' fileRoutesByTo: FileRoutesByTo to: @@ -87,7 +77,6 @@ export interface FileRouteTypes { | '/context-collision' | '/multiple-server-functions' | '/pathname-middleware' - | '/send-context-contract' | '/simple' id: | '__root__' @@ -95,7 +84,6 @@ export interface FileRouteTypes { | '/context-collision' | '/multiple-server-functions' | '/pathname-middleware' - | '/send-context-contract' | '/simple' fileRoutesById: FileRoutesById } @@ -104,7 +92,6 @@ export interface RootRouteChildren { ContextCollisionRoute: typeof ContextCollisionRoute MultipleServerFunctionsRoute: typeof MultipleServerFunctionsRoute PathnameMiddlewareRoute: typeof PathnameMiddlewareRoute - SendContextContractRoute: typeof SendContextContractRoute SimpleRoute: typeof SimpleRoute } @@ -138,13 +125,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PathnameMiddlewareRouteImport parentRoute: typeof rootRouteImport } - '/send-context-contract': { - id: '/send-context-contract' - path: '/send-context-contract' - fullPath: '/send-context-contract' - preLoaderRoute: typeof SendContextContractRouteImport - parentRoute: typeof rootRouteImport - } '/simple': { id: '/simple' path: '/simple' @@ -160,7 +140,6 @@ const rootRouteChildren: RootRouteChildren = { ContextCollisionRoute: ContextCollisionRoute, MultipleServerFunctionsRoute: MultipleServerFunctionsRoute, PathnameMiddlewareRoute: PathnameMiddlewareRoute, - SendContextContractRoute: SendContextContractRoute, SimpleRoute: SimpleRoute, } export const routeTree = rootRouteImport diff --git a/e2e/react-start/server-functions-global-middleware/src/routes/send-context-contract.tsx b/e2e/react-start/server-functions-global-middleware/src/routes/send-context-contract.tsx deleted file mode 100644 index af4a22b6fd..0000000000 --- a/e2e/react-start/server-functions-global-middleware/src/routes/send-context-contract.tsx +++ /dev/null @@ -1,181 +0,0 @@ -import { useState } from 'react' -import { createFileRoute } from '@tanstack/react-router' -import { createMiddleware, createServerFn } from '@tanstack/react-start' - -function verifyCopy( - source: object, - actual: unknown, - expected: Record, -) { - if ( - actual === source || - JSON.stringify(actual) !== JSON.stringify(expected) - ) { - throw new Error('sendContext must merge into a fresh object') - } -} - -const absent = createMiddleware({ type: 'function' }) - .client(async ({ sendContext, next }) => { - if (sendContext !== undefined) { - throw new Error('Absent client sendContext must be undefined') - } - const result = await next() - if (result.sendContext !== undefined) { - throw new Error('Absent client result sendContext must be undefined') - } - return result - }) - .server(async ({ next }) => { - const result = await next() - if (result.sendContext !== undefined) { - throw new Error('Absent server result sendContext must be undefined') - } - return result - }) - -const explicitEmpty = createMiddleware({ type: 'function' }) - .client(async ({ next }) => { - const source = Object.freeze({}) - const result = await next({ sendContext: source }) - verifyCopy(source, result.sendContext, {}) - return result - }) - .server(async ({ next }) => { - const source = Object.freeze({}) - const result = await next({ sendContext: source }) - verifyCopy(source, result.sendContext, {}) - return result - }) - -const first = createMiddleware({ type: 'function' }) - .client(async ({ next }) => { - const source = Object.freeze({ first: 'one' }) - const result = await next({ sendContext: source }) - verifyCopy(source, result.sendContext, { first: 'one', second: 'two' }) - return result - }) - .server(async ({ next }) => { - const source = Object.freeze({ first: 'one' }) - const result = await next({ sendContext: source }) - verifyCopy(source, result.sendContext, { first: 'one', second: 'two' }) - return result - }) - -const second = createMiddleware({ type: 'function' }) - .middleware([first]) - .client(async ({ next }) => { - const source = Object.freeze({ second: 'two' }) - const result = await next({ sendContext: source }) - verifyCopy(source, result.sendContext, { first: 'one', second: 'two' }) - return result - }) - .server(async ({ context, next }) => { - if (context.first !== 'one' || context.second !== 'two') { - throw new Error('Client sendContext must reach the server') - } - const source = Object.freeze({ second: 'two' }) - const result = await next({ sendContext: source }) - verifyCopy(source, result.sendContext, { first: 'one', second: 'two' }) - return result - }) - -const absentFn = createServerFn() - .middleware([absent]) - .handler(() => 'absent') - -const emptyFn = createServerFn() - .middleware([explicitEmpty]) - .handler(() => 'empty') - -const nonemptyFn = createServerFn() - .middleware([second]) - .handler(() => 'nonempty') - -const accessors = createMiddleware({ type: 'function' }) - .client(async ({ next }) => { - const source = Object.freeze({ value: 'client' }) - const reads: Array = [] - const result = await next({ - get sendContext() { - reads.push('sendContext') - return source - }, - get headers() { - reads.push('headers') - return { 'x-context-accessor': 'preserved' } - }, - }) - if (reads.join(',') !== 'sendContext,headers,sendContext,headers') { - throw new Error(`Client middleware accessor order changed: ${reads}`) - } - verifyCopy(source, result.sendContext, { value: 'client' }) - if (new Headers(result.headers).get('x-context-accessor') !== 'preserved') { - throw new Error('Client middleware header was not preserved') - } - return result - }) - .server(async ({ next }) => { - const source = Object.freeze({ value: 'server' }) - let reads = 0 - const result = await next({ - get sendContext() { - reads++ - return source - }, - }) - if (reads !== 2) { - throw new Error(`Server middleware accessor read ${reads} times`) - } - verifyCopy(source, result.sendContext, { value: 'server' }) - return result - }) - -const observeServerReply = createMiddleware({ type: 'function' }) - .middleware([accessors]) - .client(async ({ next }) => { - const result = await next() - if (result.context.value !== 'server') { - throw new Error('Server sendContext must reach the client result context') - } - return result - }) - -const accessorFn = createServerFn() - .middleware([observeServerReply]) - .handler(() => 'accessors') - -async function verifyAll() { - return ( - await Promise.all([absentFn(), emptyFn(), nonemptyFn(), accessorFn()]) - ).join(',') -} - -export const Route = createFileRoute('/send-context-contract')({ - loader: verifyAll, - component: SendContextContract, -}) - -function SendContextContract() { - const loaderResult = Route.useLoaderData() - const [result, setResult] = useState('pending') - return ( -
-
{loaderResult}
- -
{result}
-
- ) -} diff --git a/e2e/react-start/server-functions-global-middleware/tests/send-context-contract.spec.ts b/e2e/react-start/server-functions-global-middleware/tests/send-context-contract.spec.ts deleted file mode 100644 index e39927ebab..0000000000 --- a/e2e/react-start/server-functions-global-middleware/tests/send-context-contract.spec.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' - -test('preserves absent and explicit sendContext through SSR and client calls', async ({ - page, -}) => { - await page.goto('/send-context-contract') - await expect(page.getByTestId('send-context-loader')).toHaveText( - 'absent,empty,nonempty,accessors', - ) - await page.getByTestId('invoke-send-context-contract').click() - await expect(page.getByTestId('send-context-client')).toHaveText( - 'absent,empty,nonempty,accessors', - ) -}) diff --git a/e2e/react-start/server-functions/package.json b/e2e/react-start/server-functions/package.json index 63d8661717..390d417423 100644 --- a/e2e/react-start/server-functions/package.json +++ b/e2e/react-start/server-functions/package.json @@ -13,7 +13,7 @@ "build:rsbuild": "rsbuild build && tsc --noEmit", "preview": "vite preview", "start": "node server.js", - "test:e2e": "pnpm build && playwright test --project=chromium && pnpm run test:e2e:rsbuild-cache", + "test:e2e": "rm -rf port*.txt && pnpm build && playwright test --project=chromium && pnpm run test:e2e:rsbuild-cache", "test:e2e:rsbuild-cache": "playwright test -c playwright.rsbuild-cache.config.ts --project=chromium" }, "dependencies": { @@ -31,7 +31,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", "@tailwindcss/postcss": "^4.2.2", "@tailwindcss/vite": "^4.2.2", @@ -42,7 +42,7 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/react-start/server-functions/playwright.config.ts b/e2e/react-start/server-functions/playwright.config.ts index 33fe8c0572..d88e582e2f 100644 --- a/e2e/react-start/server-functions/playwright.config.ts +++ b/e2e/react-start/server-functions/playwright.config.ts @@ -1,9 +1,11 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } +const e2ePortKey = process.env.E2E_PORT_KEY ?? packageJson.name const distDir = process.env.E2E_DIST_DIR ?? 'dist' -export const PORT = Number(process.env.E2E_APP_PORT ?? 0) +export const PORT = await getTestServerPort(e2ePortKey) const baseURL = `http://localhost:${PORT}` /** @@ -23,13 +25,14 @@ export default defineConfig({ webServer: { command: `PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { PORT: String(PORT), VITE_SERVER_PORT: String(PORT), E2E_DIST_DIR: distDir, + E2E_PORT_KEY: e2ePortKey, }, }, diff --git a/e2e/react-start/server-functions/tests/server-functions.spec.ts b/e2e/react-start/server-functions/tests/server-functions.spec.ts index f87e699330..5bb458d61c 100644 --- a/e2e/react-start/server-functions/tests/server-functions.spec.ts +++ b/e2e/react-start/server-functions/tests/server-functions.spec.ts @@ -1,9 +1,11 @@ import * as fs from 'node:fs' import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' +import { getTestServerPort, test } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } import type { Page } from '@playwright/test' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const e2ePortKey = process.env.E2E_PORT_KEY ?? packageJson.name +const PORT = await getTestServerPort(e2ePortKey) test('Server function URLs correctly include explicit ids', async ({ page, diff --git a/e2e/react-start/server-routes-global-middleware/package.json b/e2e/react-start/server-routes-global-middleware/package.json index ea6ddfb793..6887b19b5f 100644 --- a/e2e/react-start/server-routes-global-middleware/package.json +++ b/e2e/react-start/server-routes-global-middleware/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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -25,7 +25,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/react-start/server-routes-global-middleware/playwright.config.ts b/e2e/react-start/server-routes-global-middleware/playwright.config.ts index 7b9ac2ceb5..8330e023ee 100644 --- a/e2e/react-start/server-routes-global-middleware/playwright.config.ts +++ b/e2e/react-start/server-routes-global-middleware/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -export const PORT = Number(process.env.E2E_APP_PORT ?? 0) +export const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/server-routes/package.json b/e2e/react-start/server-routes/package.json index 99e9090a16..0e09246ad8 100644 --- a/e2e/react-start/server-routes/package.json +++ b/e2e/react-start/server-routes/package.json @@ -34,7 +34,7 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/react-start/server-routes/playwright.config.ts b/e2e/react-start/server-routes/playwright.config.ts index 7b9ac2ceb5..8330e023ee 100644 --- a/e2e/react-start/server-routes/playwright.config.ts +++ b/e2e/react-start/server-routes/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -export const PORT = Number(process.env.E2E_APP_PORT ?? 0) +export const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/server-routes/src/routeTree.gen.ts b/e2e/react-start/server-routes/src/routeTree.gen.ts index 7ae1e4f551..2454c3bb32 100644 --- a/e2e/react-start/server-routes/src/routeTree.gen.ts +++ b/e2e/react-start/server-routes/src/routeTree.gen.ts @@ -20,9 +20,7 @@ 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 ApiParamsFooRouteRouteImport } from './routes/api/params/$foo/route' -import { Route as ApiParsedParamsIdRouteImport } from './routes/api/parsed-params.$id' import { Route as ApiParamsFooBarRouteImport } from './routes/api/params/$foo/$bar' -import { Route as ApiParsedParamsIdChildIdRouteImport } from './routes/api/parsed-params.$id.$childId' const IndexRoute = IndexRouteImport.update({ id: '/', @@ -79,22 +77,11 @@ const ApiParamsFooRouteRoute = ApiParamsFooRouteRouteImport.update({ path: '/api/params/$foo', getParentRoute: () => rootRouteImport, } as any) -const ApiParsedParamsIdRoute = ApiParsedParamsIdRouteImport.update({ - id: '/api/parsed-params/$id', - path: '/api/parsed-params/$id', - getParentRoute: () => rootRouteImport, -} as any) const ApiParamsFooBarRoute = ApiParamsFooBarRouteImport.update({ id: '/$bar', path: '/$bar', getParentRoute: () => ApiParamsFooRouteRoute, } as any) -const ApiParsedParamsIdChildIdRoute = - ApiParsedParamsIdChildIdRouteImport.update({ - id: '/$childId', - path: '/$childId', - getParentRoute: () => ApiParsedParamsIdRoute, - } as any) export interface FileRoutesByFullPath { '/': typeof IndexRoute @@ -108,9 +95,7 @@ export interface FileRoutesByFullPath { '/methods/only-any': typeof MethodsOnlyAnyRoute '/methods/': typeof MethodsIndexRoute '/api/params/$foo': typeof ApiParamsFooRouteRouteWithChildren - '/api/parsed-params/$id': typeof ApiParsedParamsIdRouteWithChildren '/api/params/$foo/$bar': typeof ApiParamsFooBarRoute - '/api/parsed-params/$id/$childId': typeof ApiParsedParamsIdChildIdRoute } export interface FileRoutesByTo { '/': typeof IndexRoute @@ -123,9 +108,7 @@ export interface FileRoutesByTo { '/methods/only-any': typeof MethodsOnlyAnyRoute '/methods': typeof MethodsIndexRoute '/api/params/$foo': typeof ApiParamsFooRouteRouteWithChildren - '/api/parsed-params/$id': typeof ApiParsedParamsIdRouteWithChildren '/api/params/$foo/$bar': typeof ApiParamsFooBarRoute - '/api/parsed-params/$id/$childId': typeof ApiParsedParamsIdChildIdRoute } export interface FileRoutesById { __root__: typeof rootRouteImport @@ -140,9 +123,7 @@ export interface FileRoutesById { '/methods/only-any': typeof MethodsOnlyAnyRoute '/methods/': typeof MethodsIndexRoute '/api/params/$foo': typeof ApiParamsFooRouteRouteWithChildren - '/api/parsed-params/$id': typeof ApiParsedParamsIdRouteWithChildren '/api/params/$foo/$bar': typeof ApiParamsFooBarRoute - '/api/parsed-params/$id/$childId': typeof ApiParsedParamsIdChildIdRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath @@ -158,9 +139,7 @@ export interface FileRouteTypes { | '/methods/only-any' | '/methods/' | '/api/params/$foo' - | '/api/parsed-params/$id' | '/api/params/$foo/$bar' - | '/api/parsed-params/$id/$childId' fileRoutesByTo: FileRoutesByTo to: | '/' @@ -173,9 +152,7 @@ export interface FileRouteTypes { | '/methods/only-any' | '/methods' | '/api/params/$foo' - | '/api/parsed-params/$id' | '/api/params/$foo/$bar' - | '/api/parsed-params/$id/$childId' id: | '__root__' | '/' @@ -189,9 +166,7 @@ export interface FileRouteTypes { | '/methods/only-any' | '/methods/' | '/api/params/$foo' - | '/api/parsed-params/$id' | '/api/params/$foo/$bar' - | '/api/parsed-params/$id/$childId' fileRoutesById: FileRoutesById } export interface RootRouteChildren { @@ -204,7 +179,6 @@ export interface RootRouteChildren { ApiMiddlewareContextRoute: typeof ApiMiddlewareContextRoute ApiOnlyAnyRoute: typeof ApiOnlyAnyRoute ApiParamsFooRouteRoute: typeof ApiParamsFooRouteRouteWithChildren - ApiParsedParamsIdRoute: typeof ApiParsedParamsIdRouteWithChildren } declare module '@tanstack/react-router' { @@ -286,13 +260,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiParamsFooRouteRouteImport parentRoute: typeof rootRouteImport } - '/api/parsed-params/$id': { - id: '/api/parsed-params/$id' - path: '/api/parsed-params/$id' - fullPath: '/api/parsed-params/$id' - preLoaderRoute: typeof ApiParsedParamsIdRouteImport - parentRoute: typeof rootRouteImport - } '/api/params/$foo/$bar': { id: '/api/params/$foo/$bar' path: '/$bar' @@ -300,13 +267,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiParamsFooBarRouteImport parentRoute: typeof ApiParamsFooRouteRoute } - '/api/parsed-params/$id/$childId': { - id: '/api/parsed-params/$id/$childId' - path: '/$childId' - fullPath: '/api/parsed-params/$id/$childId' - preLoaderRoute: typeof ApiParsedParamsIdChildIdRouteImport - parentRoute: typeof ApiParsedParamsIdRoute - } } } @@ -335,17 +295,6 @@ const ApiParamsFooRouteRouteChildren: ApiParamsFooRouteRouteChildren = { const ApiParamsFooRouteRouteWithChildren = ApiParamsFooRouteRoute._addFileChildren(ApiParamsFooRouteRouteChildren) -interface ApiParsedParamsIdRouteChildren { - ApiParsedParamsIdChildIdRoute: typeof ApiParsedParamsIdChildIdRoute -} - -const ApiParsedParamsIdRouteChildren: ApiParsedParamsIdRouteChildren = { - ApiParsedParamsIdChildIdRoute: ApiParsedParamsIdChildIdRoute, -} - -const ApiParsedParamsIdRouteWithChildren = - ApiParsedParamsIdRoute._addFileChildren(ApiParsedParamsIdRouteChildren) - const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, MethodsRouteRoute: MethodsRouteRouteWithChildren, @@ -356,7 +305,6 @@ const rootRouteChildren: RootRouteChildren = { ApiMiddlewareContextRoute: ApiMiddlewareContextRoute, ApiOnlyAnyRoute: ApiOnlyAnyRoute, ApiParamsFooRouteRoute: ApiParamsFooRouteRouteWithChildren, - ApiParsedParamsIdRoute: ApiParsedParamsIdRouteWithChildren, } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) diff --git a/e2e/react-start/server-routes/src/routes/api/parsed-params.$id.$childId.tsx b/e2e/react-start/server-routes/src/routes/api/parsed-params.$id.$childId.tsx deleted file mode 100644 index 06697a22cc..0000000000 --- a/e2e/react-start/server-routes/src/routes/api/parsed-params.$id.$childId.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { createMiddleware } from '@tanstack/react-start' - -const handleInvalidParams = createMiddleware().server(async ({ next }) => { - try { - return await next() - } catch (error) { - if (error instanceof Error && error.message === 'Invalid child id') { - return new Response(error.message, { status: 400 }) - } - throw error - } -}) - -export const Route = createFileRoute('/api/parsed-params/$id/$childId')({ - params: { - parse: (params) => { - const childId = Number(params.childId) - if (!Number.isFinite(childId)) { - throw new Error('Invalid child id') - } - return { childId } - }, - stringify: (params) => ({ childId: String(params.childId) }), - }, - server: { - handlers: ({ createHandlers }) => - createHandlers({ - GET: { - middleware: [handleInvalidParams], - handler: ({ params, request, next }) => { - if (new URL(request.url).searchParams.has('render')) { - return next({ context: { handlerParams: params } }) - } - const id: number = params.id - const childId: number = params.childId - return Response.json({ id, childId }) - }, - }, - }), - }, - loader: ({ params, serverContext }) => ({ - loaderParams: params, - handlerParams: serverContext?.handlerParams, - }), - component: () => ( -
-      {JSON.stringify(Route.useLoaderData())}
-    
- ), -}) diff --git a/e2e/react-start/server-routes/src/routes/api/parsed-params.$id.ts b/e2e/react-start/server-routes/src/routes/api/parsed-params.$id.ts deleted file mode 100644 index 0e5f0ab8a9..0000000000 --- a/e2e/react-start/server-routes/src/routes/api/parsed-params.$id.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/api/parsed-params/$id')({ - params: { - parse: (params) => ({ id: Number(params.id) }), - stringify: (params) => ({ id: String(params.id) }), - }, - server: { - handlers: { - GET: ({ params }) => { - const id: number = params.id - return Response.json({ id }) - }, - }, - }, -}) diff --git a/e2e/react-start/server-routes/tests/server-routes.spec.ts b/e2e/react-start/server-routes/tests/server-routes.spec.ts index 0ede9eaac8..97249fd733 100644 --- a/e2e/react-start/server-routes/tests/server-routes.spec.ts +++ b/e2e/react-start/server-routes/tests/server-routes.spec.ts @@ -1,46 +1,6 @@ import { expect } from '@playwright/test' import { test } from '@tanstack/router-e2e-utils' -test('server handlers receive parsed path params (issue #8431)', async ({ - request, -}) => { - const response = await request.get('/api/parsed-params/44') - - expect(response.status()).toBe(200) - expect(await response.json()).toEqual({ id: 44 }) -}) - -test('createHandlers receives parsed parent and child path params', async ({ - request, -}) => { - const response = await request.get('/api/parsed-params/44/2') - - expect(response.status()).toBe(200) - expect(await response.json()).toEqual({ id: 44, childId: 2 }) -}) - -test('handler middleware can catch path parameter parsing errors', async ({ - request, -}) => { - const response = await request.get('/api/parsed-params/44/invalid') - - expect(response.status()).toBe(400) - expect(await response.text()).toBe('Invalid child id') -}) - -test('parsed path params agree when a server handler defers to rendering', async ({ - page, -}) => { - await page.goto('/api/parsed-params/44/2?render') - - const result = page.getByTestId('parsed-params') - await expect(result).toBeVisible() - expect(JSON.parse((await result.textContent())!)).toEqual({ - loaderParams: { id: 44, childId: 2 }, - handlerParams: { id: 44, childId: 2 }, - }) -}) - test('merge-middleware-context', async ({ page }) => { await page.goto('/merge-middleware-context') diff --git a/e2e/react-start/session-handling/.gitignore b/e2e/react-start/session-handling/.gitignore deleted file mode 100644 index 16187ac1de..0000000000 --- a/e2e/react-start/session-handling/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -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/session-handling/.prettierignore b/e2e/react-start/session-handling/.prettierignore deleted file mode 100644 index 40a96e8819..0000000000 --- a/e2e/react-start/session-handling/.prettierignore +++ /dev/null @@ -1,4 +0,0 @@ -**/build -**/public -pnpm-lock.yaml -routeTree.gen.ts diff --git a/e2e/react-start/session-handling/package.json b/e2e/react-start/session-handling/package.json deleted file mode 100644 index 9dda8b2843..0000000000 --- a/e2e/react-start/session-handling/package.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "name": "tanstack-react-start-e2e-session-handling", - "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": { - "@hono/session": "0.2.1", - "@tanstack/react-router": "workspace:*", - "@tanstack/react-start": "workspace:*", - "hono": "4.13.9", - "hono-sessions": "0.8.1", - "iron-session": "9.0.1", - "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--rsbuild-ssr": { - "parallelism": false - } - }, - "metadata": { - "playwrightModes": [ - { - "toolchain": "vite", - "mode": "ssr" - }, - { - "toolchain": "rsbuild", - "mode": "ssr" - } - ] - } - } -} diff --git a/e2e/react-start/session-handling/playwright.config.ts b/e2e/react-start/session-handling/playwright.config.ts deleted file mode 100644 index 707af45de6..0000000000 --- a/e2e/react-start/session-handling/playwright.config.ts +++ /dev/null @@ -1,35 +0,0 @@ -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' - -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, - }, - }, - projects: [ - { - name: 'chromium', - use: { ...devices['Desktop Chrome'] }, - }, - ], -}) diff --git a/e2e/react-start/session-handling/rsbuild.config.ts b/e2e/react-start/session-handling/rsbuild.config.ts deleted file mode 100644 index af8c3df7d2..0000000000 --- a/e2e/react-start/session-handling/rsbuild.config.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { defineConfig } from '@rsbuild/core' -import { pluginReact } from '@rsbuild/plugin-react' -import { tanstackStart } from '@tanstack/react-start/plugin/rsbuild' - -const outDir = process.env.E2E_DIST_DIR ?? 'dist' - -export default defineConfig({ - plugins: [pluginReact(), tanstackStart()], - output: { - distPath: { - root: outDir, - }, - }, -}) diff --git a/e2e/react-start/session-handling/server.js b/e2e/react-start/session-handling/server.js deleted file mode 100644 index da874e85c7..0000000000 --- a/e2e/react-start/session-handling/server.js +++ /dev/null @@ -1,51 +0,0 @@ -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() { - 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/session-handling/src/components/DefaultCatchBoundary.tsx b/e2e/react-start/session-handling/src/components/DefaultCatchBoundary.tsx deleted file mode 100644 index f3d691814f..0000000000 --- a/e2e/react-start/session-handling/src/components/DefaultCatchBoundary.tsx +++ /dev/null @@ -1,20 +0,0 @@ -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/session-handling/src/components/NotFound.tsx b/e2e/react-start/session-handling/src/components/NotFound.tsx deleted file mode 100644 index 0b720f0e37..0000000000 --- a/e2e/react-start/session-handling/src/components/NotFound.tsx +++ /dev/null @@ -1,10 +0,0 @@ -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/session-handling/src/hono-sessions.ts b/e2e/react-start/session-handling/src/hono-sessions.ts deleted file mode 100644 index 63703a487b..0000000000 --- a/e2e/react-start/session-handling/src/hono-sessions.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { useSession as useHonoSession } from '@hono/session' -import { Hono } from 'hono' -import { setCookie } from 'hono/cookie' -import { CookieStore, sessionMiddleware } from 'hono-sessions' -import { sessionPassword } from './session' -import type { SessionEnv } from '@hono/session' -import type { Session } from 'hono-sessions' - -// These are genuine Hono applications. Start forwards the original Fetch -// Request and returns the Response after Hono has finished its middleware. -export const honoSessionApp = new Hono>() - .use( - '*', - useHonoSession({ - secret: new TextEncoder().encode('0123456789abcdef0123456789abcdef'), - duration: { absolute: 3600 }, - }), - ) - .get('/api/session-hono', async (c) => - c.json({ data: (await c.var.session.get()) ?? {} }), - ) - .post('/api/session-hono', async (c) => { - const data = await c.req.json<{ user: string }>() - await c.var.session.update({ user: data.user }) - setCookie(c, 'hono-extra', '1', { - path: '/', - expires: new Date(Date.now() + 24 * 60 * 60 * 1000), - }) - return c.json({ data: c.var.session.data }) - }) - .delete('/api/session-hono', (c) => { - c.var.session.delete() - return c.json({ cleared: true }) - }) - -export const communitySessionApp = new Hono<{ - Variables: { - session: Session<{ user: string }> - session_key_rotation: boolean - } -}>() - .use( - '*', - sessionMiddleware({ - store: new CookieStore(), - encryptionKey: sessionPassword, - expireAfterSeconds: 3600, - sessionCookieName: 'hono-community', - cookieOptions: { - path: '/', - httpOnly: true, - sameSite: 'Lax', - secure: false, - }, - }), - ) - .get('/api/session-hono-community', (c) => - c.json({ data: { user: c.var.session.get('user') } }), - ) - .post('/api/session-hono-community', async (c) => { - const data = await c.req.json<{ user: string }>() - c.var.session.set('user', data.user) - return c.json({ data: { user: c.var.session.get('user') } }) - }) - .delete('/api/session-hono-community', (c) => { - c.var.session.deleteSession() - return c.json({ cleared: true }) - }) diff --git a/e2e/react-start/session-handling/src/routeTree.gen.ts b/e2e/react-start/session-handling/src/routeTree.gen.ts deleted file mode 100644 index 5ecad97ab4..0000000000 --- a/e2e/react-start/session-handling/src/routeTree.gen.ts +++ /dev/null @@ -1,346 +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 IndexRouteImport } from './routes/index' -import { Route as ServerFunctionsRouteImport } from './routes/server-functions' -import { Route as SsrRouteImport } from './routes/ssr' -import { Route as ApiSessionRouteImport } from './routes/api/session' -import { Route as ApiSessionClearRouteImport } from './routes/api/session-clear' -import { Route as ApiSessionFlashRouteImport } from './routes/api/session-flash' -import { Route as ApiSessionHelperCookieRouteImport } from './routes/api/session-helper-cookie' -import { Route as ApiSessionHonoRouteImport } from './routes/api/session-hono' -import { Route as ApiSessionHonoCommunityRouteImport } from './routes/api/session-hono-community' -import { Route as ApiSessionHonoCookieRouteImport } from './routes/api/session-hono-cookie' -import { Route as ApiSessionIronRouteImport } from './routes/api/session-iron' -import { Route as ApiSessionMiddlewareRouteImport } from './routes/api/session-middleware' -import { Route as ApiSessionNamedRouteImport } from './routes/api/session-named' -import { Route as ApiSessionRedirectRouteImport } from './routes/api/session-redirect' - -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 ApiSessionRoute = ApiSessionRouteImport.update({ - id: '/api/session', - path: '/api/session', - getParentRoute: () => rootRouteImport, -} as any) -const ApiSessionClearRoute = ApiSessionClearRouteImport.update({ - id: '/api/session-clear', - path: '/api/session-clear', - getParentRoute: () => rootRouteImport, -} as any) -const ApiSessionFlashRoute = ApiSessionFlashRouteImport.update({ - id: '/api/session-flash', - path: '/api/session-flash', - getParentRoute: () => rootRouteImport, -} as any) -const ApiSessionHelperCookieRoute = ApiSessionHelperCookieRouteImport.update({ - id: '/api/session-helper-cookie', - path: '/api/session-helper-cookie', - getParentRoute: () => rootRouteImport, -} as any) -const ApiSessionHonoRoute = ApiSessionHonoRouteImport.update({ - id: '/api/session-hono', - path: '/api/session-hono', - getParentRoute: () => rootRouteImport, -} as any) -const ApiSessionHonoCommunityRoute = ApiSessionHonoCommunityRouteImport.update({ - id: '/api/session-hono-community', - path: '/api/session-hono-community', - getParentRoute: () => rootRouteImport, -} as any) -const ApiSessionHonoCookieRoute = ApiSessionHonoCookieRouteImport.update({ - id: '/api/session-hono-cookie', - path: '/api/session-hono-cookie', - getParentRoute: () => rootRouteImport, -} as any) -const ApiSessionIronRoute = ApiSessionIronRouteImport.update({ - id: '/api/session-iron', - path: '/api/session-iron', - getParentRoute: () => rootRouteImport, -} as any) -const ApiSessionMiddlewareRoute = ApiSessionMiddlewareRouteImport.update({ - id: '/api/session-middleware', - path: '/api/session-middleware', - getParentRoute: () => rootRouteImport, -} as any) -const ApiSessionNamedRoute = ApiSessionNamedRouteImport.update({ - id: '/api/session-named', - path: '/api/session-named', - getParentRoute: () => rootRouteImport, -} as any) -const ApiSessionRedirectRoute = ApiSessionRedirectRouteImport.update({ - id: '/api/session-redirect', - path: '/api/session-redirect', - getParentRoute: () => rootRouteImport, -} as any) - -export interface FileRoutesByFullPath { - '/': typeof IndexRoute - '/server-functions': typeof ServerFunctionsRoute - '/ssr': typeof SsrRoute - '/api/session': typeof ApiSessionRoute - '/api/session-clear': typeof ApiSessionClearRoute - '/api/session-flash': typeof ApiSessionFlashRoute - '/api/session-helper-cookie': typeof ApiSessionHelperCookieRoute - '/api/session-hono': typeof ApiSessionHonoRoute - '/api/session-hono-community': typeof ApiSessionHonoCommunityRoute - '/api/session-hono-cookie': typeof ApiSessionHonoCookieRoute - '/api/session-iron': typeof ApiSessionIronRoute - '/api/session-middleware': typeof ApiSessionMiddlewareRoute - '/api/session-named': typeof ApiSessionNamedRoute - '/api/session-redirect': typeof ApiSessionRedirectRoute -} -export interface FileRoutesByTo { - '/': typeof IndexRoute - '/server-functions': typeof ServerFunctionsRoute - '/ssr': typeof SsrRoute - '/api/session': typeof ApiSessionRoute - '/api/session-clear': typeof ApiSessionClearRoute - '/api/session-flash': typeof ApiSessionFlashRoute - '/api/session-helper-cookie': typeof ApiSessionHelperCookieRoute - '/api/session-hono': typeof ApiSessionHonoRoute - '/api/session-hono-community': typeof ApiSessionHonoCommunityRoute - '/api/session-hono-cookie': typeof ApiSessionHonoCookieRoute - '/api/session-iron': typeof ApiSessionIronRoute - '/api/session-middleware': typeof ApiSessionMiddlewareRoute - '/api/session-named': typeof ApiSessionNamedRoute - '/api/session-redirect': typeof ApiSessionRedirectRoute -} -export interface FileRoutesById { - __root__: typeof rootRouteImport - '/': typeof IndexRoute - '/server-functions': typeof ServerFunctionsRoute - '/ssr': typeof SsrRoute - '/api/session': typeof ApiSessionRoute - '/api/session-clear': typeof ApiSessionClearRoute - '/api/session-flash': typeof ApiSessionFlashRoute - '/api/session-helper-cookie': typeof ApiSessionHelperCookieRoute - '/api/session-hono': typeof ApiSessionHonoRoute - '/api/session-hono-community': typeof ApiSessionHonoCommunityRoute - '/api/session-hono-cookie': typeof ApiSessionHonoCookieRoute - '/api/session-iron': typeof ApiSessionIronRoute - '/api/session-middleware': typeof ApiSessionMiddlewareRoute - '/api/session-named': typeof ApiSessionNamedRoute - '/api/session-redirect': typeof ApiSessionRedirectRoute -} -export interface FileRouteTypes { - fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/server-functions' - | '/ssr' - | '/api/session' - | '/api/session-clear' - | '/api/session-flash' - | '/api/session-helper-cookie' - | '/api/session-hono' - | '/api/session-hono-community' - | '/api/session-hono-cookie' - | '/api/session-iron' - | '/api/session-middleware' - | '/api/session-named' - | '/api/session-redirect' - fileRoutesByTo: FileRoutesByTo - to: - | '/' - | '/server-functions' - | '/ssr' - | '/api/session' - | '/api/session-clear' - | '/api/session-flash' - | '/api/session-helper-cookie' - | '/api/session-hono' - | '/api/session-hono-community' - | '/api/session-hono-cookie' - | '/api/session-iron' - | '/api/session-middleware' - | '/api/session-named' - | '/api/session-redirect' - id: - | '__root__' - | '/' - | '/server-functions' - | '/ssr' - | '/api/session' - | '/api/session-clear' - | '/api/session-flash' - | '/api/session-helper-cookie' - | '/api/session-hono' - | '/api/session-hono-community' - | '/api/session-hono-cookie' - | '/api/session-iron' - | '/api/session-middleware' - | '/api/session-named' - | '/api/session-redirect' - fileRoutesById: FileRoutesById -} -export interface RootRouteChildren { - IndexRoute: typeof IndexRoute - ServerFunctionsRoute: typeof ServerFunctionsRoute - SsrRoute: typeof SsrRoute - ApiSessionRoute: typeof ApiSessionRoute - ApiSessionClearRoute: typeof ApiSessionClearRoute - ApiSessionFlashRoute: typeof ApiSessionFlashRoute - ApiSessionHelperCookieRoute: typeof ApiSessionHelperCookieRoute - ApiSessionHonoRoute: typeof ApiSessionHonoRoute - ApiSessionHonoCommunityRoute: typeof ApiSessionHonoCommunityRoute - ApiSessionHonoCookieRoute: typeof ApiSessionHonoCookieRoute - ApiSessionIronRoute: typeof ApiSessionIronRoute - ApiSessionMiddlewareRoute: typeof ApiSessionMiddlewareRoute - ApiSessionNamedRoute: typeof ApiSessionNamedRoute - ApiSessionRedirectRoute: typeof ApiSessionRedirectRoute -} - -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 - } - '/api/session': { - id: '/api/session' - path: '/api/session' - fullPath: '/api/session' - preLoaderRoute: typeof ApiSessionRouteImport - parentRoute: typeof rootRouteImport - } - '/api/session-clear': { - id: '/api/session-clear' - path: '/api/session-clear' - fullPath: '/api/session-clear' - preLoaderRoute: typeof ApiSessionClearRouteImport - parentRoute: typeof rootRouteImport - } - '/api/session-flash': { - id: '/api/session-flash' - path: '/api/session-flash' - fullPath: '/api/session-flash' - preLoaderRoute: typeof ApiSessionFlashRouteImport - parentRoute: typeof rootRouteImport - } - '/api/session-helper-cookie': { - id: '/api/session-helper-cookie' - path: '/api/session-helper-cookie' - fullPath: '/api/session-helper-cookie' - preLoaderRoute: typeof ApiSessionHelperCookieRouteImport - parentRoute: typeof rootRouteImport - } - '/api/session-hono': { - id: '/api/session-hono' - path: '/api/session-hono' - fullPath: '/api/session-hono' - preLoaderRoute: typeof ApiSessionHonoRouteImport - parentRoute: typeof rootRouteImport - } - '/api/session-hono-community': { - id: '/api/session-hono-community' - path: '/api/session-hono-community' - fullPath: '/api/session-hono-community' - preLoaderRoute: typeof ApiSessionHonoCommunityRouteImport - parentRoute: typeof rootRouteImport - } - '/api/session-hono-cookie': { - id: '/api/session-hono-cookie' - path: '/api/session-hono-cookie' - fullPath: '/api/session-hono-cookie' - preLoaderRoute: typeof ApiSessionHonoCookieRouteImport - parentRoute: typeof rootRouteImport - } - '/api/session-iron': { - id: '/api/session-iron' - path: '/api/session-iron' - fullPath: '/api/session-iron' - preLoaderRoute: typeof ApiSessionIronRouteImport - parentRoute: typeof rootRouteImport - } - '/api/session-middleware': { - id: '/api/session-middleware' - path: '/api/session-middleware' - fullPath: '/api/session-middleware' - preLoaderRoute: typeof ApiSessionMiddlewareRouteImport - parentRoute: typeof rootRouteImport - } - '/api/session-named': { - id: '/api/session-named' - path: '/api/session-named' - fullPath: '/api/session-named' - preLoaderRoute: typeof ApiSessionNamedRouteImport - parentRoute: typeof rootRouteImport - } - '/api/session-redirect': { - id: '/api/session-redirect' - path: '/api/session-redirect' - fullPath: '/api/session-redirect' - preLoaderRoute: typeof ApiSessionRedirectRouteImport - parentRoute: typeof rootRouteImport - } - } -} - -const rootRouteChildren: RootRouteChildren = { - IndexRoute: IndexRoute, - ServerFunctionsRoute: ServerFunctionsRoute, - SsrRoute: SsrRoute, - ApiSessionRoute: ApiSessionRoute, - ApiSessionClearRoute: ApiSessionClearRoute, - ApiSessionFlashRoute: ApiSessionFlashRoute, - ApiSessionHelperCookieRoute: ApiSessionHelperCookieRoute, - ApiSessionHonoRoute: ApiSessionHonoRoute, - ApiSessionHonoCommunityRoute: ApiSessionHonoCommunityRoute, - ApiSessionHonoCookieRoute: ApiSessionHonoCookieRoute, - ApiSessionIronRoute: ApiSessionIronRoute, - ApiSessionMiddlewareRoute: ApiSessionMiddlewareRoute, - ApiSessionNamedRoute: ApiSessionNamedRoute, - ApiSessionRedirectRoute: ApiSessionRedirectRoute, -} -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/session-handling/src/router.tsx b/e2e/react-start/session-handling/src/router.tsx deleted file mode 100644 index c5c2209e5a..0000000000 --- a/e2e/react-start/session-handling/src/router.tsx +++ /dev/null @@ -1,13 +0,0 @@ -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/session-handling/src/routes/__root.tsx b/e2e/react-start/session-handling/src/routes/__root.tsx deleted file mode 100644 index e5e5f4cd24..0000000000 --- a/e2e/react-start/session-handling/src/routes/__root.tsx +++ /dev/null @@ -1,59 +0,0 @@ -/// -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/session-handling/src/routes/api/session-clear.ts b/e2e/react-start/session-handling/src/routes/api/session-clear.ts deleted file mode 100644 index 44b83e58ac..0000000000 --- a/e2e/react-start/session-handling/src/routes/api/session-clear.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { destroySession } from '~/session' - -export const Route = createFileRoute('/api/session-clear')({ - server: { - handlers: { - POST: async () => { - await destroySession() - return Response.json({ cleared: true }) - }, - }, - }, -}) diff --git a/e2e/react-start/session-handling/src/routes/api/session-flash.ts b/e2e/react-start/session-handling/src/routes/api/session-flash.ts deleted file mode 100644 index 7b494d5050..0000000000 --- a/e2e/react-start/session-handling/src/routes/api/session-flash.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { readSession } from '~/session' - -export const Route = createFileRoute('/api/session-flash')({ - server: { - handlers: { - POST: async () => { - const session = await readSession() - session.notice = 'Saved successfully' - await session.save() - return Response.json({ saved: true }) - }, - GET: async () => { - const session = await readSession() - const notice = session.notice ?? null - delete session.notice - await session.save() - return Response.json({ notice }) - }, - }, - }, -}) diff --git a/e2e/react-start/session-handling/src/routes/api/session-helper-cookie.ts b/e2e/react-start/session-handling/src/routes/api/session-helper-cookie.ts deleted file mode 100644 index 24711e227c..0000000000 --- a/e2e/react-start/session-handling/src/routes/api/session-helper-cookie.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { setCookie } from '@tanstack/react-start/server' -import { readJson, updateSessionData } from '~/session' - -export const Route = createFileRoute('/api/session-helper-cookie')({ - server: { - handlers: { - POST: async ({ request }) => { - const session = await updateSessionData(await readJson(request)) - setCookie('helper-session', '1', { path: '/' }) - const headers = new Headers() - headers.append( - 'Set-Cookie', - 'returned-session=1; Path=/; Expires=Tue, 01 Jan 2030 00:00:00 GMT', - ) - headers.append('Set-Cookie', 'returned-extra=2; Path=/') - return Response.json(session, { headers }) - }, - }, - }, -}) diff --git a/e2e/react-start/session-handling/src/routes/api/session-hono-community.ts b/e2e/react-start/session-handling/src/routes/api/session-hono-community.ts deleted file mode 100644 index deb93ea549..0000000000 --- a/e2e/react-start/session-handling/src/routes/api/session-hono-community.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { setCookie } from '@tanstack/react-start/server' -import { communitySessionApp } from '~/hono-sessions' - -function handle({ request }: { request: Request }) { - setCookie('start-side', 'coexists', { path: '/' }) - return communitySessionApp.fetch(request) -} - -export const Route = createFileRoute('/api/session-hono-community')({ - server: { handlers: { GET: handle, POST: handle, DELETE: handle } }, -}) diff --git a/e2e/react-start/session-handling/src/routes/api/session-hono-cookie.ts b/e2e/react-start/session-handling/src/routes/api/session-hono-cookie.ts deleted file mode 100644 index fb99ce6196..0000000000 --- a/e2e/react-start/session-handling/src/routes/api/session-hono-cookie.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { generateCookie, generateSignedCookie } from 'hono/cookie' -import { parseSigned } from 'hono/utils/cookie' -import { - appendResponseHeader, - getRequestHeader, - setCookie, -} from '@tanstack/react-start/server' -import { sessionPassword } from '~/session' - -// These Hono exports work with strings; they do not require a Hono Context. -// They provide signed cookies, not session storage or server-side expiration. -export const Route = createFileRoute('/api/session-hono-cookie')({ - server: { - handlers: { - GET: async () => { - const values = await parseSigned( - getRequestHeader('cookie') ?? '', - sessionPassword, - 'hono-signed', - ) - return Response.json({ user: values['hono-signed'] || null }) - }, - POST: async ({ request }) => { - const data = await request.json() - appendResponseHeader( - 'set-cookie', - await generateSignedCookie( - 'hono-signed', - data.user, - sessionPassword, - { - httpOnly: true, - sameSite: 'Lax', - path: '/', - maxAge: 3600, - }, - ), - ) - setCookie('start-side', 'coexists', { path: '/' }) - return Response.json({ user: data.user }) - }, - DELETE: () => { - appendResponseHeader( - 'set-cookie', - generateCookie('hono-signed', '', { path: '/', maxAge: 0 }), - ) - return Response.json({ cleared: true }) - }, - }, - }, -}) diff --git a/e2e/react-start/session-handling/src/routes/api/session-hono.ts b/e2e/react-start/session-handling/src/routes/api/session-hono.ts deleted file mode 100644 index fdfd172bf0..0000000000 --- a/e2e/react-start/session-handling/src/routes/api/session-hono.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { setCookie } from '@tanstack/react-start/server' -import { honoSessionApp } from '~/hono-sessions' - -function handle({ request }: { request: Request }) { - setCookie('start-side', 'coexists', { path: '/' }) - return honoSessionApp.fetch(request) -} - -export const Route = createFileRoute('/api/session-hono')({ - server: { handlers: { GET: handle, POST: handle, DELETE: handle } }, -}) diff --git a/e2e/react-start/session-handling/src/routes/api/session-iron.ts b/e2e/react-start/session-handling/src/routes/api/session-iron.ts deleted file mode 100644 index 83337d1dfb..0000000000 --- a/e2e/react-start/session-handling/src/routes/api/session-iron.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { readJson, readSession } from '~/session' - -export const Route = createFileRoute('/api/session-iron')({ - server: { - handlers: { - GET: async () => - Response.json({ data: { ...(await readSession('iron-session')) } }), - POST: async ({ request }) => { - const session = await readSession('iron-session') - const data = await readJson(request) - if (typeof data.user === 'string') { - session.user = data.user - } - if (typeof data.token === 'string') { - session.token = data.token - } - await session.save() - return Response.json({ data: { ...session } }) - }, - DELETE: async () => { - const session = await readSession('iron-session') - session.destroy() - return Response.json({ cleared: true }) - }, - }, - }, -}) diff --git a/e2e/react-start/session-handling/src/routes/api/session-middleware.ts b/e2e/react-start/session-handling/src/routes/api/session-middleware.ts deleted file mode 100644 index 4090262477..0000000000 --- a/e2e/react-start/session-handling/src/routes/api/session-middleware.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { sessionMiddleware } from '~/start' - -export const Route = createFileRoute('/api/session-middleware')({ - server: { - middleware: [sessionMiddleware], - handlers: { - GET: ({ context }) => Response.json({ data: { ...context.session } }), - }, - }, -}) diff --git a/e2e/react-start/session-handling/src/routes/api/session-named.ts b/e2e/react-start/session-handling/src/routes/api/session-named.ts deleted file mode 100644 index 5acb82446c..0000000000 --- a/e2e/react-start/session-handling/src/routes/api/session-named.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { readJson, readSession, updateSessionData } from '~/session' - -function getName(request: Request) { - return new URL(request.url).searchParams.get('name') || 'app-named' -} - -export const Route = createFileRoute('/api/session-named')({ - server: { - handlers: { - GET: async ({ request }) => - Response.json({ - data: { ...(await readSession(getName(request))) }, - }), - POST: async ({ request }) => - Response.json( - await updateSessionData(await readJson(request), getName(request)), - ), - }, - }, -}) diff --git a/e2e/react-start/session-handling/src/routes/api/session-redirect.ts b/e2e/react-start/session-handling/src/routes/api/session-redirect.ts deleted file mode 100644 index 5280d7e6bc..0000000000 --- a/e2e/react-start/session-handling/src/routes/api/session-redirect.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { createFileRoute, redirect } from '@tanstack/react-router' -import { updateSessionData } from '~/session' - -export const Route = createFileRoute('/api/session-redirect')({ - server: { - handlers: { - POST: async () => { - await updateSessionData({ user: 'redirected' }) - throw redirect({ href: '/api/session', statusCode: 303 }) - }, - }, - }, -}) diff --git a/e2e/react-start/session-handling/src/routes/api/session.ts b/e2e/react-start/session-handling/src/routes/api/session.ts deleted file mode 100644 index 4696cf80a4..0000000000 --- a/e2e/react-start/session-handling/src/routes/api/session.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { readJson, readSession, updateSessionData } from '~/session' - -export const Route = createFileRoute('/api/session')({ - server: { - handlers: { - GET: async () => Response.json({ data: { ...(await readSession()) } }), - POST: async ({ request }) => - Response.json(await updateSessionData(await readJson(request))), - }, - }, -}) diff --git a/e2e/react-start/session-handling/src/routes/index.tsx b/e2e/react-start/session-handling/src/routes/index.tsx deleted file mode 100644 index 9dc929d5bb..0000000000 --- a/e2e/react-start/session-handling/src/routes/index.tsx +++ /dev/null @@ -1,14 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' - -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return ( -
-

Session Handling E2E

-

This app contains HTTP-level session tests.

-
- ) -} diff --git a/e2e/react-start/session-handling/src/routes/server-functions.tsx b/e2e/react-start/session-handling/src/routes/server-functions.tsx deleted file mode 100644 index bce5419c84..0000000000 --- a/e2e/react-start/session-handling/src/routes/server-functions.tsx +++ /dev/null @@ -1,85 +0,0 @@ -import { ClientOnly, createFileRoute, redirect } from '@tanstack/react-router' -import { createServerFn, useServerFn } from '@tanstack/react-start' -import * as React from 'react' -import { destroySession, readSession, updateSessionData } from '~/session' - -const updateSessionFn = createServerFn({ method: 'POST' }).handler(async () => { - const data = { serverFn: 'updated' } - await updateSessionData(data) - return { data } -}) -const readSessionFn = createServerFn().handler(async () => { - const serverFn = (await readSession()).serverFn - return { data: typeof serverFn === 'string' ? { serverFn } : {} } -}) -const clearSessionFn = createServerFn({ method: 'POST' }).handler(async () => { - await destroySession() - return { cleared: true } -}) -const redirectSessionFn = createServerFn({ method: 'POST' }).handler( - async () => { - await updateSessionData({ serverFn: 'redirected' }) - throw redirect({ to: '/ssr' }) - }, -) -const errorSessionFn = createServerFn({ method: 'POST' }).handler(async () => { - await updateSessionData({ serverFn: 'error-persisted' }) - throw new Error('Expected external session error') -}) -const ironSessionFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await readSession('iron-session') - session.user = 'iron-server-function' - await session.save() - return { user: session.user } -}) - -export const Route = createFileRoute('/server-functions')({ - component: ServerFunctions, -}) - -function ServerFunctions() { - return ( -
-

External Session 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/session-handling/src/routes/ssr.tsx b/e2e/react-start/session-handling/src/routes/ssr.tsx deleted file mode 100644 index 0339a4f813..0000000000 --- a/e2e/react-start/session-handling/src/routes/ssr.tsx +++ /dev/null @@ -1,26 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { createServerFn } from '@tanstack/react-start' -import { readSession } from '~/session' - -const loadSession = createServerFn().handler(async () => { - const session = await readSession() - const count = Number(session.ssrCount ?? 0) + 1 - session.ssrCount = count - await session.save() - return { count } -}) - -export const Route = createFileRoute('/ssr')({ - loader: () => loadSession(), - component: SsrRoute, -}) - -function SsrRoute() { - const data = Route.useLoaderData() - return ( -
-

External Session SSR

-

{String(data.count)}

-
- ) -} diff --git a/e2e/react-start/session-handling/src/session.ts b/e2e/react-start/session-handling/src/session.ts deleted file mode 100644 index f223c42cbd..0000000000 --- a/e2e/react-start/session-handling/src/session.ts +++ /dev/null @@ -1,47 +0,0 @@ -import { getIronSession } from 'iron-session' -import { getCookie, setCookie } from '@tanstack/react-start/server' - -// Fixed secrets and insecure cookies are only for this local HTTP test fixture. -export const sessionPassword = 'start-external-session-test-only-'.repeat(2) -export type SessionData = { - user?: string - token?: string - serverFn?: string - middleware?: string - notice?: string - ssrCount?: number -} - -export async function updateSessionData(data: SessionData, name?: string) { - const session = await readSession(name) - Object.assign(session, data) - await session.save() - return { data: { ...session } } -} - -export async function destroySession() { - const session = await readSession() - session.destroy() -} - -export function readSession(cookieName = 'app-session') { - return getIronSession( - { read: getCookie, write: setCookie }, - { - cookieName, - password: sessionPassword, - ttl: 3600, - chunk: true, - cookieOptions: { - secure: false, - httpOnly: true, - sameSite: 'lax', - path: '/', - }, - }, - ) -} - -export async function readJson(request: Request): Promise { - return request.json() -} diff --git a/e2e/react-start/session-handling/src/start.ts b/e2e/react-start/session-handling/src/start.ts deleted file mode 100644 index a9571afabb..0000000000 --- a/e2e/react-start/session-handling/src/start.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { createMiddleware, createStart } from '@tanstack/react-start' -import { readSession } from './session' - -export const sessionMiddleware = createMiddleware().server( - async ({ next, request }) => { - const session = await readSession() - const scenario = request.headers.get('x-session-middleware') - if (scenario === 'before') { - session.middleware = 'before' - } - const result = await next({ context: { session } }) - if (scenario === 'after') { - session.middleware = 'after' - } - if (scenario) { - await session.save() - } - return result - }, -) - -export const startInstance = createStart(() => ({})) diff --git a/e2e/react-start/session-handling/src/styles/app.css b/e2e/react-start/session-handling/src/styles/app.css deleted file mode 100644 index a38fb439a6..0000000000 --- a/e2e/react-start/session-handling/src/styles/app.css +++ /dev/null @@ -1,12 +0,0 @@ -html { - color-scheme: light dark; - font-family: system-ui, sans-serif; -} - -body { - margin: 0; -} - -main { - padding: 16px; -} diff --git a/e2e/react-start/session-handling/tests/session-handling.spec.ts b/e2e/react-start/session-handling/tests/session-handling.spec.ts deleted file mode 100644 index aaa975ccef..0000000000 --- a/e2e/react-start/session-handling/tests/session-handling.spec.ts +++ /dev/null @@ -1,334 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' -import type { APIResponse, Page, Response } from '@playwright/test' - -async function setCookieValues(response: APIResponse | Response) { - return (await Promise.resolve(response.headersArray())) - .filter((item) => item.name.toLowerCase() === 'set-cookie') - .map((item) => item.value) -} - -function expectCookie(cookies: Array, name: string) { - expect(cookies.some((cookie) => cookie.startsWith(`${name}=`))).toBe(true) -} - -async function expectResult(page: Page, name: string, value: string) { - await expect( - page.getByTestId(`server-function-${name}-result`), - ).toContainText(value) -} - -async function visitFunctions(page: Page) { - await page.goto('/server-functions') - await expect(page.getByTestId('server-functions-hydrated')).toBeAttached() -} - -test.describe('iron-session in Start', () => { - test('does not write cookies on a read and persists committed mutations', async ({ - request, - }) => { - const initial = await request.get('/api/session') - expect(await initial.json()).toEqual({ data: {} }) - expect(await setCookieValues(initial)).toEqual([]) - - const update = await request.post('/api/session', { - data: { user: 'tanner' }, - }) - const cookies = await setCookieValues(update) - expectCookie(cookies, 'app-session') - expect(cookies[0]).toContain('HttpOnly') - expect(cookies[0]).toContain('SameSite=Lax') - expect(cookies[0]).toContain('Path=/') - - const read = await request.get('/api/session') - expect(await read.json()).toEqual({ data: { user: 'tanner' } }) - expect(await setCookieValues(read)).toEqual([]) - }) - - test('destroy logs out the cookie jar', async ({ request }) => { - await request.post('/api/session', { data: { user: 'clear-me' } }) - const clear = await request.post('/api/session-clear') - const cookies = await setCookieValues(clear) - expectCookie(cookies, 'app-session') - expect(cookies[0]).toContain('Max-Age=0') - expect(await (await request.get('/api/session')).json()).toEqual({ - data: {}, - }) - }) - - test('independent named sessions coexist', async ({ request }) => { - await request.post('/api/session', { data: { user: 'default-user' } }) - await request.post('/api/session-named?name=app-account', { - data: { user: 'account-user' }, - }) - expect(await (await request.get('/api/session')).json()).toEqual({ - data: { user: 'default-user' }, - }) - expect( - await (await request.get('/api/session-named?name=app-account')).json(), - ).toEqual({ data: { user: 'account-user' } }) - }) - - test('invalid input does not become authenticated session data', async ({ - request, - }) => { - const response = await request.get('/api/session', { - headers: { cookie: 'app-session=invalid' }, - }) - expect(await response.json()).toEqual({ data: {} }) - expect(await setCookieValues(response)).toEqual([]) - }) - - test('preserves library, helper, and returned cookies including Expires commas', async ({ - request, - }) => { - const response = await request.post('/api/session-helper-cookie', { - data: { user: 'coexists' }, - }) - const cookies = await setCookieValues(response) - expect(cookies).toHaveLength(4) - for (const name of [ - 'app-session', - 'helper-session', - 'returned-session', - 'returned-extra', - ]) { - expectCookie(cookies, name) - } - expect( - cookies.find((cookie) => cookie.startsWith('returned-session=')), - ).toContain('Expires=Tue, 01 Jan 2030 00:00:00 GMT') - expect(await (await request.get('/api/session')).json()).toEqual({ - data: { user: 'coexists' }, - }) - }) - - test('a notification is consumed once after its deletion is saved', async ({ - request, - }) => { - await request.post('/api/session-flash') - expect(await (await request.get('/api/session-flash')).json()).toEqual({ - notice: 'Saved successfully', - }) - expect(await (await request.get('/api/session-flash')).json()).toEqual({ - notice: null, - }) - }) - - test('session mutations survive a thrown Start redirect', async ({ - request, - }) => { - const response = await request.post('/api/session-redirect', { - maxRedirects: 0, - }) - expect(response.status()).toBe(303) - expect(response.headers().location).toBe('/api/session') - expectCookie(await setCookieValues(response), 'app-session') - expect(await (await request.get('/api/session')).json()).toEqual({ - data: { user: 'redirected' }, - }) - }) - - test('middleware shares the session object and commits changes after next', async ({ - request, - }) => { - const before = await request.get('/api/session-middleware', { - headers: { 'x-session-middleware': 'before' }, - }) - expect(await before.json()).toEqual({ data: { middleware: 'before' } }) - expectCookie(await setCookieValues(before), 'app-session') - const after = await request.get('/api/session-middleware', { - headers: { 'x-session-middleware': 'after' }, - }) - expect(await after.json()).toEqual({ data: { middleware: 'before' } }) - expect(await (await request.get('/api/session')).json()).toEqual({ - data: { middleware: 'after' }, - }) - }) -}) - -test.describe('iron-session cookie jar adapter', () => { - test('saves, reads, and destroys encrypted sessions using Start cookie helpers', async ({ - request, - }) => { - const saved = await request.post('/api/session-iron', { - data: { user: 'iron-user' }, - }) - expectCookie(await setCookieValues(saved), 'iron-session') - expect(await (await request.get('/api/session-iron')).json()).toEqual({ - data: { user: 'iron-user' }, - }) - await request.delete('/api/session-iron') - expect(await (await request.get('/api/session-iron')).json()).toEqual({ - data: {}, - }) - }) - - test('roundtrips chunked cookies and deletes obsolete chunks after shrinking', async ({ - request, - }) => { - const large = await request.post('/api/session-iron', { - data: { token: 'x'.repeat(5000) }, - }) - const cookies = await setCookieValues(large) - expectCookie(cookies, 'iron-session.0') - expectCookie(cookies, 'iron-session.1') - expect( - (await (await request.get('/api/session-iron')).json()).data.token, - ).toHaveLength(5000) - const small = await request.post('/api/session-iron', { - data: { token: 'tiny' }, - }) - const smallCookies = await setCookieValues(small) - expectCookie(smallCookies, 'iron-session') - expect( - smallCookies.some( - (cookie) => - cookie.startsWith('iron-session.1=') && /Max-Age=0/i.test(cookie), - ), - ).toBe(true) - expect( - (await (await request.get('/api/session-iron')).json()).data.token, - ).toBe('tiny') - }) -}) - -test.describe('Hono applications mounted in Start server routes', () => { - for (const [path, cookieName] of [ - ['session-hono', 'sid'], - ['session-hono-community', 'hono-community'], - ]) { - test(`${path} persists and clears sessions after Hono middleware completes`, async ({ - request, - }) => { - const saved = await request.post(`/api/${path}`, { - data: { user: 'hono-user' }, - }) - expect(saved.status()).toBe(200) - const cookies = await setCookieValues(saved) - expectCookie(cookies, cookieName!) - expectCookie(cookies, 'start-side') - if (path === 'session-hono') { - expectCookie(cookies, 'hono-extra') - } - expect((await (await request.get(`/api/${path}`)).json()).data.user).toBe( - 'hono-user', - ) - await request.delete(`/api/${path}`) - expect( - (await (await request.get(`/api/${path}`)).json()).data.user ?? null, - ).toBeNull() - }) - } - - test('Hono context-free signed cookie helpers work directly in Start', async ({ - request, - }) => { - const saved = await request.post('/api/session-hono-cookie', { - data: { user: 'signed-user' }, - }) - expectCookie(await setCookieValues(saved), 'hono-signed') - expectCookie(await setCookieValues(saved), 'start-side') - expect( - await (await request.get('/api/session-hono-cookie')).json(), - ).toEqual({ user: 'signed-user' }) - await request.delete('/api/session-hono-cookie') - expect( - await (await request.get('/api/session-hono-cookie')).json(), - ).toEqual({ user: null }) - }) -}) - -test.describe('document and server function sessions', () => { - test('SSR loader commits persist across browser reloads', async ({ - page, - }) => { - await page.goto('/ssr') - await expect(page.getByTestId('ssr-session-count')).toHaveText('1') - await page.reload() - await expect(page.getByTestId('ssr-session-count')).toHaveText('2') - }) - - test('server functions update, read, and clear the browser session', async ({ - page, - }) => { - await visitFunctions(page) - const responsePromise = page.waitForResponse((response) => - response.url().includes('/_serverFn/'), - ) - await page.getByTestId('server-function-update').click() - expectCookie(await setCookieValues(await responsePromise), 'app-session') - await expectResult(page, 'update', '"serverFn":"updated"') - await page.getByTestId('server-function-read').click() - await expectResult(page, 'read', '"serverFn":"updated"') - await page.getByTestId('server-function-clear').click() - await expectResult(page, 'clear', '"cleared":true') - await page.getByTestId('server-function-read').click() - await expectResult(page, 'read', '"data":{}') - }) - - test('server function redirects retain committed session data', async ({ - page, - }) => { - await visitFunctions(page) - await page.getByTestId('server-function-redirect').click() - await expect(page).toHaveURL(/\/ssr$/) - await expect(page.getByTestId('ssr-session-count')).toHaveText('1') - expect( - (await (await page.request.get('/api/session')).json()).data.serverFn, - ).toBe('redirected') - }) - - test.describe('expected server function error', () => { - test.use({ - whitelistErrors: [ - /Failed to load resource: the server responded with a status of 500/, - ], - }) - test('server function errors retain committed session data', async ({ - page, - }) => { - await visitFunctions(page) - await page.getByTestId('server-function-error').click() - await expectResult(page, 'error', 'Expected external session error') - expect( - (await (await page.request.get('/api/session')).json()).data.serverFn, - ).toBe('error-persisted') - }) - }) - - test('iron-session cookie jar works in browser-invoked server functions', async ({ - page, - }) => { - await visitFunctions(page) - await page.getByTestId('server-function-iron').click() - await expectResult(page, 'iron', 'iron-server-function') - expect( - (await (await page.request.get('/api/session-iron')).json()).data.user, - ).toBe('iron-server-function') - }) - - test('separate browser contexts retain independent sessions', async ({ - browser, - baseURL, - }) => { - const first = await browser.newContext({ baseURL }) - const second = await browser.newContext({ baseURL }) - try { - const firstPage = await first.newPage() - const secondPage = await second.newPage() - const [firstResponse, secondResponse] = await Promise.all([ - firstPage.goto('/ssr'), - secondPage.goto('/ssr'), - ]) - expect(firstResponse?.ok()).toBe(true) - expect(secondResponse?.ok()).toBe(true) - await firstPage.reload() - await expect(firstPage.getByTestId('ssr-session-count')).toHaveText('2') - await expect(secondPage.getByTestId('ssr-session-count')).toHaveText('1') - } finally { - await first.close() - await second.close() - } - }) -}) diff --git a/e2e/react-start/spa-mode/package.json b/e2e/react-start/spa-mode/package.json index 5281364692..1810493b1a 100644 --- a/e2e/react-start/spa-mode/package.json +++ b/e2e/react-start/spa-mode/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "npx serve dist/client", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", diff --git a/e2e/react-start/spa-mode/playwright.config.ts b/e2e/react-start/spa-mode/playwright.config.ts index 630989e41f..badd6db0eb 100644 --- a/e2e/react-start/spa-mode/playwright.config.ts +++ b/e2e/react-start/spa-mode/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/split-base-and-basepath/package.json b/e2e/react-start/split-base-and-basepath/package.json index 7f0e62766c..c0066b7aaf 100644 --- a/e2e/react-start/split-base-and-basepath/package.json +++ b/e2e/react-start/split-base-and-basepath/package.json @@ -10,7 +10,7 @@ "start": "node prod-server.js", "test:e2e:dev": "MODE=dev playwright test --project=chromium", "test:e2e:prod": "playwright test --project=chromium", - "test:e2e": "pnpm run test:e2e:dev && pnpm run test:e2e:prod" + "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:dev && pnpm run test:e2e:prod" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -26,7 +26,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" diff --git a/e2e/react-start/split-base-and-basepath/playwright.config.ts b/e2e/react-start/split-base-and-basepath/playwright.config.ts index f0e25bb95a..3596ccd106 100644 --- a/e2e/react-start/split-base-and-basepath/playwright.config.ts +++ b/e2e/react-start/split-base-and-basepath/playwright.config.ts @@ -1,10 +1,11 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +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 = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -13,17 +14,16 @@ 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 --port 0` - : `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: isDev ? `pnpm dev:e2e` : `pnpm build && PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { PORT: String(PORT), diff --git a/e2e/react-start/split-base-and-basepath/prod-server.js b/e2e/react-start/split-base-and-basepath/prod-server.js index 58421125cf..72114a1d40 100644 --- a/e2e/react-start/split-base-and-basepath/prod-server.js +++ b/e2e/react-start/split-base-and-basepath/prod-server.js @@ -20,9 +20,7 @@ app.use(async (req, res, next) => { } }) -const httpServer = app.listen(PORT, (error) => { - if (error) { - throw error - } - console.log(`E2E app: http://localhost:${httpServer.address().port}`) +app.listen(PORT, (error) => { + if (error) throw error + console.log(`Server is running on http://localhost:${PORT}`) }) diff --git a/e2e/react-start/split-base-and-basepath/tests/setup/global.setup.ts b/e2e/react-start/split-base-and-basepath/tests/setup/global.setup.ts index 9fc3ddc286..41ad16a44f 100644 --- a/e2e/react-start/split-base-and-basepath/tests/setup/global.setup.ts +++ b/e2e/react-start/split-base-and-basepath/tests/setup/global.setup.ts @@ -1,9 +1,17 @@ -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' +import { + e2eStartDummyServer, + getTestServerPort, + preOptimizeDevServer, + waitForServer, +} from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } export default async function setup() { + await e2eStartDummyServer(packageJson.name) + if (process.env.MODE !== 'dev') return - const port = Number(process.env.E2E_APP_PORT ?? 0) + const port = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${port}` await waitForServer(baseURL) diff --git a/e2e/react-start/split-base-and-basepath/tests/setup/global.teardown.ts b/e2e/react-start/split-base-and-basepath/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/split-base-and-basepath/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/start-manifest/package.json b/e2e/react-start/start-manifest/package.json index d5367558e8..939882a346 100644 --- a/e2e/react-start/start-manifest/package.json +++ b/e2e/react-start/start-manifest/package.json @@ -21,7 +21,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "nitro": "^3.0.260903-beta", + "nitro": "^3.0.260311-beta", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" @@ -29,11 +29,7 @@ "nx": { "targets": { "test:e2e": { - "parallelism": false, - "outputs": [ - "...", - "{projectRoot}/.output" - ] + "parallelism": false } } } diff --git a/e2e/react-start/start-manifest/playwright.config.ts b/e2e/react-start/start-manifest/playwright.config.ts index 333ada654d..9e72f6160b 100644 --- a/e2e/react-start/start-manifest/playwright.config.ts +++ b/e2e/react-start/start-manifest/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -15,8 +16,8 @@ export default defineConfig({ webServer: { command: `PORT=${PORT} pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/start-manifest/tests/start-manifest.spec.ts b/e2e/react-start/start-manifest/tests/start-manifest.spec.ts index bd7bd20e98..7dfa390997 100644 --- a/e2e/react-start/start-manifest/tests/start-manifest.spec.ts +++ b/e2e/react-start/start-manifest/tests/start-manifest.spec.ts @@ -27,6 +27,12 @@ async function getBackgroundColor(testId: string, page: Page) { .evaluate((element) => getComputedStyle(element).backgroundColor) } +async function getBorderTopColor(testId: string, page: Page) { + return page + .getByTestId(testId) + .evaluate((element) => getComputedStyle(element).borderTopColor) +} + function getStylesheetHrefsFromHtml(html: string) { return Array.from( html.matchAll(/]+rel="stylesheet"[^>]+href="([^"]+)"/g), @@ -356,19 +362,24 @@ test('shared widget CSS stays applied when navigating from static to lazy route' const widget = page.getByTestId('shared-widget') await expect(widget).toBeVisible() - await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + expect(await getBackgroundColor('shared-widget', page)).toBe(SHARED_WIDGET_BG) + await expect + .poll(() => getBorderTopColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(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(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) }) test('shared widget CSS stays applied when navigating from lazy to static route', async ({ @@ -378,19 +389,28 @@ 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() - 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 expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) 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(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) + await expect + .poll(() => getBorderTopColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BORDER) }) test('shared widget CSS is applied on direct navigation to lazy route', async ({ @@ -402,8 +422,17 @@ 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(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) + await expect + .poll(() => getBorderTopColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BORDER) }) test('shared widget CSS persists after navigating away from lazy and back', async ({ @@ -413,21 +442,19 @@ 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('lazy-css-lazy-heading')).toBeVisible() - await expect(widget).toBeVisible() + await expect(page.getByTestId('shared-widget')).toBeVisible() await page.getByTestId('nav-home').click() 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(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) }) diff --git a/e2e/react-start/static-server-functions/package.json b/e2e/react-start/static-server-functions/package.json index 85f08d19c9..6aa146fc59 100644 --- a/e2e/react-start/static-server-functions/package.json +++ b/e2e/react-start/static-server-functions/package.json @@ -9,13 +9,13 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "node .output/server/index.mjs", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:*", "@tanstack/react-start": "workspace:*", "@tanstack/start-static-server-functions": "workspace:*", - "nitro": "^3.0.260903-beta", + "nitro": "^3.0.1-alpha.2", "react": "^19.0.0", "react-dom": "^19.0.0" }, @@ -29,14 +29,5 @@ "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" - }, - "nx": { - "targets": { - "test:e2e": { - "dependsOn": [ - "build" - ] - } - } } } diff --git a/e2e/react-start/static-server-functions/playwright.config.ts b/e2e/react-start/static-server-functions/playwright.config.ts index 08416e4d53..b9f835c16a 100644 --- a/e2e/react-start/static-server-functions/playwright.config.ts +++ b/e2e/react-start/static-server-functions/playwright.config.ts @@ -1,6 +1,8 @@ import { defineConfig, devices } from '@playwright/test' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = 3000 +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -13,9 +15,9 @@ export default defineConfig({ }, webServer: { - command: `PORT=${PORT} pnpm start`, + command: `pnpm build && PORT=${PORT} pnpm start`, url: baseURL, - reuseExistingServer: false, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/static-server-functions/src/routeTree.gen.ts b/e2e/react-start/static-server-functions/src/routeTree.gen.ts index 558b1ab4d9..ea6a6a3806 100644 --- a/e2e/react-start/static-server-functions/src/routeTree.gen.ts +++ b/e2e/react-start/static-server-functions/src/routeTree.gen.ts @@ -11,7 +11,6 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as IndexRouteImport } from './routes/index' import { Route as PostsRouteImport } from './routes/posts' -import { Route as RawStreamRouteImport } from './routes/raw-stream' import { Route as PostsIndexRouteImport } from './routes/posts.index' const IndexRoute = IndexRouteImport.update({ @@ -24,11 +23,6 @@ const PostsRoute = PostsRouteImport.update({ path: '/posts', getParentRoute: () => rootRouteImport, } as any) -const RawStreamRoute = RawStreamRouteImport.update({ - id: '/raw-stream', - path: '/raw-stream', - getParentRoute: () => rootRouteImport, -} as any) const PostsIndexRoute = PostsIndexRouteImport.update({ id: '/', path: '/', @@ -38,33 +32,29 @@ const PostsIndexRoute = PostsIndexRouteImport.update({ export interface FileRoutesByFullPath { '/': typeof IndexRoute '/posts': typeof PostsRouteWithChildren - '/raw-stream': typeof RawStreamRoute '/posts/': typeof PostsIndexRoute } export interface FileRoutesByTo { '/': typeof IndexRoute - '/raw-stream': typeof RawStreamRoute '/posts': typeof PostsIndexRoute } export interface FileRoutesById { __root__: typeof rootRouteImport '/': typeof IndexRoute '/posts': typeof PostsRouteWithChildren - '/raw-stream': typeof RawStreamRoute '/posts/': typeof PostsIndexRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/posts' | '/raw-stream' | '/posts/' + fullPaths: '/' | '/posts' | '/posts/' fileRoutesByTo: FileRoutesByTo - to: '/' | '/raw-stream' | '/posts' - id: '__root__' | '/' | '/posts' | '/raw-stream' | '/posts/' + to: '/' | '/posts' + id: '__root__' | '/' | '/posts' | '/posts/' fileRoutesById: FileRoutesById } export interface RootRouteChildren { IndexRoute: typeof IndexRoute PostsRoute: typeof PostsRouteWithChildren - RawStreamRoute: typeof RawStreamRoute } declare module '@tanstack/react-router' { @@ -83,13 +73,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof PostsRouteImport parentRoute: typeof rootRouteImport } - '/raw-stream': { - id: '/raw-stream' - path: '/raw-stream' - fullPath: '/raw-stream' - preLoaderRoute: typeof RawStreamRouteImport - parentRoute: typeof rootRouteImport - } '/posts/': { id: '/posts/' path: '/' @@ -113,7 +96,6 @@ const PostsRouteWithChildren = PostsRoute._addFileChildren(PostsRouteChildren) const rootRouteChildren: RootRouteChildren = { IndexRoute: IndexRoute, PostsRoute: PostsRouteWithChildren, - RawStreamRoute: RawStreamRoute, } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) diff --git a/e2e/react-start/static-server-functions/src/routes/__root.tsx b/e2e/react-start/static-server-functions/src/routes/__root.tsx index a300613fa8..b768e8b9a1 100644 --- a/e2e/react-start/static-server-functions/src/routes/__root.tsx +++ b/e2e/react-start/static-server-functions/src/routes/__root.tsx @@ -30,9 +30,6 @@ function RootComponent() { Posts - - Raw Stream -

diff --git a/e2e/react-start/static-server-functions/src/routes/raw-stream.tsx b/e2e/react-start/static-server-functions/src/routes/raw-stream.tsx deleted file mode 100644 index df898d2907..0000000000 --- a/e2e/react-start/static-server-functions/src/routes/raw-stream.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { createFileRoute } from '@tanstack/react-router' -import { RawStream, createServerFn } from '@tanstack/react-start' -import { staticFunctionMiddleware } from '@tanstack/start-static-server-functions' - -const fetchRawStream = createServerFn({ method: 'GET' }) - .middleware([staticFunctionMiddleware]) - .handler(async () => { - return new RawStream(new Response('Static cache stream').body!, { - hint: 'text', - }) - }) - -export const Route = createFileRoute('/raw-stream')({ - loader: async () => { - const result = await fetchRawStream() - if (typeof document === 'undefined') { - return '' - } - const stream = result as RawStream | ReadableStream - return new Response( - stream instanceof RawStream ? stream.stream : stream, - ).text() - }, - component: RawStreamComponent, -}) - -function RawStreamComponent() { - return

{Route.useLoaderData()}

-} diff --git a/e2e/react-start/static-server-functions/tests/app.spec.ts b/e2e/react-start/static-server-functions/tests/app.spec.ts index d86fd61a75..895566aa35 100644 --- a/e2e/react-start/static-server-functions/tests/app.spec.ts +++ b/e2e/react-start/static-server-functions/tests/app.spec.ts @@ -59,32 +59,5 @@ test.describe('Static Server Functions with Nitro', () => { await expect(page.getByTestId('post-2')).toHaveText('Second Post') await expect(page.getByTestId('post-3')).toHaveText('Third Post') }) - - test('should decode a cached RawStream during client navigation', async ({ - page, - }) => { - await page.goto('/') - // Nitro snapshots public assets before Start prerenders (see #6787). - // Serve the generated file as a static host would to isolate decoding. - await page.route('**/__tsr/staticServerFnCache/*.json', (route) => - route.fulfill({ - path: join( - process.cwd(), - '.output', - 'public', - new URL(route.request().url()).pathname, - ), - }), - ) - const cacheResponse = page.waitForResponse((response) => - response.url().includes('/__tsr/staticServerFnCache/'), - ) - await page.getByTestId('link-raw-stream').click() - const response = await cacheResponse - expect(response.status(), response.url()).toBe(200) - await expect(page.getByTestId('raw-stream')).toHaveText( - 'Static cache stream', - ) - }) }) }) diff --git a/e2e/react-start/streaming-ssr/package.json b/e2e/react-start/streaming-ssr/package.json index 1d08a07622..fcf78262d5 100644 --- a/e2e/react-start/streaming-ssr/package.json +++ b/e2e/react-start/streaming-ssr/package.json @@ -9,9 +9,8 @@ "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", - "test:e2e:buffer-repro": "RUN_SSR_ROUTER_HTML_BUFFER_REPRO=true playwright test router-html-buffer.spec.ts --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium", + "test:e2e:preview": "rm -rf port*.txt; MODE=preview playwright test preview-streaming.spec.ts --project=chromium" }, "dependencies": { "@tanstack/react-query": "^5.80.7", @@ -27,45 +26,9 @@ "@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", + "srvx": "^0.11.9", "@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" - ] - }, - "test:e2e:buffer-repro": { - "inputs": [ - "default", - "^production", - "dependentTaskOutputs", - "streamingSsrTests" - ] - } - } } } diff --git a/e2e/react-start/streaming-ssr/playwright.config.ts b/e2e/react-start/streaming-ssr/playwright.config.ts index c2f3b67a0c..052ebe879d 100644 --- a/e2e/react-start/streaming-ssr/playwright.config.ts +++ b/e2e/react-start/streaming-ssr/playwright.config.ts @@ -1,9 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } const isPreview = process.env.MODE === 'preview' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + `${packageJson.name}${isPreview ? '_preview' : ''}`, +) const baseURL = `http://localhost:${PORT}` const ssrCommand = `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start` @@ -25,8 +28,8 @@ export default defineConfig({ webServer: { command: isPreview ? previewCommand : ssrCommand, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/react-start/streaming-ssr/src/routeTree.gen.ts b/e2e/react-start/streaming-ssr/src/routeTree.gen.ts index 169121003d..c1a51b62f8 100644 --- a/e2e/react-start/streaming-ssr/src/routeTree.gen.ts +++ b/e2e/react-start/streaming-ssr/src/routeTree.gen.ts @@ -17,7 +17,6 @@ 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 RouterHtmlBufferRouteImport } from './routes/router-html-buffer' import { Route as SlowRenderRouteImport } from './routes/slow-render' import { Route as StreamRouteImport } from './routes/stream' import { Route as SyncOnlyRouteImport } from './routes/sync-only' @@ -62,11 +61,6 @@ const QueryHeavyRoute = QueryHeavyRouteImport.update({ path: '/query-heavy', getParentRoute: () => rootRouteImport, } as any) -const RouterHtmlBufferRoute = RouterHtmlBufferRouteImport.update({ - id: '/router-html-buffer', - path: '/router-html-buffer', - getParentRoute: () => rootRouteImport, -} as any) const SlowRenderRoute = SlowRenderRouteImport.update({ id: '/slow-render', path: '/slow-render', @@ -92,7 +86,6 @@ export interface FileRoutesByFullPath { '/many-promises': typeof ManyPromisesRoute '/nested-deferred': typeof NestedDeferredRoute '/query-heavy': typeof QueryHeavyRoute - '/router-html-buffer': typeof RouterHtmlBufferRoute '/slow-render': typeof SlowRenderRoute '/stream': typeof StreamRoute '/sync-only': typeof SyncOnlyRoute @@ -106,7 +99,6 @@ export interface FileRoutesByTo { '/many-promises': typeof ManyPromisesRoute '/nested-deferred': typeof NestedDeferredRoute '/query-heavy': typeof QueryHeavyRoute - '/router-html-buffer': typeof RouterHtmlBufferRoute '/slow-render': typeof SlowRenderRoute '/stream': typeof StreamRoute '/sync-only': typeof SyncOnlyRoute @@ -121,7 +113,6 @@ export interface FileRoutesById { '/many-promises': typeof ManyPromisesRoute '/nested-deferred': typeof NestedDeferredRoute '/query-heavy': typeof QueryHeavyRoute - '/router-html-buffer': typeof RouterHtmlBufferRoute '/slow-render': typeof SlowRenderRoute '/stream': typeof StreamRoute '/sync-only': typeof SyncOnlyRoute @@ -137,7 +128,6 @@ export interface FileRouteTypes { | '/many-promises' | '/nested-deferred' | '/query-heavy' - | '/router-html-buffer' | '/slow-render' | '/stream' | '/sync-only' @@ -151,7 +141,6 @@ export interface FileRouteTypes { | '/many-promises' | '/nested-deferred' | '/query-heavy' - | '/router-html-buffer' | '/slow-render' | '/stream' | '/sync-only' @@ -165,7 +154,6 @@ export interface FileRouteTypes { | '/many-promises' | '/nested-deferred' | '/query-heavy' - | '/router-html-buffer' | '/slow-render' | '/stream' | '/sync-only' @@ -180,7 +168,6 @@ export interface RootRouteChildren { ManyPromisesRoute: typeof ManyPromisesRoute NestedDeferredRoute: typeof NestedDeferredRoute QueryHeavyRoute: typeof QueryHeavyRoute - RouterHtmlBufferRoute: typeof RouterHtmlBufferRoute SlowRenderRoute: typeof SlowRenderRoute StreamRoute: typeof StreamRoute SyncOnlyRoute: typeof SyncOnlyRoute @@ -244,13 +231,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof QueryHeavyRouteImport parentRoute: typeof rootRouteImport } - '/router-html-buffer': { - id: '/router-html-buffer' - path: '/router-html-buffer' - fullPath: '/router-html-buffer' - preLoaderRoute: typeof RouterHtmlBufferRouteImport - parentRoute: typeof rootRouteImport - } '/slow-render': { id: '/slow-render' path: '/slow-render' @@ -284,7 +264,6 @@ const rootRouteChildren: RootRouteChildren = { ManyPromisesRoute: ManyPromisesRoute, NestedDeferredRoute: NestedDeferredRoute, QueryHeavyRoute: QueryHeavyRoute, - RouterHtmlBufferRoute: RouterHtmlBufferRoute, SlowRenderRoute: SlowRenderRoute, StreamRoute: StreamRoute, SyncOnlyRoute: SyncOnlyRoute, diff --git a/e2e/react-start/streaming-ssr/src/routes/concurrent.tsx b/e2e/react-start/streaming-ssr/src/routes/concurrent.tsx index c04155aa59..a1bed0fe07 100644 --- a/e2e/react-start/streaming-ssr/src/routes/concurrent.tsx +++ b/e2e/react-start/streaming-ssr/src/routes/concurrent.tsx @@ -1,9 +1,54 @@ import { Await, createFileRoute } from '@tanstack/react-router' import { Suspense } from 'react' -import { createConcurrentLoaderData } from '../../../../streaming-ssr-fixtures' + +/** + * Tests concurrent promise resolution - multiple promises resolving at the exact same time. + * This can stress the serialization system and reveal race conditions. + */ + +// Shared delay function that resolves multiple promises at the same instant +function createConcurrentPromises( + count: number, + delayMs: number, +): Array> { + const sharedPromise = new Promise((resolve) => + setTimeout(resolve, delayMs), + ) + return Array.from({ length: count }, (_, i) => + sharedPromise.then(() => `concurrent-${i + 1}`), + ) +} export const Route = createFileRoute('/concurrent')({ - loader: async () => createConcurrentLoaderData(), + loader: async () => { + // Create fresh batches of concurrent promises for each request + const batch1 = createConcurrentPromises(5, 100) // 5 promises resolving at 100ms + const batch2 = createConcurrentPromises(5, 200) // 5 promises resolving at 200ms + const batch3 = createConcurrentPromises(5, 300) // 5 promises resolving at 300ms + + return { + // Batch 1: 5 promises resolving at exactly the same time (100ms) + concurrent1_1: batch1[0], + concurrent1_2: batch1[1], + concurrent1_3: batch1[2], + concurrent1_4: batch1[3], + concurrent1_5: batch1[4], + + // Batch 2: 5 promises resolving at exactly the same time (200ms) + concurrent2_1: batch2[0], + concurrent2_2: batch2[1], + concurrent2_3: batch2[2], + concurrent2_4: batch2[3], + concurrent2_5: batch2[4], + + // Batch 3: 5 promises resolving at exactly the same time (300ms) + concurrent3_1: batch3[0], + concurrent3_2: batch3[1], + concurrent3_3: batch3[2], + concurrent3_4: batch3[3], + concurrent3_5: batch3[4], + } + }, component: Concurrent, }) @@ -41,6 +86,7 @@ function Concurrent() { gap: '20px', }} > + {/* Batch 1: 100ms */}

Batch 1 (100ms)

@@ -50,6 +96,7 @@ function Concurrent() {
+ {/* Batch 2: 200ms */}

Batch 2 (200ms)

@@ -59,6 +106,7 @@ function Concurrent() {
+ {/* Batch 3: 300ms */}

Batch 3 (300ms)

diff --git a/e2e/react-start/streaming-ssr/src/routes/deferred-rejection.tsx b/e2e/react-start/streaming-ssr/src/routes/deferred-rejection.tsx index 3ac1e7fc2d..d9b5305480 100644 --- a/e2e/react-start/streaming-ssr/src/routes/deferred-rejection.tsx +++ b/e2e/react-start/streaming-ssr/src/routes/deferred-rejection.tsx @@ -1,9 +1,7 @@ import { Await, createFileRoute } from '@tanstack/react-router' import { Suspense } from 'react' -import { - deferredDataDelay, - deferredErrorMessage, -} from '../../../../streaming-ssr-fixtures' + +const deferredErrorMessage = 'Error in deferred object' export const Route = createFileRoute('/deferred-rejection')({ loader: async () => { @@ -11,7 +9,7 @@ export const Route = createFileRoute('/deferred-rejection')({ deferredData: new Promise((_resolve, reject) => { setTimeout(() => { reject(new Error(deferredErrorMessage)) - }, deferredDataDelay) + }, 1000) }), } }, diff --git a/e2e/react-start/streaming-ssr/src/routes/deferred.tsx b/e2e/react-start/streaming-ssr/src/routes/deferred.tsx index 9f91c0f2d4..506efbd345 100644 --- a/e2e/react-start/streaming-ssr/src/routes/deferred.tsx +++ b/e2e/react-start/streaming-ssr/src/routes/deferred.tsx @@ -1,40 +1,55 @@ import { Await, createFileRoute } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' import { Suspense } from 'react' -import { - deferredDataDelay, - deferredDataMessage, - deferredImmediateName, - deferredServerDelay, - deferredSlowName, - delay, - makeDeferredMessage, - makeServerData, - sourceMarker, -} from '../../../../streaming-ssr-fixtures' +// Server function that returns immediately const getImmediateData = createServerFn({ method: 'GET' }) .validator((data: { name: string }) => data) - .handler(({ data }) => makeServerData(data.name)) + .handler(({ data }) => { + return { + name: data.name, + timestamp: Date.now(), + // Track where this data came from - should always be 'server' if SSR works + source: 'server' as const, + } + }) +// Server function that takes time to complete const getSlowData = createServerFn({ method: 'GET' }) .validator((data: { name: string; delay: number }) => data) .handler(async ({ data }) => { - await delay(data.delay) - return makeServerData(data.name) + await new Promise((r) => setTimeout(r, data.delay)) + return { + name: data.name, + timestamp: Date.now(), + // Track where this data came from - should always be 'server' if SSR works + source: 'server' as const, + } }) export const Route = createFileRoute('/deferred')({ loader: async () => { return { - deferredData: makeDeferredMessage(deferredDataMessage, deferredDataDelay), + // Deferred promise that resolves after 1 second + deferredData: new Promise<{ message: string; source: string }>((r) => + setTimeout( + () => + r({ + message: 'Deferred data loaded!', + // Track where this data came from - should always be 'server' if SSR works + source: typeof window === 'undefined' ? 'server' : 'client', + }), + 1000, + ), + ), + // Deferred server function call deferredServerData: getSlowData({ - data: { name: deferredSlowName, delay: deferredServerDelay }, + data: { name: 'Slow User', delay: 800 }, }), - immediateData: await getImmediateData({ - data: { name: deferredImmediateName }, - }), - loaderSource: sourceMarker(), + // Immediate data (awaited) + immediateData: await getImmediateData({ data: { name: 'Fast User' } }), + // Track where loader ran - should always be 'server' if SSR works + loaderSource: typeof window === 'undefined' ? 'server' : 'client', } }, component: Deferred, @@ -48,6 +63,7 @@ function Deferred() {

Deferred Data Test

+ {/* Immediate data should be available right away */}
Immediate: {immediateData.name} @ {immediateData.timestamp}
@@ -58,6 +74,7 @@ function Deferred() {
Loader source: {loaderSource}
+ {/* Deferred promise */} Loading deferred...
} > @@ -71,6 +88,7 @@ function Deferred() { /> + {/* Deferred server function */} Loading server data...
diff --git a/e2e/react-start/streaming-ssr/src/routes/fast-serial.tsx b/e2e/react-start/streaming-ssr/src/routes/fast-serial.tsx index cc3f0c2b5c..61a47469f4 100644 --- a/e2e/react-start/streaming-ssr/src/routes/fast-serial.tsx +++ b/e2e/react-start/streaming-ssr/src/routes/fast-serial.tsx @@ -1,23 +1,26 @@ import { createFileRoute } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' -import { - fastSerialStaticData, - makeFastSerialSmallData, - sourceMarker, -} from '../../../../streaming-ssr-fixtures' -const getSmallData = createServerFn({ method: 'GET' }).handler(() => - makeFastSerialSmallData(), -) +// Server function that returns immediately with minimal data +const getSmallData = createServerFn({ method: 'GET' }).handler(() => { + return { + value: 'small-data', + timestamp: Date.now(), + // Track where this data came from - should always be 'server' if SSR works + source: 'server' as const, + } +}) export const Route = createFileRoute('/fast-serial')({ loader: async () => { + // All data is awaited immediately - serialization should complete quickly const data = await getSmallData() return { serverData: data, - staticData: fastSerialStaticData, + staticData: 'This is static data', timestamp: Date.now(), - loaderSource: sourceMarker(), + // Track where loader ran - should always be 'server' if SSR works + loaderSource: typeof window === 'undefined' ? 'server' : 'client', } }, component: FastSerial, diff --git a/e2e/react-start/streaming-ssr/src/routes/many-promises.tsx b/e2e/react-start/streaming-ssr/src/routes/many-promises.tsx index 25cb6511c7..a6d0374972 100644 --- a/e2e/react-start/streaming-ssr/src/routes/many-promises.tsx +++ b/e2e/react-start/streaming-ssr/src/routes/many-promises.tsx @@ -1,9 +1,47 @@ import { Await, createFileRoute } from '@tanstack/react-router' import { Suspense } from 'react' -import { createManyPromises } from '../../../../streaming-ssr-fixtures' + +/** + * Tests streaming with many (15+) deferred promises resolving in various orders. + * This stresses the serialization system with concurrent promise resolutions. + */ + +// Helper to create a promise with a specific delay and value +function createDelayedPromise(value: T, delayMs: number): Promise { + return new Promise((resolve) => setTimeout(() => resolve(value), delayMs)) +} export const Route = createFileRoute('/many-promises')({ - loader: async () => createManyPromises(), + loader: async () => { + // Create 15 promises with varying delays to test ordering + // Some resolve quickly, some slowly, some at similar times + return { + // Immediate/very fast (0-50ms) + immediate1: createDelayedPromise('immediate-1', 0), + immediate2: createDelayedPromise('immediate-2', 10), + immediate3: createDelayedPromise('immediate-3', 20), + + // Fast (50-150ms) + fast1: createDelayedPromise('fast-1', 50), + fast2: createDelayedPromise('fast-2', 75), + fast3: createDelayedPromise('fast-3', 100), + fast4: createDelayedPromise('fast-4', 125), + + // Medium (150-300ms) + medium1: createDelayedPromise('medium-1', 150), + medium2: createDelayedPromise('medium-2', 200), + medium3: createDelayedPromise('medium-3', 250), + + // Slow (300-600ms) + slow1: createDelayedPromise('slow-1', 300), + slow2: createDelayedPromise('slow-2', 400), + slow3: createDelayedPromise('slow-3', 500), + + // Very slow (600ms+) + verySlow1: createDelayedPromise('very-slow-1', 600), + verySlow2: createDelayedPromise('very-slow-2', 800), + } + }, component: ManyPromises, }) @@ -47,6 +85,7 @@ function ManyPromises() { gap: '10px', }} > + {/* Immediate group */}

Immediate (0-20ms)

+ {/* Fast group */}

Fast (50-125ms)

@@ -74,6 +114,7 @@ function ManyPromises() {
+ {/* Medium group */}

Medium (150-250ms)

+ {/* Slow group */}

Slow (300-500ms)

@@ -100,6 +142,7 @@ function ManyPromises() {
+ {/* Very slow group */}

Very Slow (600-800ms)

{ - await delay(nestedLevelDelays[0]) - return makeLevelData(1) + await new Promise((r) => setTimeout(r, 200)) + return { level: 1, timestamp: Date.now() } }) const getLevel2Data = createServerFn({ method: 'GET' }).handler(async () => { - await delay(nestedLevelDelays[1]) - return makeLevelData(2) + await new Promise((r) => setTimeout(r, 400)) + return { level: 2, timestamp: Date.now() } }) const getLevel3Data = createServerFn({ method: 'GET' }).handler(async () => { - await delay(nestedLevelDelays[2]) - return makeLevelData(3) + await new Promise((r) => setTimeout(r, 600)) + return { level: 3, timestamp: Date.now() } }) export const Route = createFileRoute('/nested-deferred')({ loader: async () => { return { + // Multiple deferred promises that resolve at different times level1: getLevel1Data(), level2: getLevel2Data(), level3: getLevel3Data(), - plainDeferred: makeDeferred(nestedPlainMessage, nestedPlainDelay), + // Also a plain deferred promise + plainDeferred: new Promise((r) => + setTimeout(() => r('Plain deferred resolved!'), 300), + ), } }, component: NestedDeferred, }) +// Nested component that renders more Await components function Level1Content({ level2, level3, @@ -108,6 +106,7 @@ function NestedDeferred() { Tests multiple nested deferred promises resolving at different times.

+ {/* Plain deferred */} Loading plain...
} > @@ -117,6 +116,7 @@ function NestedDeferred() { /> + {/* Nested structure */}
Loading level 1...
} diff --git a/e2e/react-start/streaming-ssr/src/routes/query-heavy.tsx b/e2e/react-start/streaming-ssr/src/routes/query-heavy.tsx index 115ae9f10f..b20921323c 100644 --- a/e2e/react-start/streaming-ssr/src/routes/query-heavy.tsx +++ b/e2e/react-start/streaming-ssr/src/routes/query-heavy.tsx @@ -1,48 +1,167 @@ import { queryOptions, useSuspenseQuery } from '@tanstack/react-query' import { createFileRoute } from '@tanstack/react-router' import { Suspense } from 'react' -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: (): QueryData | Promise => { - if (item.delayMs > 0) { - return delay(item.delayMs).then(() => makeQueryData(item)) - } +/** + * Tests multiple useSuspenseQuery calls on a single route. + * Some queries have synchronous queryFn (return immediately), + * some have async queryFn with various delays. + * + * This stresses the SSR query streaming integration. + */ - return makeQueryData(item) - }, - staleTime: Infinity, - }) -} +// Synchronous query - returns immediately (no await) +const syncQuery1 = queryOptions({ + queryKey: ['sync', 1], + queryFn: () => { + // Synchronous return - no Promise delay + return { + type: 'sync', + id: 1, + value: 'sync-value-1', + source: typeof window === 'undefined' ? 'server' : 'client', + } + }, + 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]) +const syncQuery2 = queryOptions({ + queryKey: ['sync', 2], + queryFn: () => { + return { + type: 'sync', + id: 2, + value: 'sync-value-2', + source: typeof window === 'undefined' ? 'server' : 'client', + } + }, + staleTime: Infinity, +}) -type QueryOptions = ReturnType +const syncQuery3 = queryOptions({ + queryKey: ['sync', 3], + queryFn: () => { + return { + type: 'sync', + id: 3, + value: 'sync-value-3', + source: typeof window === 'undefined' ? 'server' : 'client', + } + }, + staleTime: Infinity, +}) + +// Fast async queries (50-100ms) +const fastAsyncQuery1 = queryOptions({ + queryKey: ['fast-async', 1], + queryFn: async () => { + await new Promise((r) => setTimeout(r, 50)) + return { + type: 'fast-async', + id: 1, + value: 'fast-async-1', + source: typeof window === 'undefined' ? 'server' : 'client', + } + }, + staleTime: Infinity, +}) + +const fastAsyncQuery2 = queryOptions({ + queryKey: ['fast-async', 2], + queryFn: async () => { + await new Promise((r) => setTimeout(r, 75)) + return { + type: 'fast-async', + id: 2, + value: 'fast-async-2', + source: typeof window === 'undefined' ? 'server' : 'client', + } + }, + staleTime: Infinity, +}) + +const fastAsyncQuery3 = queryOptions({ + queryKey: ['fast-async', 3], + queryFn: async () => { + await new Promise((r) => setTimeout(r, 100)) + return { + type: 'fast-async', + id: 3, + value: 'fast-async-3', + source: typeof window === 'undefined' ? 'server' : 'client', + } + }, + staleTime: Infinity, +}) + +// Slow async queries (200-400ms) +const slowAsyncQuery1 = queryOptions({ + queryKey: ['slow-async', 1], + queryFn: async () => { + await new Promise((r) => setTimeout(r, 200)) + return { + type: 'slow-async', + id: 1, + value: 'slow-async-1', + source: typeof window === 'undefined' ? 'server' : 'client', + } + }, + staleTime: Infinity, +}) + +const slowAsyncQuery2 = queryOptions({ + queryKey: ['slow-async', 2], + queryFn: async () => { + await new Promise((r) => setTimeout(r, 300)) + return { + type: 'slow-async', + id: 2, + value: 'slow-async-2', + source: typeof window === 'undefined' ? 'server' : 'client', + } + }, + staleTime: Infinity, +}) + +const slowAsyncQuery3 = queryOptions({ + queryKey: ['slow-async', 3], + queryFn: async () => { + await new Promise((r) => setTimeout(r, 400)) + return { + type: 'slow-async', + id: 3, + value: 'slow-async-3', + source: typeof window === 'undefined' ? 'server' : 'client', + } + }, + staleTime: Infinity, +}) export const Route = createFileRoute('/query-heavy')({ component: QueryHeavy, }) -function QueryDisplay({ +// Individual query components to test Suspense boundaries +function SyncQueryDisplay({ queryOpts, testId, }: { - queryOpts: QueryOptions + queryOpts: typeof syncQuery1 + testId: string +}) { + const { data } = useSuspenseQuery(queryOpts) + return ( +
+ {data.value} (source: {data.source}) +
+ ) +} + +function AsyncQueryDisplay({ + queryOpts, + testId, +}: { + queryOpts: typeof fastAsyncQuery1 testId: string }) { const { data } = useSuspenseQuery(queryOpts) @@ -71,25 +190,27 @@ function QueryHeavy() { marginTop: '20px', }} > + {/* Sync queries - should resolve immediately */}

Sync Queries (immediate)

Loading sync 1...
} > - + Loading sync 2...} > - + Loading sync 3...} > - + + {/* Fast async queries */}

Fast Async Queries (50-100ms)

Loading fast 1...
} > - @@ -107,7 +228,7 @@ function QueryHeavy() {
Loading fast 2...
} > - @@ -117,13 +238,14 @@ function QueryHeavy() {
Loading fast 3...
} > - + {/* Slow async queries */}

Slow Async Queries (200-400ms)

Loading slow 1...
} > - @@ -141,7 +263,7 @@ function QueryHeavy() {
Loading slow 2...
} > - @@ -151,7 +273,7 @@ function QueryHeavy() {
Loading slow 3...
} > - diff --git a/e2e/react-start/streaming-ssr/src/routes/router-html-buffer.tsx b/e2e/react-start/streaming-ssr/src/routes/router-html-buffer.tsx deleted file mode 100644 index 6fb7bde27b..0000000000 --- a/e2e/react-start/streaming-ssr/src/routes/router-html-buffer.tsx +++ /dev/null @@ -1,58 +0,0 @@ -import { Suspense, useState } from 'react' -import { Await, createFileRoute } from '@tanstack/react-router' -import { createRouterHtmlPayload } from '../../../../streaming-ssr-fixtures' - -export const Route = createFileRoute('/router-html-buffer')({ - loader: () => { - return { - payload: createRouterHtmlPayload(), - } - }, - component: RouterHtmlBufferRoute, -}) - -function RouterHtmlBufferRoute() { - const { payload } = Route.useLoaderData() - - return ( -
-

Router HTML Buffer Reproduction

- Waiting for the deferred payload...

}> - ( - - )} - /> -
-
- ) -} - -function HydratedPayload({ - payload, - source, -}: { - payload: string - source: 'server' | 'client' -}) { - const [hydrationResult, setHydrationResult] = useState('not checked') - - return ( - <> -

{payload.length}

- -

{hydrationResult}

- - ) -} diff --git a/e2e/react-start/streaming-ssr/src/routes/slow-render.tsx b/e2e/react-start/streaming-ssr/src/routes/slow-render.tsx index a897c519c1..5dd9772604 100644 --- a/e2e/react-start/streaming-ssr/src/routes/slow-render.tsx +++ b/e2e/react-start/streaming-ssr/src/routes/slow-render.tsx @@ -1,36 +1,47 @@ import { Await, createFileRoute } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' import { Suspense } from 'react' -import { - makeDeferredMessage, - makeServerData, - slowRenderComponents, - slowRenderDeferredDelay, - slowRenderDeferredMessage, - slowRenderQuickName, - sourceMarker, -} from '../../../../streaming-ssr-fixtures' -const getQuickData = createServerFn({ method: 'GET' }).handler(() => - makeServerData(slowRenderQuickName), -) +// Server function that completes quickly +const getQuickData = createServerFn({ method: 'GET' }).handler(() => { + return { + name: 'Quick data', + timestamp: Date.now(), + // Track where this data came from - should always be 'server' if SSR works + source: 'server' as const, + } +}) +// Simulate a slow component render by doing work during render function SlowComponent({ data, index }: { data: string; index: number }) { + // This simulates a component that takes time to render const startTime = Date.now() - while (Date.now() - startTime < 100) {} + while (Date.now() - startTime < 100) { + // Blocking loop to simulate slow render + } return
{data}
} export const Route = createFileRoute('/slow-render')({ loader: async () => { + // All data loads quickly const quickData = await getQuickData() return { quickData, - deferredData: makeDeferredMessage( - slowRenderDeferredMessage, - slowRenderDeferredDelay, + // Deferred data that resolves before render might complete + deferredData: new Promise<{ message: string; source: string }>((r) => + setTimeout( + () => + r({ + message: 'Deferred resolved!', + // Track where this data came from - should always be 'server' if SSR works + source: typeof window === 'undefined' ? 'server' : 'client', + }), + 50, + ), ), - loaderSource: sourceMarker(), + // Track where loader ran - should always be 'server' if SSR works + loaderSource: typeof window === 'undefined' ? 'server' : 'client', } }, component: SlowRender, @@ -65,9 +76,10 @@ function SlowRender() { /> - {slowRenderComponents.map((data, index) => ( - - ))} + {/* Multiple slow components to extend render time */} + + + ) } diff --git a/e2e/react-start/streaming-ssr/src/routes/stream.tsx b/e2e/react-start/streaming-ssr/src/routes/stream.tsx index 458be61366..c1629204c7 100644 --- a/e2e/react-start/streaming-ssr/src/routes/stream.tsx +++ b/e2e/react-start/streaming-ssr/src/routes/stream.tsx @@ -1,16 +1,24 @@ import { Await, createFileRoute } from '@tanstack/react-router' import { Suspense, useEffect, useRef, useState } from 'react' -import { - createChunkStream, - createStreamPromise, -} from '../../../../streaming-ssr-fixtures' export const Route = createFileRoute('/stream')({ component: StreamRoute, loader() { return { - promise: createStreamPromise(), - stream: createChunkStream(), + // A promise that resolves after a short delay + promise: new Promise((resolve) => + setTimeout(() => resolve('promise-resolved'), 150), + ), + // A ReadableStream that emits chunks over time + stream: new ReadableStream({ + async start(controller) { + for (let i = 0; i < 5; i++) { + await new Promise((resolve) => setTimeout(resolve, 200)) + controller.enqueue(`chunk-${i}`) + } + controller.close() + }, + }), } }, }) @@ -25,16 +33,19 @@ function StreamRoute() { const streamRef = useRef(null) useEffect(() => { + // If we're already reading this exact stream, don't start again if (streamRef.current === stream && readerRef.current) { return } + // Reset state for a new stream if (streamRef.current !== stream) { setStreamData([]) setStreamComplete(false) streamRef.current = stream } + // Check if stream is already locked (from a previous render) if (stream.locked) { return } @@ -54,6 +65,7 @@ function StreamRoute() { } setStreamComplete(true) } catch (e) { + // Stream was cancelled or errored, ignore if (!(e instanceof TypeError && String(e).includes('cancelled'))) { console.error('Stream error:', e) } @@ -63,6 +75,7 @@ function StreamRoute() { fetchStream() return () => { + // Cancel the reader on cleanup if (readerRef.current) { readerRef.current.cancel().catch(() => {}) readerRef.current = null @@ -74,6 +87,7 @@ function StreamRoute() {

ReadableStream Test

+ {/* Promise data */} Loading promise...
} > @@ -83,6 +97,7 @@ function StreamRoute() { /> + {/* Stream data */}

Stream chunks:

diff --git a/e2e/react-start/streaming-ssr/src/routes/sync-only.tsx b/e2e/react-start/streaming-ssr/src/routes/sync-only.tsx index 67a77a3e9f..c95a1d467f 100644 --- a/e2e/react-start/streaming-ssr/src/routes/sync-only.tsx +++ b/e2e/react-start/streaming-ssr/src/routes/sync-only.tsx @@ -1,8 +1,22 @@ import { createFileRoute } from '@tanstack/react-router' -import { makeSyncOnlyData } from '../../../../streaming-ssr-fixtures' +/** + * This route tests synchronous serialization - no deferred data, no streaming. + * The loader returns data synchronously (awaited), so crossSerializeStream + * completes immediately and all bootstrap scripts should be in the initial HTML. + */ export const Route = createFileRoute('/sync-only')({ - loader: async () => makeSyncOnlyData(), + loader: async () => { + // Simulate a fast synchronous data fetch + // This data is awaited, not deferred, so serialization completes synchronously + return { + message: 'Hello from sync loader!', + timestamp: Date.now(), + items: ['item-1', 'item-2', 'item-3'], + // Track where this data came from - should always be 'server' if SSR works + source: typeof window === 'undefined' ? 'server' : 'client', + } + }, component: SyncOnly, }) diff --git a/e2e/react-start/streaming-ssr/tests/client-navigation.spec.ts b/e2e/react-start/streaming-ssr/tests/client-navigation.spec.ts index 8b9b3a8dcc..91138987ad 100644 --- a/e2e/react-start/streaming-ssr/tests/client-navigation.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/client-navigation.spec.ts @@ -1 +1,372 @@ -import '../../../streaming-ssr-specs/client-navigation' +import { expect, test, testWithHydration } from './fixtures' + +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 to home before stream completes + 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('rapid navigation between routes works', async ({ page }) => { + // Console errors are monitored by the fixture automatically + + // Rapid navigation sequence + 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/react-start/streaming-ssr/tests/concurrent.spec.ts b/e2e/react-start/streaming-ssr/tests/concurrent.spec.ts index 8625473a58..10e32c6809 100644 --- a/e2e/react-start/streaming-ssr/tests/concurrent.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/concurrent.spec.ts @@ -1 +1,100 @@ -import '../../../streaming-ssr-specs/concurrent' +import { expect, test, testWithHydration } from './fixtures' + +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 }, + ) + }) + + test('batch 1 resolves before batch 3', async ({ page }) => { + await page.goto('/concurrent', { waitUntil: 'commit' }) + + // Batch 1 should be visible before batch 3 + await expect(page.getByTestId('concurrent-1-1')).toBeVisible({ + timeout: 3000, + }) + + // Eventually batch 3 should also be visible + await expect(page.getByTestId('concurrent-3-5')).toBeVisible({ + 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/react-start/streaming-ssr/tests/deferred-rejection.spec.ts b/e2e/react-start/streaming-ssr/tests/deferred-rejection.spec.ts index 355b5019bc..3b8144072c 100644 --- a/e2e/react-start/streaming-ssr/tests/deferred-rejection.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/deferred-rejection.spec.ts @@ -1 +1,21 @@ -import '../../../streaming-ssr-specs/deferred-rejection' +import { expect, test } from './fixtures' + +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/react-start/streaming-ssr/tests/deferred.spec.ts b/e2e/react-start/streaming-ssr/tests/deferred.spec.ts index 3145897d7b..90ee16edc0 100644 --- a/e2e/react-start/streaming-ssr/tests/deferred.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/deferred.spec.ts @@ -1 +1,120 @@ -import '../../../streaming-ssr-specs/deferred' +import { expect, test, testWithHydration } from './fixtures' + +test.describe('Deferred data streaming', () => { + test('shows immediate data right away and deferred data after loading', async ({ + page, + }) => { + await page.goto('/deferred') + + // Immediate data should be available right away + 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 }, + ) + }) + + test('shows loading states for deferred content', async ({ page }) => { + // Navigate with cache disabled to ensure fresh load + await page.goto('/deferred', { waitUntil: 'commit' }) + + // Should see loading states initially (may be very brief) + // We check that deferred content eventually shows + await expect(page.getByTestId('deferred-data')).toBeVisible({ + timeout: 5000, + }) + await expect(page.getByTestId('deferred-server-data')).toBeVisible({ + 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 - proves SSR streaming works', 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/react-start/streaming-ssr/tests/fast-serial.spec.ts b/e2e/react-start/streaming-ssr/tests/fast-serial.spec.ts index 95df0555e2..339d6408ea 100644 --- a/e2e/react-start/streaming-ssr/tests/fast-serial.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/fast-serial.spec.ts @@ -1 +1,72 @@ -import '../../../streaming-ssr-specs/fast-serial' +import { expect, test, testWithHydration } from './fixtures' + +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() + + expect(responseHtml).toContain('$_TSR') + expect(responseHtml).toContain('$_TSR.router') + expect(responseHtml).toContain('$_TSR.e()') + expect(responseHtml).toContain('$tsr-stream-barrier') + }) + + test('all data is available immediately', 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 data came from server (proves SSR streaming worked) + 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/react-start/streaming-ssr/tests/fixtures.ts b/e2e/react-start/streaming-ssr/tests/fixtures.ts new file mode 100644 index 0000000000..71c564aebe --- /dev/null +++ b/e2e/react-start/streaming-ssr/tests/fixtures.ts @@ -0,0 +1,90 @@ +import { test as base, expect, type Page } from '@playwright/test' + +/** + * Verifies that React hydration has completed by clicking the global + * hydration check button and verifying the status changes. + * + * This is the canonical way to verify hydration in streaming-ssr tests. + * The HydrationCheck component is rendered in the root layout (__root.tsx). + * + * The function retries clicking until the status changes to 'hydrated', + * which handles the case where the button is visible from SSR before + * React has finished hydrating. + */ +async function verifyHydration( + page: Page, + options: { timeout?: number } = {}, +): Promise { + const timeout = options.timeout ?? 10000 + const button = page.getByTestId('hydration-check-btn') + const status = page.getByTestId('hydration-status') + + // Ensure the button is visible + await expect(button).toBeVisible() + + // Retry clicking until hydration succeeds + // This handles the case where SSR renders the button before React hydrates + await expect(async () => { + // Click the button to trigger hydration verification + await button.click() + + // Check if the status changed to 'hydrated' + await expect(status).toHaveText('hydrated', { timeout: 100 }) + }).toPass({ timeout }) +} + +export interface StreamingSsrOptions { + /** + * List of error message patterns to ignore in console output. + */ + whitelistErrors: Array +} + +/** + * Base test fixture for streaming-ssr e2e tests. + * Provides console error monitoring. + */ +export const test = base.extend({ + whitelistErrors: [[], { option: true }], + + page: async ({ page, whitelistErrors }, use) => { + const errorMessages: Array = [] + + page.on('console', (m) => { + if (m.type() === 'error') { + const text = m.text() + for (const whitelistError of whitelistErrors) { + if ( + (typeof whitelistError === 'string' && + text.includes(whitelistError)) || + (whitelistError instanceof RegExp && whitelistError.test(text)) + ) { + return + } + } + errorMessages.push(text) + } + }) + + await use(page) + + // Assert no unexpected console errors + expect(errorMessages).toEqual([]) + }, +}) + +/** + * Extended test fixture that automatically verifies hydration at the end. + * Use this for tests where you want to confirm React hydration succeeded. + */ +export const testWithHydration = test.extend({ + page: async ({ page }, use) => { + await use(page) + + // Automatically verify hydration at the end of the test + await verifyHydration(page) + }, +}) + +// Re-export expect for convenience +export { expect } diff --git a/e2e/react-start/streaming-ssr/tests/home.spec.ts b/e2e/react-start/streaming-ssr/tests/home.spec.ts index 5d49d34a56..e231d007fb 100644 --- a/e2e/react-start/streaming-ssr/tests/home.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/home.spec.ts @@ -1 +1,34 @@ -import '../../../streaming-ssr-specs/home' +import { expect, test, testWithHydration } from './fixtures' + +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/react-start/streaming-ssr/tests/many-promises.spec.ts b/e2e/react-start/streaming-ssr/tests/many-promises.spec.ts index b747bd7d0a..034ab74220 100644 --- a/e2e/react-start/streaming-ssr/tests/many-promises.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/many-promises.spec.ts @@ -1 +1,93 @@ -import '../../../streaming-ssr-specs/many-promises' +import { expect, test, testWithHydration } from './fixtures' + +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 }) + }) + + test('fast promises resolve before slow ones', async ({ page }) => { + // Navigate and check ordering - faster promises should be visible first + await page.goto('/many-promises', { waitUntil: 'commit' }) + + // Immediate promises should appear first + await expect(page.getByTestId('immediate-1')).toBeVisible({ timeout: 2000 }) + + // By the time we check very-slow, all should be visible + await expect(page.getByTestId('very-slow-2')).toBeVisible({ timeout: 5000 }) + }) +}) diff --git a/e2e/react-start/streaming-ssr/tests/nested-deferred.spec.ts b/e2e/react-start/streaming-ssr/tests/nested-deferred.spec.ts index 8df20a8a95..dbf6df4265 100644 --- a/e2e/react-start/streaming-ssr/tests/nested-deferred.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/nested-deferred.spec.ts @@ -1 +1,77 @@ -import '../../../streaming-ssr-specs/nested-deferred' +import { expect, test, testWithHydration } from './fixtures' + +test.describe('Nested deferred (multiple levels of deferred data)', () => { + test('all levels of deferred data eventually resolve', async ({ page }) => { + await page.goto('/nested-deferred') + + // Plain deferred should resolve first (300ms) + await expect(page.getByTestId('plain-deferred')).toContainText( + 'Plain deferred resolved!', + { timeout: 5000 }, + ) + + // Level 1 should resolve (200ms) + await expect(page.getByTestId('level1-data')).toContainText('Level 1:', { + timeout: 5000, + }) + + // Level 2 should resolve (400ms) + await expect(page.getByTestId('level2-data')).toContainText('Level 2:', { + timeout: 5000, + }) + + // Level 3 should resolve (600ms) + await expect(page.getByTestId('level3-data')).toContainText('Level 3:', { + timeout: 5000, + }) + }) + + test('shows loading states while data is loading', async ({ page }) => { + // Use fast navigation to catch loading states + await page.goto('/nested-deferred', { waitUntil: 'commit' }) + + // Eventually all data should be visible + await expect(page.getByTestId('level3-data')).toBeVisible({ + timeout: 10000, + }) + }) + + 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, + }) + }) + + test('data resolves in expected order (fastest first)', async ({ page }) => { + await page.goto('/nested-deferred') + + // Wait for all to be visible + await expect(page.getByTestId('level1-data')).toBeVisible({ timeout: 5000 }) + await expect(page.getByTestId('level2-data')).toBeVisible({ timeout: 5000 }) + await expect(page.getByTestId('level3-data')).toBeVisible({ timeout: 5000 }) + await expect(page.getByTestId('plain-deferred')).toBeVisible({ + timeout: 5000, + }) + }) +}) diff --git a/e2e/react-start/streaming-ssr/tests/preview-streaming.spec.ts b/e2e/react-start/streaming-ssr/tests/preview-streaming.spec.ts index 34241cfbaa..319219c519 100644 --- a/e2e/react-start/streaming-ssr/tests/preview-streaming.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/preview-streaming.spec.ts @@ -1 +1,21 @@ -import '../../../streaming-ssr-specs/preview-streaming' +import { expect, test } from './fixtures' + +test('vite preview streams HTML incrementally', async ({ page }) => { + // /deferred has immediate data + deferred data with a ~1s delay. + // Without streaming, compression buffers the entire response. + await page.goto('/deferred', { waitUntil: 'commit' }) + + // Immediate data should arrive in the first chunk + await expect(page.getByTestId('immediate-data')).toBeVisible({ + timeout: 3000, + }) + + // Deferred data (1s delay) should still be loading at this point + await expect(page.getByTestId('deferred-loading')).toBeVisible() + + // Wait for it to resolve + await expect(page.getByTestId('deferred-data')).toContainText( + 'Deferred data loaded!', + { timeout: 5000 }, + ) +}) diff --git a/e2e/react-start/streaming-ssr/tests/query-heavy.spec.ts b/e2e/react-start/streaming-ssr/tests/query-heavy.spec.ts index e0d617106c..8e735040c2 100644 --- a/e2e/react-start/streaming-ssr/tests/query-heavy.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/query-heavy.spec.ts @@ -1,18 +1,168 @@ -import '../../../streaming-ssr-specs/query-heavy' -import { expect, test } from '../../../streaming-ssr-assertions' +import { expect, test, testWithHydration } from './fixtures' -test('batches same-turn queries into one stream chunk', async ({ request }) => { - const response = await request.get('/query-heavy') - const html = await response.text() - const scripts = Array.from( - html.matchAll(/]*>([\s\S]*?)<\/script>/g), - (match) => match[1]!, - ) - const syncQueryChunk = scripts.find((script) => - script.includes('sync-value-1'), - ) +test.describe('Query heavy route (9 useSuspenseQuery)', () => { + test('all queries resolve with server data', async ({ page }) => { + await page.goto('/query-heavy') - expect(syncQueryChunk).toBeDefined() - expect(syncQueryChunk).toContain('sync-value-2') - expect(syncQueryChunk).toContain('sync-value-3') + // 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('no hydration mismatch - queries streamed from server', async ({ + page, + }) => { + // This test verifies that query data is streamed from server + // If it wasn't, the queries would re-execute on client and show 'client' as source + await page.goto('/query-heavy') + + // Wait for all queries + await expect(page.getByTestId('slow-async-query-3')).toBeVisible({ + timeout: 5000, + }) + + // Verify all show 'server' - this proves data was streamed, not re-fetched + const serverSourceCount = await page + .locator('[data-testid*="query-"]') + .filter({ hasText: 'source: server' }) + .count() + expect(serverSourceCount).toBe(9) + }) + + test('emits query stream data before stream end marker', async ({ + request, + }) => { + const response = await request.get('/query-heavy') + const html = await response.text() + const endMarker = '$_TSR.e()' + const endIndex = html.indexOf(endMarker) + const slowAsyncPayloadIndex = html.indexOf('"slow-async-3"') + const lastScriptOpen = html.lastIndexOf('', 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('')) + }) + + test('batches same-turn queries into one stream chunk', async ({ + request, + }) => { + const response = await request.get('/query-heavy') + const html = await response.text() + const scripts = Array.from( + html.matchAll(/]*>([\s\S]*?)<\/script>/g), + (match) => match[1]!, + ) + const syncQueryChunk = scripts.find( + (script) => script.includes('.next(') && script.includes('sync-value-1'), + ) + + 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 deleted file mode 100644 index a9cf8a8142..0000000000 --- a/e2e/react-start/streaming-ssr/tests/router-html-buffer.spec.ts +++ /dev/null @@ -1,34 +0,0 @@ -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 0d5a87363f..c3631a7fc0 100644 --- a/e2e/react-start/streaming-ssr/tests/slow-render.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/slow-render.spec.ts @@ -1 +1,73 @@ -import '../../../streaming-ssr-specs/slow-render' +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', + ) + }) +}) diff --git a/e2e/react-start/streaming-ssr/tests/stream.spec.ts b/e2e/react-start/streaming-ssr/tests/stream.spec.ts index a51614f09a..5e4c134f82 100644 --- a/e2e/react-start/streaming-ssr/tests/stream.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/stream.spec.ts @@ -1 +1,46 @@ -import '../../../streaming-ssr-specs/stream' +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, + }) + }, + ) +}) 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 0e9278d3f2..a0060a07ee 100644 --- a/e2e/react-start/streaming-ssr/tests/sync-only.spec.ts +++ b/e2e/react-start/streaming-ssr/tests/sync-only.spec.ts @@ -1 +1,84 @@ -import '../../../streaming-ssr-specs/sync-only' +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!', + ) +}) diff --git a/e2e/react-start/streaming-ssr/vite.config.ts b/e2e/react-start/streaming-ssr/vite.config.ts index 0590c197a5..275bfacde2 100644 --- a/e2e/react-start/streaming-ssr/vite.config.ts +++ b/e2e/react-start/streaming-ssr/vite.config.ts @@ -1,10 +1,9 @@ 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(), viteReact()], + plugins: [tanstackStart()], }) diff --git a/e2e/react-start/transform-asset-urls/package.json b/e2e/react-start/transform-asset-urls/package.json index e0a5ffec59..95e39e459b 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; 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: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:options:matrix": "pnpm test:e2e:options:transform:cache-true:warmup-true && pnpm test:e2e:options:transform:cache-true:warmup-false && pnpm test:e2e:options:transform:cache-false:warmup-true && pnpm test:e2e:options:transform:cache-false:warmup-false && pnpm test:e2e:options:createTransform:cache-true:warmup-true && pnpm test:e2e:options:createTransform:cache-true:warmup-false && pnpm test:e2e:options:createTransform:cache-false:warmup-true && pnpm test:e2e:options:createTransform:cache-false:warmup-false", "test:e2e": "pnpm test:e2e:string && pnpm test:e2e:function && pnpm test:e2e:options:matrix" }, @@ -46,7 +46,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@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 209a7e0596..bbef6838fe 100644 --- a/e2e/react-start/transform-asset-urls/playwright.config.ts +++ b/e2e/react-start/transform-asset-urls/playwright.config.ts @@ -1,10 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const APP_PORT = Number(process.env.E2E_APP_PORT ?? 0) -const CDN_PORT = Number(process.env.E2E_CDN_PORT ?? 0) +const APP_PORT = await getTestServerPort(packageJson.name) +const CDN_PORT = await getTestServerPort(`${packageJson.name}_cdn`) 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' @@ -24,11 +26,8 @@ export default defineConfig({ { // CDN server — serves built client assets on a separate port with CORS command: `node tests/cdn-server.mjs`, - wait: { - stdout: - /CDN Server: (?http:\/\/localhost:(?\d+))/, - }, - reuseExistingServer: false, + url: `http://localhost:${CDN_PORT}/health`, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { CDN_PORT: String(CDN_PORT), @@ -38,11 +37,12 @@ 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`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, 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/tests/cdn-server.mjs b/e2e/react-start/transform-asset-urls/tests/cdn-server.mjs index 280c626867..ea9bf62cd0 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 = Number(process.env.CDN_PORT ?? 0) +const port = process.env.CDN_PORT || 3002 const app = express() @@ -36,7 +36,7 @@ app.use((req, res, next) => { app.use(express.static(path.resolve(__dirname, '..', 'dist', 'client'))) -const server = app.listen(port, (error) => { +app.listen(port, (error) => { if (error) throw error - console.info(`CDN Server: http://localhost:${server.address().port}`) + console.info(`CDN Server: http://localhost:${port}`) }) diff --git a/e2e/react-start/virtual-routes/package.json b/e2e/react-start/virtual-routes/package.json index c415d1845e..9648dd2c99 100644 --- a/e2e/react-start/virtual-routes/package.json +++ b/e2e/react-start/virtual-routes/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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -31,7 +31,7 @@ "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/react-start/virtual-routes/playwright.config.ts b/e2e/react-start/virtual-routes/playwright.config.ts index 1862174905..b0c365f8bd 100644 --- a/e2e/react-start/virtual-routes/playwright.config.ts +++ b/e2e/react-start/virtual-routes/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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}` /** @@ -13,19 +18,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: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/react-start/virtual-routes/src/posts.tsx b/e2e/react-start/virtual-routes/src/posts.tsx index cc3cb0f9c8..01831e335c 100644 --- a/e2e/react-start/virtual-routes/src/posts.tsx +++ b/e2e/react-start/virtual-routes/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/react-start/virtual-routes/src/utils/posts.tsx b/e2e/react-start/virtual-routes/src/utils/posts.tsx index d9b98a8c9c..4cc5dcc4c6 100644 --- a/e2e/react-start/virtual-routes/src/utils/posts.tsx +++ b/e2e/react-start/virtual-routes/src/utils/posts.tsx @@ -8,7 +8,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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) diff --git a/e2e/react-start/virtual-routes/src/utils/users.tsx b/e2e/react-start/virtual-routes/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/react-start/virtual-routes/src/utils/users.tsx +++ b/e2e/react-start/virtual-routes/src/utils/users.tsx @@ -3,3 +3,7 @@ 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/virtual-routes/tests/app.spec.ts b/e2e/react-start/virtual-routes/tests/app.spec.ts index e9db98e3f3..3182febfa0 100644 --- a/e2e/react-start/virtual-routes/tests/app.spec.ts +++ b/e2e/react-start/virtual-routes/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/react-start/virtual-routes/tests/setup/global.setup.ts b/e2e/react-start/virtual-routes/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/react-start/virtual-routes/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/virtual-routes/tests/setup/global.teardown.ts b/e2e/react-start/virtual-routes/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/react-start/virtual-routes/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/website/package.json b/e2e/react-start/website/package.json index 1a5c3e1f4e..4c8461a3b5 100644 --- a/e2e/react-start/website/package.json +++ b/e2e/react-start/website/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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/react-router": "workspace:^", @@ -29,7 +29,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/react-start/website/playwright.config.ts b/e2e/react-start/website/playwright.config.ts index 82678ac00b..18b8905468 100644 --- a/e2e/react-start/website/playwright.config.ts +++ b/e2e/react-start/website/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/scroll-restoration-lifecycle.ts b/e2e/scroll-restoration-lifecycle.ts deleted file mode 100644 index def0d10934..0000000000 --- a/e2e/scroll-restoration-lifecycle.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { expect } from '@playwright/test' - -// These exercise browser lifecycle handlers, not actual BFCache navigation. -export function scrollRestorationLifecycleTests( - test: typeof import('./e2e-utils/src/fixture').test, -) { - test.beforeEach(async ({ page }) => { - await page.goto('/normal-page') - await expect - .poll(() => page.evaluate(() => history.scrollRestoration)) - .toBe('manual') - await page.waitForLoadState('networkidle') - }) - - for (const persisted of [false, true]) { - test(`pagehide hands control back with persisted=${persisted}`, async ({ - page, - }) => { - const mode = await page.evaluate((persisted) => { - dispatchEvent(new PageTransitionEvent('pagehide', { persisted })) - return history.scrollRestoration - }, persisted) - expect(mode).toBe('auto') - }) - - test(`pageshow reclaims control only with persisted=${persisted}`, async ({ - page, - }) => { - const mode = await page.evaluate((persisted) => { - // Model the state left by pagehide before the document resumes. - history.scrollRestoration = 'auto' - dispatchEvent(new PageTransitionEvent('pageshow', { persisted })) - return history.scrollRestoration - }, persisted) - expect(mode).toBe(persisted ? 'manual' : 'auto') - }) - } - - test('repeats the handoff when a cached document resumes more than once', async ({ - page, - }) => { - const modes = await page.evaluate(() => { - const modes: Array = [] - for (let i = 0; i < 3; i++) { - dispatchEvent(new PageTransitionEvent('pagehide', { persisted: true })) - modes.push(history.scrollRestoration) - dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true })) - modes.push(history.scrollRestoration) - } - return modes - }) - expect(modes).toEqual([ - 'auto', - 'manual', - 'auto', - 'manual', - 'auto', - 'manual', - ]) - }) -} diff --git a/e2e/solid-router/basepath-file-based/package.json b/e2e/solid-router/basepath-file-based/package.json index bc54799989..4b27235857 100644 --- a/e2e/solid-router/basepath-file-based/package.json +++ b/e2e/solid-router/basepath-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/solid-router": "workspace:^", diff --git a/e2e/solid-router/basepath-file-based/playwright.config.ts b/e2e/solid-router/basepath-file-based/playwright.config.ts index 4eead86444..6069bbe59f 100644 --- a/e2e/solid-router/basepath-file-based/playwright.config.ts +++ b/e2e/solid-router/basepath-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', }, diff --git a/e2e/solid-router/basepath-file-based/tests/setup/global.setup.ts b/e2e/solid-router/basepath-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/solid-router/basepath-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/solid-router/basepath-file-based/tests/setup/global.teardown.ts b/e2e/solid-router/basepath-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/solid-router/basepath-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/solid-router/basic-esbuild-file-based/package.json b/e2e/solid-router/basic-esbuild-file-based/package.json index e2448db01b..d3b10307d2 100644 --- a/e2e/solid-router/basic-esbuild-file-based/package.json +++ b/e2e/solid-router/basic-esbuild-file-based/package.json @@ -7,7 +7,7 @@ "build": "esbuild src/main.tsx --jsx=preserve --jsx-import-source=solid-js --bundle --outfile=dist/main.js && tsc --noEmit", "serve": "esbuild src/main.tsx --jsx=preserve --jsx-import-source=solid-js --bundle --outfile=dist/main.js --servedir=.", "start": "dev", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/router-plugin": "workspace:^", diff --git a/e2e/solid-router/basic-esbuild-file-based/playwright.config.ts b/e2e/solid-router/basic-esbuild-file-based/playwright.config.ts index 972dd66d72..a0e9c0f041 100644 --- a/e2e/solid-router/basic-esbuild-file-based/playwright.config.ts +++ b/e2e/solid-router/basic-esbuild-file-based/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `pnpm run build && pnpm run serve --serve=${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/solid-router/basic-esbuild-file-based/src/esbuild.config.js b/e2e/solid-router/basic-esbuild-file-based/src/esbuild.config.js index 68d31fe754..2d6ea80c1b 100644 --- a/e2e/solid-router/basic-esbuild-file-based/src/esbuild.config.js +++ b/e2e/solid-router/basic-esbuild-file-based/src/esbuild.config.js @@ -6,6 +6,7 @@ export default { plugins: [ tanstackRouter({ target: 'solid', + autoCodeSplitting: true, }), solidPlugin(), ], diff --git a/e2e/solid-router/basic-file-based-code-splitting/package.json b/e2e/solid-router/basic-file-based-code-splitting/package.json index bb4cc2291e..daf7e5d998 100644 --- a/e2e/solid-router/basic-file-based-code-splitting/package.json +++ b/e2e/solid-router/basic-file-based-code-splitting/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/solid-router/basic-file-based-code-splitting/playwright.config.ts b/e2e/solid-router/basic-file-based-code-splitting/playwright.config.ts index 4eead86444..836ea41bd8 100644 --- a/e2e/solid-router/basic-file-based-code-splitting/playwright.config.ts +++ b/e2e/solid-router/basic-file-based-code-splitting/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', }, diff --git a/e2e/solid-router/basic-file-based-code-splitting/src/posts.tsx b/e2e/solid-router/basic-file-based-code-splitting/src/posts.tsx index d5f0ce903d..aebe80648f 100644 --- a/e2e/solid-router/basic-file-based-code-splitting/src/posts.tsx +++ b/e2e/solid-router/basic-file-based-code-splitting/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/solid-router/basic-file-based-code-splitting/tests/app.spec.ts b/e2e/solid-router/basic-file-based-code-splitting/tests/app.spec.ts index fbf093cd51..3e5a69ccaa 100644 --- a/e2e/solid-router/basic-file-based-code-splitting/tests/app.spec.ts +++ b/e2e/solid-router/basic-file-based-code-splitting/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/solid-router/basic-file-based-code-splitting/tests/preload.spec.ts b/e2e/solid-router/basic-file-based-code-splitting/tests/preload.spec.ts index fd17fcc47b..0bc3265760 100644 --- a/e2e/solid-router/basic-file-based-code-splitting/tests/preload.spec.ts +++ b/e2e/solid-router/basic-file-based-code-splitting/tests/preload.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/solid-router/basic-file-based-code-splitting/tests/setup/global.setup.ts b/e2e/solid-router/basic-file-based-code-splitting/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/solid-router/basic-file-based-code-splitting/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/solid-router/basic-file-based-code-splitting/tests/setup/global.teardown.ts b/e2e/solid-router/basic-file-based-code-splitting/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/solid-router/basic-file-based-code-splitting/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/solid-router/basic-file-based/package.json b/e2e/solid-router/basic-file-based/package.json index bb882e2786..140e763f43 100644 --- a/e2e/solid-router/basic-file-based/package.json +++ b/e2e/solid-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": "playwright test --project=chromium" + "test:e2e:default": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/solid-router/basic-file-based/playwright.config.ts b/e2e/solid-router/basic-file-based/playwright.config.ts index ea3ef9ffec..6e4e1d7703 100644 --- a/e2e/solid-router/basic-file-based/playwright.config.ts +++ b/e2e/solid-router/basic-file-based/playwright.config.ts @@ -1,9 +1,14 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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}` -const command = `pnpm build && pnpm preview --host 0.0.0.0 --port ${PORT}` +const command = `pnpm build && pnpm preview --port ${PORT}` console.info('Running with mode: ', process.env.MODE || 'default') @@ -16,6 +21,9 @@ 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, @@ -23,12 +31,15 @@ export default defineConfig({ webServer: { command, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, 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/solid-router/basic-file-based/src/posts.tsx b/e2e/solid-router/basic-file-based/src/posts.tsx index 6df270c619..909620abf9 100644 --- a/e2e/solid-router/basic-file-based/src/posts.tsx +++ b/e2e/solid-router/basic-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/solid-router/basic-file-based/src/routeTree.gen.ts b/e2e/solid-router/basic-file-based/src/routeTree.gen.ts index 7601b581cc..c7cbb94b56 100644 --- a/e2e/solid-router/basic-file-based/src/routeTree.gen.ts +++ b/e2e/solid-router/basic-file-based/src/routeTree.gen.ts @@ -1451,7 +1451,7 @@ declare module '@tanstack/solid-router' { '/(group)/_layout': { id: '/(group)/_layout' path: '' - fullPath: '/' + fullPath: '' preLoaderRoute: typeof groupLayoutRouteImport parentRoute: typeof rootRouteImport } diff --git a/e2e/solid-router/basic-file-based/tests/app.spec.ts b/e2e/solid-router/basic-file-based/tests/app.spec.ts index 274d234031..f535fdd78c 100644 --- a/e2e/solid-router/basic-file-based/tests/app.spec.ts +++ b/e2e/solid-router/basic-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import type { Page } from '@playwright/test' test.beforeEach(async ({ page }) => { diff --git a/e2e/solid-router/basic-file-based/tests/hover-preload-hash.spec.ts b/e2e/solid-router/basic-file-based/tests/hover-preload-hash.spec.ts index 1263faf391..b090c2a6b7 100644 --- a/e2e/solid-router/basic-file-based/tests/hover-preload-hash.spec.ts +++ b/e2e/solid-router/basic-file-based/tests/hover-preload-hash.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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/solid-router/basic-file-based/tests/mask.spec.ts b/e2e/solid-router/basic-file-based/tests/mask.spec.ts index 9a7ee8a1c8..f6ec42c604 100644 --- a/e2e/solid-router/basic-file-based/tests/mask.spec.ts +++ b/e2e/solid-router/basic-file-based/tests/mask.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test('route masks transform params and expose masked pathname in the browser (solid)', async ({ page, diff --git a/e2e/solid-router/basic-file-based/tests/non-nested-paths.spec.ts b/e2e/solid-router/basic-file-based/tests/non-nested-paths.spec.ts index ea0e585c75..dccdfd4acf 100644 --- a/e2e/solid-router/basic-file-based/tests/non-nested-paths.spec.ts +++ b/e2e/solid-router/basic-file-based/tests/non-nested-paths.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' const testCases: Array<{ name: string diff --git a/e2e/solid-router/basic-file-based/tests/params.spec.ts b/e2e/solid-router/basic-file-based/tests/params.spec.ts index 6014689ed2..ca9b2ca429 100644 --- a/e2e/solid-router/basic-file-based/tests/params.spec.ts +++ b/e2e/solid-router/basic-file-based/tests/params.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import type { Page } from '@playwright/test' test.beforeEach(async ({ page }) => { diff --git a/e2e/solid-router/basic-file-based/tests/redirect.spec.ts b/e2e/solid-router/basic-file-based/tests/redirect.spec.ts index c3604ccb92..4375aa6673 100644 --- a/e2e/solid-router/basic-file-based/tests/redirect.spec.ts +++ b/e2e/solid-router/basic-file-based/tests/redirect.spec.ts @@ -1,13 +1,19 @@ import queryString from 'node:querystring' -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import combinateImport from 'combinate' +import { + getDummyServerPort, + getTestServerPort, + localDummyServer, +} from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } +import type { Server } from 'node:http' // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const EXTERNAL_ORIGIN = `http://127.0.0.1:${PORT}` +const PORT = await getTestServerPort(packageJson.name) +const EXTERNAL_HOST_PORT = await getDummyServerPort(packageJson.name) test.describe('redirects', () => { const internalNavigationTestMatrix = combinate({ @@ -35,7 +41,7 @@ test.describe('redirects', () => { const requestPromise = new Promise((resolve) => { page.on('request', (request) => { if ( - request.url() === 'https://jsonplaceholder.typicode.com/posts' + request.url() === `http://localhost:${EXTERNAL_HOST_PORT}/posts` ) { requestHappened = true resolve() @@ -100,8 +106,8 @@ test.describe('redirects', () => { }) => { await page.waitForLoadState('networkidle') - const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + let q = queryString.stringify({ + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, }) if (scenario === 'navigate') { await page.goto(`/redirect/external?${q}`) @@ -110,7 +116,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/external/via-${thrower}?${q}`) } - const url = `${EXTERNAL_ORIGIN}/` + const url = `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) diff --git a/e2e/solid-router/basic-file-based/tests/relative.spec.ts b/e2e/solid-router/basic-file-based/tests/relative.spec.ts index f62c248680..4850d3630d 100644 --- a/e2e/solid-router/basic-file-based/tests/relative.spec.ts +++ b/e2e/solid-router/basic-file-based/tests/relative.spec.ts @@ -1,11 +1,12 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) test.describe('relative_routing', () => { const internalNavigationTestMatrix = combinate({ diff --git a/e2e/solid-router/basic-file-based/tests/scroll-into-view.spec.ts b/e2e/solid-router/basic-file-based/tests/scroll-into-view.spec.ts index 6730959838..d1af86adfb 100644 --- a/e2e/solid-router/basic-file-based/tests/scroll-into-view.spec.ts +++ b/e2e/solid-router/basic-file-based/tests/scroll-into-view.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import type { Page } from '@playwright/test' const anchors = { diff --git a/e2e/solid-router/basic-file-based/tests/search-params.spec.ts b/e2e/solid-router/basic-file-based/tests/search-params.spec.ts index a99488a47a..d6307cbcf8 100644 --- a/e2e/solid-router/basic-file-based/tests/search-params.spec.ts +++ b/e2e/solid-router/basic-file-based/tests/search-params.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.describe('/search-params/default', () => { test('Directly visiting the route without search param set', async ({ diff --git a/e2e/solid-router/basic-file-based/tests/setup/global.setup.ts b/e2e/solid-router/basic-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/solid-router/basic-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/solid-router/basic-file-based/tests/setup/global.teardown.ts b/e2e/solid-router/basic-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/solid-router/basic-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/solid-router/basic-file-based/tests/transition.spec.ts b/e2e/solid-router/basic-file-based/tests/transition.spec.ts index 06f6d04a77..b777c52862 100644 --- a/e2e/solid-router/basic-file-based/tests/transition.spec.ts +++ b/e2e/solid-router/basic-file-based/tests/transition.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test('transitions/count/create-resource should keep old values visible during navigation', async ({ page, diff --git a/e2e/solid-router/basic-scroll-restoration/package.json b/e2e/solid-router/basic-scroll-restoration/package.json index e2b945cb6a..8e93ddfc72 100644 --- a/e2e/solid-router/basic-scroll-restoration/package.json +++ b/e2e/solid-router/basic-scroll-restoration/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/solid-router/basic-scroll-restoration/playwright.config.ts b/e2e/solid-router/basic-scroll-restoration/playwright.config.ts index 6a684ac89e..0c5cee43e4 100644 --- a/e2e/solid-router/basic-scroll-restoration/playwright.config.ts +++ b/e2e/solid-router/basic-scroll-restoration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/solid-router/basic-solid-query-file-based/package.json b/e2e/solid-router/basic-solid-query-file-based/package.json index 5243275066..1a5c393d1a 100644 --- a/e2e/solid-router/basic-solid-query-file-based/package.json +++ b/e2e/solid-router/basic-solid-query-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/solid-router/basic-solid-query-file-based/playwright.config.ts b/e2e/solid-router/basic-solid-query-file-based/playwright.config.ts index 4eead86444..836ea41bd8 100644 --- a/e2e/solid-router/basic-solid-query-file-based/playwright.config.ts +++ b/e2e/solid-router/basic-solid-query-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', }, diff --git a/e2e/solid-router/basic-solid-query-file-based/src/posts.tsx b/e2e/solid-router/basic-solid-query-file-based/src/posts.tsx index 1f6cb8e308..1becc2c242 100644 --- a/e2e/solid-router/basic-solid-query-file-based/src/posts.tsx +++ b/e2e/solid-router/basic-solid-query-file-based/src/posts.tsx @@ -8,7 +8,11 @@ export type PostType = { export class PostNotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +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 = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/solid-router/basic-solid-query-file-based/tests/app.spec.ts b/e2e/solid-router/basic-solid-query-file-based/tests/app.spec.ts index fbf093cd51..3e5a69ccaa 100644 --- a/e2e/solid-router/basic-solid-query-file-based/tests/app.spec.ts +++ b/e2e/solid-router/basic-solid-query-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/solid-router/basic-solid-query-file-based/tests/setup/global.setup.ts b/e2e/solid-router/basic-solid-query-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/solid-router/basic-solid-query-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/solid-router/basic-solid-query-file-based/tests/setup/global.teardown.ts b/e2e/solid-router/basic-solid-query-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/solid-router/basic-solid-query-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/solid-router/basic-solid-query/package.json b/e2e/solid-router/basic-solid-query/package.json index 1efe55fa60..93469e3699 100644 --- a/e2e/solid-router/basic-solid-query/package.json +++ b/e2e/solid-router/basic-solid-query/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/solid-router/basic-solid-query/playwright.config.ts b/e2e/solid-router/basic-solid-query/playwright.config.ts index e7b8439dba..1faa47a497 100644 --- a/e2e/solid-router/basic-solid-query/playwright.config.ts +++ b/e2e/solid-router/basic-solid-query/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -13,15 +18,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', }, diff --git a/e2e/solid-router/basic-solid-query/src/posts.ts b/e2e/solid-router/basic-solid-query/src/posts.ts index 392fd2deb0..9700a8463a 100644 --- a/e2e/solid-router/basic-solid-query/src/posts.ts +++ b/e2e/solid-router/basic-solid-query/src/posts.ts @@ -9,7 +9,11 @@ type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} const fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/solid-router/basic-solid-query/tests/app.spec.ts b/e2e/solid-router/basic-solid-query/tests/app.spec.ts index fbf093cd51..3e5a69ccaa 100644 --- a/e2e/solid-router/basic-solid-query/tests/app.spec.ts +++ b/e2e/solid-router/basic-solid-query/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/solid-router/basic-solid-query/tests/setup/global.setup.ts b/e2e/solid-router/basic-solid-query/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/solid-router/basic-solid-query/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/solid-router/basic-solid-query/tests/setup/global.teardown.ts b/e2e/solid-router/basic-solid-query/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/solid-router/basic-solid-query/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/solid-router/basic-virtual-file-based/package.json b/e2e/solid-router/basic-virtual-file-based/package.json index 4f188d9262..9e7dafd46a 100644 --- a/e2e/solid-router/basic-virtual-file-based/package.json +++ b/e2e/solid-router/basic-virtual-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/solid-router/basic-virtual-file-based/playwright.config.ts b/e2e/solid-router/basic-virtual-file-based/playwright.config.ts index 4eead86444..836ea41bd8 100644 --- a/e2e/solid-router/basic-virtual-file-based/playwright.config.ts +++ b/e2e/solid-router/basic-virtual-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', }, diff --git a/e2e/solid-router/basic-virtual-file-based/src/posts.tsx b/e2e/solid-router/basic-virtual-file-based/src/posts.tsx index d5f0ce903d..aebe80648f 100644 --- a/e2e/solid-router/basic-virtual-file-based/src/posts.tsx +++ b/e2e/solid-router/basic-virtual-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/solid-router/basic-virtual-file-based/tests/app.spec.ts b/e2e/solid-router/basic-virtual-file-based/tests/app.spec.ts index fbf093cd51..3e5a69ccaa 100644 --- a/e2e/solid-router/basic-virtual-file-based/tests/app.spec.ts +++ b/e2e/solid-router/basic-virtual-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/solid-router/basic-virtual-file-based/tests/setup/global.setup.ts b/e2e/solid-router/basic-virtual-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/solid-router/basic-virtual-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/solid-router/basic-virtual-file-based/tests/setup/global.teardown.ts b/e2e/solid-router/basic-virtual-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/solid-router/basic-virtual-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/solid-router/basic-virtual-named-export-config-file-based/package.json b/e2e/solid-router/basic-virtual-named-export-config-file-based/package.json index 7a29e6576a..6a8b6de158 100644 --- a/e2e/solid-router/basic-virtual-named-export-config-file-based/package.json +++ b/e2e/solid-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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/solid-router/basic-virtual-named-export-config-file-based/playwright.config.ts b/e2e/solid-router/basic-virtual-named-export-config-file-based/playwright.config.ts index 4eead86444..836ea41bd8 100644 --- a/e2e/solid-router/basic-virtual-named-export-config-file-based/playwright.config.ts +++ b/e2e/solid-router/basic-virtual-named-export-config-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', }, diff --git a/e2e/solid-router/basic-virtual-named-export-config-file-based/src/posts.tsx b/e2e/solid-router/basic-virtual-named-export-config-file-based/src/posts.tsx index d5f0ce903d..aebe80648f 100644 --- a/e2e/solid-router/basic-virtual-named-export-config-file-based/src/posts.tsx +++ b/e2e/solid-router/basic-virtual-named-export-config-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/solid-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts b/e2e/solid-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts index fbf093cd51..3e5a69ccaa 100644 --- a/e2e/solid-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts +++ b/e2e/solid-router/basic-virtual-named-export-config-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/solid-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts b/e2e/solid-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/solid-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/solid-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts b/e2e/solid-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/solid-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/solid-router/basic/package.json b/e2e/solid-router/basic/package.json index 29f10e19ff..33479274b6 100644 --- a/e2e/solid-router/basic/package.json +++ b/e2e/solid-router/basic/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/solid-router/basic/playwright.config.ts b/e2e/solid-router/basic/playwright.config.ts index 4eead86444..836ea41bd8 100644 --- a/e2e/solid-router/basic/playwright.config.ts +++ b/e2e/solid-router/basic/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', }, diff --git a/e2e/solid-router/basic/src/posts.ts b/e2e/solid-router/basic/src/posts.ts index f72d16fee3..e859645746 100644 --- a/e2e/solid-router/basic/src/posts.ts +++ b/e2e/solid-router/basic/src/posts.ts @@ -8,7 +8,11 @@ type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/solid-router/basic/tests/app.spec.ts b/e2e/solid-router/basic/tests/app.spec.ts index 9c0a6b6901..ec0e24d8a4 100644 --- a/e2e/solid-router/basic/tests/app.spec.ts +++ b/e2e/solid-router/basic/tests/app.spec.ts @@ -1,7 +1,8 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/solid-router/basic/tests/params.spec.ts b/e2e/solid-router/basic/tests/params.spec.ts index f673138047..ac18f39864 100644 --- a/e2e/solid-router/basic/tests/params.spec.ts +++ b/e2e/solid-router/basic/tests/params.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.describe('params operations + prefix/suffix', () => { test.beforeEach(async ({ page }) => { diff --git a/e2e/solid-router/basic/tests/setup/global.setup.ts b/e2e/solid-router/basic/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/solid-router/basic/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/solid-router/basic/tests/setup/global.teardown.ts b/e2e/solid-router/basic/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/solid-router/basic/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/solid-router/generator-cli-only/package.json b/e2e/solid-router/generator-cli-only/package.json index 55fd448971..64e98187d6 100644 --- a/e2e/solid-router/generator-cli-only/package.json +++ b/e2e/solid-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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/solid-router/generator-cli-only/playwright.config.ts b/e2e/solid-router/generator-cli-only/playwright.config.ts index 4eead86444..c9d9a76ae7 100644 --- a/e2e/solid-router/generator-cli-only/playwright.config.ts +++ b/e2e/solid-router/generator-cli-only/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', }, diff --git a/e2e/solid-router/generator-cli-only/src/posts.ts b/e2e/solid-router/generator-cli-only/src/posts.ts index f72d16fee3..e859645746 100644 --- a/e2e/solid-router/generator-cli-only/src/posts.ts +++ b/e2e/solid-router/generator-cli-only/src/posts.ts @@ -8,7 +8,11 @@ type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/solid-router/generator-cli-only/tests/app.spec.ts b/e2e/solid-router/generator-cli-only/tests/app.spec.ts index ced5ac9310..5a83a314f2 100644 --- a/e2e/solid-router/generator-cli-only/tests/app.spec.ts +++ b/e2e/solid-router/generator-cli-only/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/solid-router/generator-cli-only/tests/setup/global.setup.ts b/e2e/solid-router/generator-cli-only/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/solid-router/generator-cli-only/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/solid-router/generator-cli-only/tests/setup/global.teardown.ts b/e2e/solid-router/generator-cli-only/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/solid-router/generator-cli-only/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/solid-router/js-only-file-based/package.json b/e2e/solid-router/js-only-file-based/package.json index 3704edb6f9..8b3cc0b83b 100644 --- a/e2e/solid-router/js-only-file-based/package.json +++ b/e2e/solid-router/js-only-file-based/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/solid-router/js-only-file-based/playwright.config.ts b/e2e/solid-router/js-only-file-based/playwright.config.ts index 0925936d55..4f93bc1413 100644 --- a/e2e/solid-router/js-only-file-based/playwright.config.ts +++ b/e2e/solid-router/js-only-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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}` /** @@ -13,15 +18,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', }, diff --git a/e2e/solid-router/js-only-file-based/src/posts.js b/e2e/solid-router/js-only-file-based/src/posts.js index 36c1c281f6..979e5e381c 100644 --- a/e2e/solid-router/js-only-file-based/src/posts.js +++ b/e2e/solid-router/js-only-file-based/src/posts.js @@ -2,7 +2,11 @@ import axios from 'redaxios' export class NotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +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 fetchPosts = async () => { console.info('Fetching posts...') diff --git a/e2e/solid-router/js-only-file-based/tests/app.spec.ts b/e2e/solid-router/js-only-file-based/tests/app.spec.ts index ced5ac9310..5a83a314f2 100644 --- a/e2e/solid-router/js-only-file-based/tests/app.spec.ts +++ b/e2e/solid-router/js-only-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/solid-router/js-only-file-based/tests/setup/global.setup.ts b/e2e/solid-router/js-only-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/solid-router/js-only-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/solid-router/js-only-file-based/tests/setup/global.teardown.ts b/e2e/solid-router/js-only-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/solid-router/js-only-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/solid-router/rspack-basic-file-based/package.json b/e2e/solid-router/rspack-basic-file-based/package.json index 4015f0f606..23842edeaa 100644 --- a/e2e/solid-router/rspack-basic-file-based/package.json +++ b/e2e/solid-router/rspack-basic-file-based/package.json @@ -7,7 +7,7 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/solid-router": "workspace:^", @@ -17,7 +17,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-babel": "^1.1.2", "@rsbuild/plugin-solid": "^1.1.1", "@tailwindcss/postcss": "^4.2.2", diff --git a/e2e/solid-router/rspack-basic-file-based/playwright.config.ts b/e2e/solid-router/rspack-basic-file-based/playwright.config.ts index 4eead86444..5f20415459 100644 --- a/e2e/solid-router/rspack-basic-file-based/playwright.config.ts +++ b/e2e/solid-router/rspack-basic-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', }, diff --git a/e2e/solid-router/rspack-basic-file-based/src/posts.tsx b/e2e/solid-router/rspack-basic-file-based/src/posts.tsx index d5f0ce903d..93faeb7c27 100644 --- a/e2e/solid-router/rspack-basic-file-based/src/posts.tsx +++ b/e2e/solid-router/rspack-basic-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.PUBLIC_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/solid-router/rspack-basic-file-based/tests/app.spec.ts b/e2e/solid-router/rspack-basic-file-based/tests/app.spec.ts index d230263bfe..10beff655f 100644 --- a/e2e/solid-router/rspack-basic-file-based/tests/app.spec.ts +++ b/e2e/solid-router/rspack-basic-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/solid-router/rspack-basic-file-based/tests/setup/global.setup.ts b/e2e/solid-router/rspack-basic-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/solid-router/rspack-basic-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/solid-router/rspack-basic-file-based/tests/setup/global.teardown.ts b/e2e/solid-router/rspack-basic-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/solid-router/rspack-basic-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/solid-router/rspack-basic-virtual-named-export-config-file-based/package.json b/e2e/solid-router/rspack-basic-virtual-named-export-config-file-based/package.json index 3772d7beb1..f5e36a5ab5 100644 --- a/e2e/solid-router/rspack-basic-virtual-named-export-config-file-based/package.json +++ b/e2e/solid-router/rspack-basic-virtual-named-export-config-file-based/package.json @@ -7,7 +7,7 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/solid-router": "workspace:^", @@ -17,7 +17,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-babel": "^1.1.2", "@rsbuild/plugin-solid": "^1.1.1", "@tailwindcss/postcss": "^4.2.2", diff --git a/e2e/solid-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts b/e2e/solid-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts index 1c1d021f2f..bf3adc082c 100644 --- a/e2e/solid-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts +++ b/e2e/solid-router/rspack-basic-virtual-named-export-config-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm start --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', }, diff --git a/e2e/solid-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx b/e2e/solid-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx index d5f0ce903d..93faeb7c27 100644 --- a/e2e/solid-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx +++ b/e2e/solid-router/rspack-basic-virtual-named-export-config-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.PUBLIC_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/solid-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts b/e2e/solid-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts index d230263bfe..10beff655f 100644 --- a/e2e/solid-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts +++ b/e2e/solid-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/solid-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts b/e2e/solid-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/solid-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/solid-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts b/e2e/solid-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/solid-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/solid-router/scroll-restoration-sandbox-vite/package.json b/e2e/solid-router/scroll-restoration-sandbox-vite/package.json index cd816f7e09..128b4c0790 100644 --- a/e2e/solid-router/scroll-restoration-sandbox-vite/package.json +++ b/e2e/solid-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": "pnpm run test:e2e:browser && pnpm run test:e2e:hash" + "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:browser && pnpm run test:e2e:hash" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -28,15 +28,5 @@ "@tanstack/router-e2e-utils": "workspace:^", "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11" - }, - "nx": { - "targets": { - "test:e2e": { - "outputs": [ - "...", - "{projectRoot}/dist-hash" - ] - } - } } } diff --git a/e2e/solid-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts b/e2e/solid-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts index e2681daea5..9d7691f0fd 100644 --- a/e2e/solid-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts +++ b/e2e/solid-router/scroll-restoration-sandbox-vite/playwright.browser.config.ts @@ -1,7 +1,15 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, + resolveRuntimeSuffix, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + packageJson.name + `-${resolveRuntimeSuffix('browser')}`, +) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +20,18 @@ 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_APP_HISTORY=browser pnpm build && VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', }, diff --git a/e2e/solid-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts b/e2e/solid-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts index 445616b9bd..80a340cef4 100644 --- a/e2e/solid-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts +++ b/e2e/solid-router/scroll-restoration-sandbox-vite/playwright.hash.config.ts @@ -1,7 +1,15 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, + resolveRuntimeSuffix, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + packageJson.name + `-${resolveRuntimeSuffix('hash')}`, +) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +20,18 @@ 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_APP_HISTORY=hash vite build --outDir dist-hash && VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', }, diff --git a/e2e/solid-router/scroll-restoration-sandbox-vite/src/posts.tsx b/e2e/solid-router/scroll-restoration-sandbox-vite/src/posts.tsx index bc56dff904..c6cba486ab 100644 --- a/e2e/solid-router/scroll-restoration-sandbox-vite/src/posts.tsx +++ b/e2e/solid-router/scroll-restoration-sandbox-vite/src/posts.tsx @@ -12,7 +12,11 @@ export type PostType = { export class PostNotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +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 = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/solid-router/scroll-restoration-sandbox-vite/tests/app.spec.ts b/e2e/solid-router/scroll-restoration-sandbox-vite/tests/app.spec.ts index 067f0341c4..5f226c6db3 100644 --- a/e2e/solid-router/scroll-restoration-sandbox-vite/tests/app.spec.ts +++ b/e2e/solid-router/scroll-restoration-sandbox-vite/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' import { toRuntimePath } from '@tanstack/router-e2e-utils' test('Smoke - Renders home', async ({ page }) => { diff --git a/e2e/solid-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts b/e2e/solid-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/solid-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/solid-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts b/e2e/solid-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/solid-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/solid-router/scroll-restoration-sandbox-vite/tsconfig.json b/e2e/solid-router/scroll-restoration-sandbox-vite/tsconfig.json index ae3b435a85..a16f70ed34 100644 --- a/e2e/solid-router/scroll-restoration-sandbox-vite/tsconfig.json +++ b/e2e/solid-router/scroll-restoration-sandbox-vite/tsconfig.json @@ -12,5 +12,5 @@ "allowJs": true, "types": ["vite/client", "node"] }, - "exclude": ["node_modules", "dist", "dist-hash"] + "exclude": ["node_modules", "dist"] } diff --git a/e2e/solid-router/sentry-integration/package.json b/e2e/solid-router/sentry-integration/package.json index 83c9c7a087..04f36db588 100644 --- a/e2e/solid-router/sentry-integration/package.json +++ b/e2e/solid-router/sentry-integration/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@sentry/solid": "^10.32.0", diff --git a/e2e/solid-router/sentry-integration/playwright.config.ts b/e2e/solid-router/sentry-integration/playwright.config.ts index 6a684ac89e..0c5cee43e4 100644 --- a/e2e/solid-router/sentry-integration/playwright.config.ts +++ b/e2e/solid-router/sentry-integration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/solid-router/view-transitions/package.json b/e2e/solid-router/view-transitions/package.json index 5fc632c172..c0b7d2e383 100644 --- a/e2e/solid-router/view-transitions/package.json +++ b/e2e/solid-router/view-transitions/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/solid-router/view-transitions/playwright.config.ts b/e2e/solid-router/view-transitions/playwright.config.ts index 4eead86444..c5de6b5611 100644 --- a/e2e/solid-router/view-transitions/playwright.config.ts +++ b/e2e/solid-router/view-transitions/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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,10 +22,13 @@ export default defineConfig({ baseURL, }, + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', }, diff --git a/e2e/solid-router/view-transitions/tests/app.spec.ts b/e2e/solid-router/view-transitions/tests/app.spec.ts index 6c1ccf1a6e..472bd6ed0b 100644 --- a/e2e/solid-router/view-transitions/tests/app.spec.ts +++ b/e2e/solid-router/view-transitions/tests/app.spec.ts @@ -1,4 +1,4 @@ -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/solid-router/view-transitions/tests/setup/global.setup.ts b/e2e/solid-router/view-transitions/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/solid-router/view-transitions/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/solid-router/view-transitions/tests/setup/global.teardown.ts b/e2e/solid-router/view-transitions/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/solid-router/view-transitions/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/solid-start/basic-auth/package.json b/e2e/solid-start/basic-auth/package.json index a95d6f73d1..789c3bc582 100644 --- a/e2e/solid-start/basic-auth/package.json +++ b/e2e/solid-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": "mkdir -p .tmp; rm -f .tmp/dev.db .tmp/dev.db-journal .tmp/dev.db-wal .tmp/dev.db-shm; export DATABASE_URL=file:./.tmp/dev.db; pnpm run prisma-generate && pnpm exec prisma migrate deploy && playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; mkdir -p .tmp; rm -f .tmp/dev.db .tmp/dev.db-journal .tmp/dev.db-wal .tmp/dev.db-shm; export DATABASE_URL=file:./.tmp/dev.db; pnpm run prisma-generate && pnpm exec prisma migrate deploy && playwright test --project=chromium" }, "dependencies": { "@libsql/client": "^0.15.15", @@ -19,7 +19,6 @@ "@tanstack/solid-router": "workspace:^", "@tanstack/solid-router-devtools": "workspace:^", "@tanstack/solid-start": "workspace:^", - "iron-session": "^9.0.1", "redaxios": "catalog:", "solid-js": "^1.9.10", "tailwind-merge": "^3.6.0" @@ -31,22 +30,11 @@ "@types/node": "^22.10.2", "dotenv": "^17.2.3", "prisma": "^7.0.0", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.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" - }, - "nx": { - "targets": { - "test:e2e": { - "outputs": [ - "...", - "{projectRoot}/.tmp", - "{projectRoot}/src/prisma-generated" - ] - } - } } } diff --git a/e2e/solid-start/basic-auth/playwright.config.ts b/e2e/solid-start/basic-auth/playwright.config.ts index 4d5ea2e9f2..d8ab0dd8cc 100644 --- a/e2e/solid-start/basic-auth/playwright.config.ts +++ b/e2e/solid-start/basic-auth/playwright.config.ts @@ -1,13 +1,14 @@ -import path from 'node:path' import { fileURLToPath } from 'node:url' +import path from 'node:path' import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } // Ensure port file is written next to this config, even if Playwright loads it // from a different working directory. process.chdir(path.dirname(fileURLToPath(import.meta.url))) -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -25,8 +26,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/solid-start/basic-auth/src/routes/__root.tsx b/e2e/solid-start/basic-auth/src/routes/__root.tsx index 8068b7a331..3a3392e922 100644 --- a/e2e/solid-start/basic-auth/src/routes/__root.tsx +++ b/e2e/solid-start/basic-auth/src/routes/__root.tsx @@ -15,18 +15,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 { getAppSession } from '~/utils/session.js' +import { useAppSession } 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 getAppSession() + const session = await useAppSession() - if (!session.userEmail) { + if (!session.data.userEmail) { return null } return { - email: session.userEmail, + email: session.data.userEmail, } }) diff --git a/e2e/solid-start/basic-auth/src/routes/_authed.tsx b/e2e/solid-start/basic-auth/src/routes/_authed.tsx index e204d2e3a0..a42aac212a 100644 --- a/e2e/solid-start/basic-auth/src/routes/_authed.tsx +++ b/e2e/solid-start/basic-auth/src/routes/_authed.tsx @@ -3,7 +3,7 @@ import { createServerFn } from '@tanstack/solid-start' import { hashPassword, prismaClient } from '~/utils/prisma' import { Login } from '~/components/Login' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST', @@ -37,11 +37,12 @@ export const loginFn = createServerFn({ } // Create a session - const session = await getAppSession() + const session = await useAppSession() // Store the user's email in the session - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) }) export const Route = createFileRoute('/_authed')({ diff --git a/e2e/solid-start/basic-auth/src/routes/logout.tsx b/e2e/solid-start/basic-auth/src/routes/logout.tsx index 5c69eb516d..85b1670a5f 100644 --- a/e2e/solid-start/basic-auth/src/routes/logout.tsx +++ b/e2e/solid-start/basic-auth/src/routes/logout.tsx @@ -1,12 +1,12 @@ import { redirect, createFileRoute } from '@tanstack/solid-router' import { createServerFn } from '@tanstack/solid-start' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await getAppSession() + const session = await useAppSession() - session.destroy() + session.clear() throw redirect({ href: '/', diff --git a/e2e/solid-start/basic-auth/src/routes/signup.tsx b/e2e/solid-start/basic-auth/src/routes/signup.tsx index 155f816883..2142574faa 100644 --- a/e2e/solid-start/basic-auth/src/routes/signup.tsx +++ b/e2e/solid-start/basic-auth/src/routes/signup.tsx @@ -4,7 +4,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 { getAppSession } from '~/utils/session' +import { useAppSession } 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 getAppSession() + const session = await useAppSession() if (found) { if (found.password !== password) { @@ -36,8 +36,9 @@ export const signupFn = createServerFn({ } // Store the user's email in the session - session.userEmail = found.email - await session.save() + await session.update({ + userEmail: found.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -54,8 +55,9 @@ export const signupFn = createServerFn({ }) // Store the user's email in the session - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ diff --git a/e2e/solid-start/basic-auth/src/utils/session.ts b/e2e/solid-start/basic-auth/src/utils/session.ts index 728332d28f..6aac388545 100644 --- a/e2e/solid-start/basic-auth/src/utils/session.ts +++ b/e2e/solid-start/basic-auth/src/utils/session.ts @@ -1,25 +1,13 @@ -import { getIronSession } from 'iron-session' -import { getCookie, setCookie } from '@tanstack/solid-start/server' +// src/services/session.server.ts +import { useSession } from '@tanstack/solid-start/server' import type { User } from '~/prisma-generated/client' type SessionUser = { userEmail: User['email'] } -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: '/', - }, - }, - ) +export function useAppSession() { + return useSession({ + password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', + }) } diff --git a/e2e/solid-start/basic-cloudflare/package.json b/e2e/solid-start/basic-cloudflare/package.json index f1c823b3a9..c9d4f6b244 100644 --- a/e2e/solid-start/basic-cloudflare/package.json +++ b/e2e/solid-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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/solid-router": "workspace:^", @@ -30,15 +30,5 @@ "vite": "^8.0.14", "vite-plugin-solid": "^2.11.11", "wrangler": "^4.74.0" - }, - "nx": { - "targets": { - "test:e2e": { - "outputs": [ - "...", - "{projectRoot}/.wrangler/deploy" - ] - } - } } } diff --git a/e2e/solid-start/basic-cloudflare/playwright.config.ts b/e2e/solid-start/basic-cloudflare/playwright.config.ts index 0925936d55..a545dff891 100644 --- a/e2e/solid-start/basic-cloudflare/playwright.config.ts +++ b/e2e/solid-start/basic-cloudflare/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,6 +14,9 @@ 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, @@ -20,8 +24,8 @@ export default defineConfig({ webServer: { command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/solid-start/basic-cloudflare/tests/setup/global.setup.ts b/e2e/solid-start/basic-cloudflare/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/solid-start/basic-cloudflare/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/solid-start/basic-cloudflare/tests/setup/global.teardown.ts b/e2e/solid-start/basic-cloudflare/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/solid-start/basic-cloudflare/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/solid-start/basic-solid-query/package.json b/e2e/solid-start/basic-solid-query/package.json index 468a67877b..0522bd3808 100644 --- a/e2e/solid-start/basic-solid-query/package.json +++ b/e2e/solid-start/basic-solid-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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/solid-query": "^5.90.9", @@ -28,7 +28,7 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/solid-start/basic-solid-query/playwright.config.ts b/e2e/solid-start/basic-solid-query/playwright.config.ts index 0618b7272a..84636ab0f9 100644 --- a/e2e/solid-start/basic-solid-query/playwright.config.ts +++ b/e2e/solid-start/basic-solid-query/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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}` @@ -11,18 +16,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { baseURL, }, webServer: { - command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/solid-start/basic-solid-query/src/routes/api.users.ts b/e2e/solid-start/basic-solid-query/src/routes/api.users.ts index 1ab58b711a..54859a701e 100644 --- a/e2e/solid-start/basic-solid-query/src/routes/api.users.ts +++ b/e2e/solid-start/basic-solid-query/src/routes/api.users.ts @@ -2,7 +2,11 @@ import { createFileRoute } from '@tanstack/solid-router' import axios from 'redaxios' import type { User } from '../utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +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: { diff --git a/e2e/solid-start/basic-solid-query/src/routes/api/users.$id.ts b/e2e/solid-start/basic-solid-query/src/routes/api/users.$id.ts index b0947a27f1..a7b2e44491 100644 --- a/e2e/solid-start/basic-solid-query/src/routes/api/users.$id.ts +++ b/e2e/solid-start/basic-solid-query/src/routes/api/users.$id.ts @@ -2,7 +2,11 @@ import { createFileRoute } from '@tanstack/solid-router' import axios from 'redaxios' import type { User } from '../../utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +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: { diff --git a/e2e/solid-start/basic-solid-query/src/utils/users.tsx b/e2e/solid-start/basic-solid-query/src/utils/users.tsx index e7fc1a5de4..52d659b001 100644 --- a/e2e/solid-start/basic-solid-query/src/utils/users.tsx +++ b/e2e/solid-start/basic-solid-query/src/utils/users.tsx @@ -1,6 +1,4 @@ import { queryOptions } from '@tanstack/solid-query' -import { createIsomorphicFn } from '@tanstack/solid-start' -import { getRequestUrl } from '@tanstack/solid-start/server' import axios from 'redaxios' export type User = { @@ -9,16 +7,17 @@ export type User = { email: string } -const getOrigin = createIsomorphicFn() - .server(() => getRequestUrl().origin) - .client(() => window.location.origin) +const PORT = + import.meta.env.VITE_SERVER_PORT || process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` export const usersQueryOptions = () => queryOptions({ queryKey: ['users'], queryFn: () => axios - .get>(getOrigin() + '/api/users') + .get>(DEPLOY_URL + '/api/users') .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch users') @@ -30,7 +29,7 @@ export const userQueryOptions = (id: string) => queryKey: ['users', id], queryFn: () => axios - .get(getOrigin() + '/api/users/' + id) + .get(DEPLOY_URL + '/api/users/' + id) .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch user') diff --git a/e2e/solid-start/basic-solid-query/tests/app.spec.ts b/e2e/solid-start/basic-solid-query/tests/app.spec.ts index 4ce5c20ef7..ab2469f68d 100644 --- a/e2e/solid-start/basic-solid-query/tests/app.spec.ts +++ b/e2e/solid-start/basic-solid-query/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test('Navigating to post', async ({ page }) => { await page.goto('/') diff --git a/e2e/solid-start/basic-solid-query/tests/setup/global.setup.ts b/e2e/solid-start/basic-solid-query/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/solid-start/basic-solid-query/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/solid-start/basic-solid-query/tests/setup/global.teardown.ts b/e2e/solid-start/basic-solid-query/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/solid-start/basic-solid-query/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/solid-start/basic-solid-query/tests/transition.spec.ts b/e2e/solid-start/basic-solid-query/tests/transition.spec.ts index a0f3bf0964..2c28fc72a2 100644 --- a/e2e/solid-start/basic-solid-query/tests/transition.spec.ts +++ b/e2e/solid-start/basic-solid-query/tests/transition.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test('transitions/count/query should keep old values visible during navigation', async ({ page, diff --git a/e2e/solid-start/basic-tsr-config/package.json b/e2e/solid-start/basic-tsr-config/package.json index 8d720d5ce4..44321e96a1 100644 --- a/e2e/solid-start/basic-tsr-config/package.json +++ b/e2e/solid-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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/solid-router": "workspace:^", @@ -19,7 +19,7 @@ "devDependencies": { "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", diff --git a/e2e/solid-start/basic-tsr-config/playwright.config.ts b/e2e/solid-start/basic-tsr-config/playwright.config.ts index e6b92ce385..f6dd61ba6c 100644 --- a/e2e/solid-start/basic-tsr-config/playwright.config.ts +++ b/e2e/solid-start/basic-tsr-config/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/solid-start/basic/package.json b/e2e/solid-start/basic/package.json index e83ed11775..f4dde5a3b2 100644 --- a/e2e/solid-start/basic/package.json +++ b/e2e/solid-start/basic/package.json @@ -6,12 +6,12 @@ "scripts": { "dev": "vite dev --port 3000", "dev:e2e": "vite dev", - "build": "pnpm build:vite", + "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "node server.js", - "test:e2e:local": "playwright test --project=chromium", - "build:vite": "vite build && tsc --noEmit", - "build:rsbuild": "rsbuild build && tsc --noEmit" + "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": { "@tanstack/solid-router": "workspace:^", @@ -27,7 +27,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-babel": "^1.1.2", "@rsbuild/plugin-solid": "^1.1.1", "@tailwindcss/postcss": "^4.2.2", @@ -36,7 +36,7 @@ "@types/js-cookie": "^3.0.6", "@types/node": "^22.10.2", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", @@ -57,10 +57,7 @@ }, { "toolchain": "vite", - "mode": "prerender", - "env": { - "NODE_OPTIONS": "--import=@tanstack/router-e2e-utils/mock-api" - } + "mode": "prerender" }, { "toolchain": "vite", diff --git a/e2e/solid-start/basic/playwright.config.ts b/e2e/solid-start/basic/playwright.config.ts index 9322874f3a..6924134cd1 100644 --- a/e2e/solid-start/basic/playwright.config.ts +++ b/e2e/solid-start/basic/playwright.config.ts @@ -1,37 +1,59 @@ +import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } const mode = process.env.MODE ?? 'ssr' - +const e2ePortKey = process.env.E2E_PORT_KEY ?? packageJson.name const distDir = process.env.E2E_DIST_DIR ?? 'dist' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +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 baseURL = `http://localhost:${PORT}` const commandByMode = mode === 'preview' - ? `pnpm preview --host 0.0.0.0 --outDir ${distDir} --port ${PORT}` - : `pnpm start` + ? `pnpm run test:e2e:startDummyServer && pnpm preview --outDir ${distDir} --port ${PORT}` + : `pnpm run test:e2e:startDummyServer && pnpm start` export default defineConfig({ testDir: './tests', workers: 1, reporter: [['line']], + globalTeardown: './tests/setup/global.teardown.ts', + use: { baseURL, }, webServer: { command: commandByMode, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, MODE: mode, - START_PORT: '0', + VITE_NODE_ENV: 'test', + VITE_EXTERNAL_PORT: String(EXTERNAL_PORT), + VITE_SERVER_PORT: String(PORT), + START_PORT: String(START_PORT), PORT: String(PORT), E2E_DIST_DIR: distDir, + E2E_PORT_KEY: e2ePortKey, }, }, diff --git a/e2e/solid-start/basic/server.js b/e2e/solid-start/basic/server.js index 3e1ddab400..69c1e4ca91 100644 --- a/e2e/solid-start/basic/server.js +++ b/e2e/solid-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 = Number(process.env.PORT ?? 3000) +const port = process.env.PORT || 3000 -const startPort = Number(process.env.START_PORT ?? 0) +const startPort = process.env.START_PORT || 3001 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(backendPort) { +export async function createSpaServer() { const app = express() app.use( '/api', createProxyMiddleware({ - target: `http://localhost:${backendPort}/api`, // Replace with your target server's URL + target: `http://localhost:${startPort}/api`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -63,7 +63,7 @@ export async function createSpaServer(backendPort) { app.use( '/_serverFn', createProxyMiddleware({ - target: `http://localhost:${backendPort}/_serverFn`, // Replace with your target server's URL + target: `http://localhost:${startPort}/_serverFn`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -71,28 +71,31 @@ export async function createSpaServer(backendPort) { app.use(express.static(distClientDir)) app.get('/{*splat}', (req, res) => { - res.sendFile('index.html', { root: distClientDir }) + res.sendFile(path.resolve(distClientDir, 'index.html')) }) return { app } } -// 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}`) - } -}) +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}`) + }), + ) +} diff --git a/e2e/solid-start/basic/src/routes/api/users.$userId.ts b/e2e/solid-start/basic/src/routes/api/users.$userId.ts index ed90076917..6c583f2619 100644 --- a/e2e/solid-start/basic/src/routes/api/users.$userId.ts +++ b/e2e/solid-start/basic/src/routes/api/users.$userId.ts @@ -1,15 +1,19 @@ import { createFileRoute } from '@tanstack/solid-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( - `https://jsonplaceholder.typicode.com/users/${params.userId}`, - ) + const res = await fetch(`${queryURL}/users/${params.userId}`) if (!res.ok) { throw new Error('Failed to fetch user') } diff --git a/e2e/solid-start/basic/src/routes/api/users.ts b/e2e/solid-start/basic/src/routes/api/users.ts index f2fa98359a..3d0a2f1116 100644 --- a/e2e/solid-start/basic/src/routes/api/users.ts +++ b/e2e/solid-start/basic/src/routes/api/users.ts @@ -38,13 +38,19 @@ 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('https://jsonplaceholder.typicode.com/users') + const res = await fetch(`${queryURL}/users`) if (!res.ok) { throw new Error('Failed to fetch users') } diff --git a/e2e/solid-start/basic/src/utils/posts.tsx b/e2e/solid-start/basic/src/utils/posts.tsx index 6c12105ab8..05ca4651fb 100644 --- a/e2e/solid-start/basic/src/utils/posts.tsx +++ b/e2e/solid-start/basic/src/utils/posts.tsx @@ -8,12 +8,18 @@ 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(`https://jsonplaceholder.typicode.com/posts/${postId}`) + .get(`${queryURL}/posts/${postId}`) .then((r) => r.data) .catch((err) => { console.error(err) @@ -30,7 +36,7 @@ export const fetchPosts = createServerFn({ method: 'GET' }).handler( async () => { console.info('Fetching posts...') return axios - .get>('https://jsonplaceholder.typicode.com/posts') + .get>(`${queryURL}/posts`) .then((r) => r.data.slice(0, 10)) }, ) diff --git a/e2e/solid-start/basic/src/utils/users.tsx b/e2e/solid-start/basic/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/solid-start/basic/src/utils/users.tsx +++ b/e2e/solid-start/basic/src/utils/users.tsx @@ -3,3 +3,7 @@ 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/solid-start/basic/tests/fixture-api.spec.ts b/e2e/solid-start/basic/tests/fixture-api.spec.ts deleted file mode 100644 index 6c9b26dc4c..0000000000 --- a/e2e/solid-start/basic/tests/fixture-api.spec.ts +++ /dev/null @@ -1,11 +0,0 @@ -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/solid-start/basic/tests/redirect.spec.ts b/e2e/solid-start/basic/tests/redirect.spec.ts index 8e6ceba5b9..2f6354aa81 100644 --- a/e2e/solid-start/basic/tests/redirect.spec.ts +++ b/e2e/solid-start/basic/tests/redirect.spec.ts @@ -1,14 +1,19 @@ import queryString from 'node:querystring' -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' +import { expect, type Page } from '@playwright/test' import combinateImport from 'combinate' -import type { Page } from '@playwright/test' +import { + getDummyServerPort, + getTestServerPort, + test, +} from '@tanstack/router-e2e-utils' +import { getE2EPortKey } from './utils/getE2EPortKey.ts' // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const EXTERNAL_ORIGIN = `http://127.0.0.1:${PORT}` +const e2ePortKey = getE2EPortKey() +const PORT = await getTestServerPort(e2ePortKey) +const EXTERNAL_HOST_PORT = await getDummyServerPort(e2ePortKey) const POSTS_URL = `http://localhost:${PORT}/posts` async function waitForRouterIdle(page: Page) { @@ -101,7 +106,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, }) if (scenario === 'navigate') { @@ -114,7 +119,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/external/via-${thrower}?${q}`) } - const url = `${EXTERNAL_ORIGIN}/` + const url = `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) @@ -135,7 +140,7 @@ test.describe('redirects', () => { }) => { let fullPageLoad = false const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, reloadDocument, }) @@ -154,7 +159,10 @@ test.describe('redirects', () => { await page.goto(`/redirect/${target}/serverFn/via-${thrower}?${q}`) } - const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` + const url = + target === 'internal' + ? POSTS_URL + : `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) if (target === 'internal' && scenario === 'navigate') { @@ -176,7 +184,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, reloadDocument, }) @@ -193,7 +201,10 @@ test.describe('redirects', () => { await button.click() - const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` + const url = + target === 'internal' + ? POSTS_URL + : `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) if (target === 'internal') { diff --git a/e2e/solid-start/basic/tests/setup/global.setup.ts b/e2e/solid-start/basic/tests/setup/global.setup.ts new file mode 100644 index 0000000000..cd38c35885 --- /dev/null +++ b/e2e/solid-start/basic/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/solid-start/basic/tests/setup/global.teardown.ts b/e2e/solid-start/basic/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..36e5c92858 --- /dev/null +++ b/e2e/solid-start/basic/tests/setup/global.teardown.ts @@ -0,0 +1,8 @@ +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/solid-start/basic/tests/setup/waitForDummyServer.ts b/e2e/solid-start/basic/tests/setup/waitForDummyServer.ts new file mode 100644 index 0000000000..88c18fd79e --- /dev/null +++ b/e2e/solid-start/basic/tests/setup/waitForDummyServer.ts @@ -0,0 +1,24 @@ +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/solid-start/basic/tests/utils/getE2EPortKey.ts b/e2e/solid-start/basic/tests/utils/getE2EPortKey.ts new file mode 100644 index 0000000000..48be6a9027 --- /dev/null +++ b/e2e/solid-start/basic/tests/utils/getE2EPortKey.ts @@ -0,0 +1,5 @@ +import { getPackageName } from './getPackageName.ts' + +export function getE2EPortKey() { + return process.env.E2E_PORT_KEY ?? getPackageName() +} diff --git a/e2e/solid-start/csp/package.json b/e2e/solid-start/csp/package.json index f233a87d67..9e288ba0ef 100644 --- a/e2e/solid-start/csp/package.json +++ b/e2e/solid-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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/solid-router": "workspace:^", @@ -19,7 +19,7 @@ "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", diff --git a/e2e/solid-start/csp/playwright.config.ts b/e2e/solid-start/csp/playwright.config.ts index 87b32e1f50..5f9de5709e 100644 --- a/e2e/solid-start/csp/playwright.config.ts +++ b/e2e/solid-start/csp/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/solid-start/css-modules/package.json b/e2e/solid-start/css-modules/package.json index 107659f43c..d996409200 100644 --- a/e2e/solid-start/css-modules/package.json +++ b/e2e/solid-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": "pnpm run test:e2e:dev" + "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:dev" }, "dependencies": { "@tanstack/solid-router": "workspace:*", @@ -23,7 +23,7 @@ "@tanstack/router-e2e-utils": "workspace:*", "@types/node": "^22.10.2", "sass": "^1.97.2", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", diff --git a/e2e/solid-start/css-modules/playwright.config.ts b/e2e/solid-start/css-modules/playwright.config.ts index a50ac5ae63..0b810d5372 100644 --- a/e2e/solid-start/css-modules/playwright.config.ts +++ b/e2e/solid-start/css-modules/playwright.config.ts @@ -1,9 +1,10 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +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 = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -12,17 +13,16 @@ 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 --port 0` - : `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: isDev ? `pnpm dev:e2e` : `pnpm build && PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { VITE_NODE_ENV: 'test', diff --git a/e2e/solid-start/css-modules/tests/setup/global.setup.ts b/e2e/solid-start/css-modules/tests/setup/global.setup.ts index 17be637f77..2d3a1db946 100644 --- a/e2e/solid-start/css-modules/tests/setup/global.setup.ts +++ b/e2e/solid-start/css-modules/tests/setup/global.setup.ts @@ -1,9 +1,17 @@ -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' +import { + e2eStartDummyServer, + getTestServerPort, + preOptimizeDevServer, + waitForServer, +} from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } export default async function setup() { + await e2eStartDummyServer(packageJson.name) + if (process.env.MODE !== 'dev') return - const port = Number(process.env.E2E_APP_PORT ?? 0) + const port = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${port}` await waitForServer(baseURL) diff --git a/e2e/solid-start/css-modules/tests/setup/global.teardown.ts b/e2e/solid-start/css-modules/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/solid-start/css-modules/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/solid-start/custom-basepath/express-server.ts b/e2e/solid-start/custom-basepath/express-server.ts index b9bf393466..1884c5eb5a 100644 --- a/e2e/solid-start/custom-basepath/express-server.ts +++ b/e2e/solid-start/custom-basepath/express-server.ts @@ -1,6 +1,5 @@ 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' @@ -41,11 +40,7 @@ if (DEVELOPMENT) { }) } -const httpServer = app.listen(PORT, (error) => { - if (error) { - throw error - } - console.log( - `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, - ) +app.listen(PORT, (error) => { + if (error) throw error + console.log(`Server is running on http://localhost:${PORT}`) }) diff --git a/e2e/solid-start/custom-basepath/package.json b/e2e/solid-start/custom-basepath/package.json index 9113db133b..0ce43d152d 100644 --- a/e2e/solid-start/custom-basepath/package.json +++ b/e2e/solid-start/custom-basepath/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "tsx express-server.ts", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/solid-router": "workspace:^", @@ -25,7 +25,7 @@ "@types/express": "^5.0.6", "@types/node": "^22.10.2", "cross-env": "^10.0.0", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "tsx": "^4.20.3", "@typescript/native": "npm:typescript@^7.0.2", diff --git a/e2e/solid-start/custom-basepath/playwright.config.ts b/e2e/solid-start/custom-basepath/playwright.config.ts index e113ce64ad..5095425f47 100644 --- a/e2e/solid-start/custom-basepath/playwright.config.ts +++ b/e2e/solid-start/custom-basepath/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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}/custom/basepath` /** @@ -13,19 +18,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: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/solid-start/custom-basepath/src/routes/api/users.$userId.ts b/e2e/solid-start/custom-basepath/src/routes/api/users.$userId.ts index 2c1978b370..6c583f2619 100644 --- a/e2e/solid-start/custom-basepath/src/routes/api/users.$userId.ts +++ b/e2e/solid-start/custom-basepath/src/routes/api/users.$userId.ts @@ -1,7 +1,11 @@ import { createFileRoute } from '@tanstack/solid-router' import type { User } from '~/utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +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: { diff --git a/e2e/solid-start/custom-basepath/src/routes/api/users.ts b/e2e/solid-start/custom-basepath/src/routes/api/users.ts index d9fe7817d6..3d0a2f1116 100644 --- a/e2e/solid-start/custom-basepath/src/routes/api/users.ts +++ b/e2e/solid-start/custom-basepath/src/routes/api/users.ts @@ -38,7 +38,11 @@ const testMiddleware = createMiddleware() return result }) -const queryURL = 'https://jsonplaceholder.typicode.com' +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: { diff --git a/e2e/solid-start/custom-basepath/src/utils/posts.tsx b/e2e/solid-start/custom-basepath/src/utils/posts.tsx index d0889bd725..05ca4651fb 100644 --- a/e2e/solid-start/custom-basepath/src/utils/posts.tsx +++ b/e2e/solid-start/custom-basepath/src/utils/posts.tsx @@ -8,7 +8,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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) diff --git a/e2e/solid-start/custom-basepath/src/utils/users.tsx b/e2e/solid-start/custom-basepath/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/solid-start/custom-basepath/src/utils/users.tsx +++ b/e2e/solid-start/custom-basepath/src/utils/users.tsx @@ -3,3 +3,7 @@ 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/solid-start/custom-basepath/tests/setup/global.setup.ts b/e2e/solid-start/custom-basepath/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/solid-start/custom-basepath/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/solid-start/custom-basepath/tests/setup/global.teardown.ts b/e2e/solid-start/custom-basepath/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/solid-start/custom-basepath/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/solid-start/deferred-hydration/package.json b/e2e/solid-start/deferred-hydration/package.json index 4e2a3a1665..0b272e838a 100644 --- a/e2e/solid-start/deferred-hydration/package.json +++ b/e2e/solid-start/deferred-hydration/package.json @@ -23,12 +23,12 @@ "solid-js": "^1.9.10" }, "devDependencies": { - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-babel": "^1.1.2", "@rsbuild/plugin-solid": "^1.1.1", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", @@ -38,12 +38,6 @@ "targets": { "test:e2e": { "parallelism": false - }, - "build": { - "outputs": [ - "...", - "{projectRoot}/dist-vite-ssr" - ] } }, "metadata": { diff --git a/e2e/solid-start/deferred-hydration/playwright.config.ts b/e2e/solid-start/deferred-hydration/playwright.config.ts index 4b7fbc6a9c..ea9e73a856 100644 --- a/e2e/solid-start/deferred-hydration/playwright.config.ts +++ b/e2e/solid-start/deferred-hydration/playwright.config.ts @@ -1,13 +1,20 @@ +import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } 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 serverEntryFile = toolchain === 'rsbuild' ? 'index.js' : 'server.js' const startCommand = `pnpm exec srvx --prod --dir=. -s ${distDir}/client --entry ${distDir}/server/${serverEntryFile}` -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +if (process.env.TEST_WORKER_INDEX === undefined) { + fs.rmSync(`port-${e2ePortKey}.txt`, { force: true }) +} + +const PORT = await getTestServerPort(e2ePortKey) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -17,8 +24,8 @@ export default defineConfig({ use: { baseURL }, webServer: { command: startCommand, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { E2E_DIST_DIR: distDir, diff --git a/e2e/solid-start/dev-ssr-styles/.gitignore b/e2e/solid-start/dev-ssr-styles/.gitignore deleted file mode 100644 index 950326609c..0000000000 --- a/e2e/solid-start/dev-ssr-styles/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -node_modules -dist -.routeTree.gen.ts -src/routeTree.gen.ts -test-results -playwright-report -port*.txt diff --git a/e2e/solid-start/dev-ssr-styles/package.json b/e2e/solid-start/dev-ssr-styles/package.json deleted file mode 100644 index 6ca79c15c6..0000000000 --- a/e2e/solid-start/dev-ssr-styles/package.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "tanstack-solid-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/solid-router": "workspace:*", - "@tanstack/solid-start": "workspace:*", - "solid-js": "^1.9.10" - }, - "devDependencies": { - "@playwright/test": "^1.61.0", - "@tanstack/router-core": "workspace:*", - "@tanstack/router-e2e-utils": "workspace:*", - "@types/node": "^22.10.2", - "srvx": "^1.0.0", - "typescript": "npm:@typescript/typescript6@^6.0.2", - "vite": "^8.0.14", - "vite-plugin-solid": "^2.11.11", - "@typescript/native": "npm:typescript@^7.0.2" - } -} diff --git a/e2e/solid-start/dev-ssr-styles/playwright.config.ts b/e2e/solid-start/dev-ssr-styles/playwright.config.ts deleted file mode 100644 index 723cd32789..0000000000 --- a/e2e/solid-start/dev-ssr-styles/playwright.config.ts +++ /dev/null @@ -1,28 +0,0 @@ -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/solid-start/dev-ssr-styles/src/components/CodeSplitStyledBox.tsx b/e2e/solid-start/dev-ssr-styles/src/components/CodeSplitStyledBox.tsx deleted file mode 100644 index 02d924dd10..0000000000 --- a/e2e/solid-start/dev-ssr-styles/src/components/CodeSplitStyledBox.tsx +++ /dev/null @@ -1,9 +0,0 @@ -import styles from '../styles/code-split-route.module.css' - -export function CodeSplitStyledBox() { - return ( -
- This box is styled by a code-split route component. -
- ) -} diff --git a/e2e/solid-start/dev-ssr-styles/src/router.tsx b/e2e/solid-start/dev-ssr-styles/src/router.tsx deleted file mode 100644 index 73b487af4d..0000000000 --- a/e2e/solid-start/dev-ssr-styles/src/router.tsx +++ /dev/null @@ -1,10 +0,0 @@ -import { createRouter } from '@tanstack/solid-router' -import { routeTree } from './routeTree.gen' - -export function getRouter() { - return createRouter({ - routeTree, - scrollRestoration: true, - defaultPreload: false, - }) -} diff --git a/e2e/solid-start/dev-ssr-styles/src/routes/__root.tsx b/e2e/solid-start/dev-ssr-styles/src/routes/__root.tsx deleted file mode 100644 index 47a50b5716..0000000000 --- a/e2e/solid-start/dev-ssr-styles/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -import { - HeadContent, - Outlet, - Scripts, - createRootRoute, -} from '@tanstack/solid-router' -import { HydrationScript } from 'solid-js/web' -import '~/styles/app.css' - -export const Route = createRootRoute({ - component: RootComponent, -}) - -function RootComponent() { - return ( - - - - - - - - - - - ) -} diff --git a/e2e/solid-start/dev-ssr-styles/src/routes/index.tsx b/e2e/solid-start/dev-ssr-styles/src/routes/index.tsx deleted file mode 100644 index 73e6f1e89d..0000000000 --- a/e2e/solid-start/dev-ssr-styles/src/routes/index.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { CodeSplitStyledBox } from '../components/CodeSplitStyledBox' - -export const Route = createFileRoute('/')({ - component: Home, -}) - -function Home() { - return ( -
-

Solid Dev SSR Styles Test

- -
- ) -} diff --git a/e2e/solid-start/dev-ssr-styles/src/styles/app.css b/e2e/solid-start/dev-ssr-styles/src/styles/app.css deleted file mode 100644 index 9a67f9b153..0000000000 --- a/e2e/solid-start/dev-ssr-styles/src/styles/app.css +++ /dev/null @@ -1,5 +0,0 @@ -body { - font-family: sans-serif; - margin: 0; - padding: 20px; -} diff --git a/e2e/solid-start/dev-ssr-styles/src/styles/code-split-route.module.css b/e2e/solid-start/dev-ssr-styles/src/styles/code-split-route.module.css deleted file mode 100644 index 75a73ca7c3..0000000000 --- a/e2e/solid-start/dev-ssr-styles/src/styles/code-split-route.module.css +++ /dev/null @@ -1,6 +0,0 @@ -.styledBox { - --solid-code-split-style-marker: present; - background-color: #3b82f6; - color: white; - padding: 24px; -} diff --git a/e2e/solid-start/dev-ssr-styles/tests/app.spec.ts b/e2e/solid-start/dev-ssr-styles/tests/app.spec.ts deleted file mode 100644 index 25bd317a72..0000000000 --- a/e2e/solid-start/dev-ssr-styles/tests/app.spec.ts +++ /dev/null @@ -1,61 +0,0 @@ -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 CSS from a code-split route component during SSR', async ({ - page, - }) => { - await page.goto('/') - - const element = page.getByTestId('styled-box') - await expect(element).toBeVisible() - await expect(element).toHaveCSS('background-color', 'rgb(59, 130, 246)') - - 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()).toContain( - '/* /src/styles/code-split-route.module.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/solid-start/dev-ssr-styles/tests/setup/global.setup.ts b/e2e/solid-start/dev-ssr-styles/tests/setup/global.setup.ts deleted file mode 100644 index b03b6485c8..0000000000 --- a/e2e/solid-start/dev-ssr-styles/tests/setup/global.setup.ts +++ /dev/null @@ -1,15 +0,0 @@ -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/solid-start/dev-ssr-styles/tsconfig.json b/e2e/solid-start/dev-ssr-styles/tsconfig.json deleted file mode 100644 index c34f9d7c36..0000000000 --- a/e2e/solid-start/dev-ssr-styles/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "preserve", - "jsxImportSource": "solid-js", - "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/solid-start/dev-ssr-styles/vite.config.ts b/e2e/solid-start/dev-ssr-styles/vite.config.ts deleted file mode 100644 index fa59f4af6d..0000000000 --- a/e2e/solid-start/dev-ssr-styles/vite.config.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { defineConfig } from 'vite' -import { tanstackStart } from '@tanstack/solid-start/plugin/vite' -import viteSolid from 'vite-plugin-solid' - -export default defineConfig({ - resolve: { tsconfigPaths: true }, - experimental: - process.env.E2E_VITE_BUNDLED_DEV === 'true' - ? { bundledDev: true } - : undefined, - server: { port: 3000 }, - plugins: [tanstackStart(), viteSolid({ ssr: true })], -}) diff --git a/e2e/solid-start/query-integration/package.json b/e2e/solid-start/query-integration/package.json index 336804c46e..549d47f77e 100644 --- a/e2e/solid-start/query-integration/package.json +++ b/e2e/solid-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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/solid-query": "^5.90.9", diff --git a/e2e/solid-start/query-integration/playwright.config.ts b/e2e/solid-start/query-integration/playwright.config.ts index 1381ce6cde..c09b27e29f 100644 --- a/e2e/solid-start/query-integration/playwright.config.ts +++ b/e2e/solid-start/query-integration/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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}` @@ -16,9 +21,9 @@ export default defineConfig({ }, webServer: { - command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', }, diff --git a/e2e/solid-start/scroll-restoration/package.json b/e2e/solid-start/scroll-restoration/package.json index 8cb355490d..5cc24ac11a 100644 --- a/e2e/solid-start/scroll-restoration/package.json +++ b/e2e/solid-start/scroll-restoration/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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/solid-router": "workspace:^", @@ -26,7 +26,7 @@ "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/solid-start/scroll-restoration/playwright.config.ts b/e2e/solid-start/scroll-restoration/playwright.config.ts index 1862174905..b0c365f8bd 100644 --- a/e2e/solid-start/scroll-restoration/playwright.config.ts +++ b/e2e/solid-start/scroll-restoration/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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}` /** @@ -13,19 +18,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: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/solid-start/scroll-restoration/src/utils/posts.tsx b/e2e/solid-start/scroll-restoration/src/utils/posts.tsx index c4a2d0dcca..e45ef52969 100644 --- a/e2e/solid-start/scroll-restoration/src/utils/posts.tsx +++ b/e2e/solid-start/scroll-restoration/src/utils/posts.tsx @@ -10,7 +10,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} export class PostNotFoundError extends Error {} diff --git a/e2e/solid-start/scroll-restoration/src/utils/users.tsx b/e2e/solid-start/scroll-restoration/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/solid-start/scroll-restoration/src/utils/users.tsx +++ b/e2e/solid-start/scroll-restoration/src/utils/users.tsx @@ -3,3 +3,7 @@ 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/solid-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts b/e2e/solid-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts deleted file mode 100644 index df75cba73c..0000000000 --- a/e2e/solid-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { test } from '@tanstack/router-e2e-utils' -import { scrollRestorationLifecycleTests } from '../../../scroll-restoration-lifecycle' - -scrollRestorationLifecycleTests(test) diff --git a/e2e/solid-start/scroll-restoration/tests/setup/global.setup.ts b/e2e/solid-start/scroll-restoration/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/solid-start/scroll-restoration/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/solid-start/scroll-restoration/tests/setup/global.teardown.ts b/e2e/solid-start/scroll-restoration/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/solid-start/scroll-restoration/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/solid-start/selective-ssr/dev-server.ts b/e2e/solid-start/selective-ssr/dev-server.ts index f1805a544b..519075f261 100644 --- a/e2e/solid-start/selective-ssr/dev-server.ts +++ b/e2e/solid-start/selective-ssr/dev-server.ts @@ -1,2 +1,5 @@ -export const devPort = Number(process.env.E2E_DEV_PORT ?? 0) +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } + +export const devPort = await getTestServerPort(`${packageJson.name}-dev`) export const devBaseURL = `http://localhost:${devPort}` diff --git a/e2e/solid-start/selective-ssr/package.json b/e2e/solid-start/selective-ssr/package.json index 8cb10e1780..3b52d572e1 100644 --- a/e2e/solid-start/selective-ssr/package.json +++ b/e2e/solid-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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/solid-router": "workspace:^", @@ -20,7 +20,7 @@ "devDependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/solid-start/selective-ssr/playwright.config.ts b/e2e/solid-start/selective-ssr/playwright.config.ts index 3da1e2eba4..09e5c50410 100644 --- a/e2e/solid-start/selective-ssr/playwright.config.ts +++ b/e2e/solid-start/selective-ssr/playwright.config.ts @@ -1,11 +1,9 @@ import { defineConfig, devices } from '@playwright/test' -import { - appServerReady, - appServerReadyPattern, -} from '@tanstack/router-e2e-utils' -import { devPort } from './dev-server' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } +import { devBaseURL, devPort } from './dev-server' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -24,18 +22,14 @@ export default defineConfig({ webServer: [ { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, { command: `NODE_ENV=development VITE_SERVER_PORT=${devPort} pnpm dev:e2e --host localhost --port ${devPort} --strictPort`, - wait: { - stdout: new RegExp( - appServerReadyPattern.source.replace('E2E_APP_PORT', 'E2E_DEV_PORT'), - ), - }, - reuseExistingServer: false, + url: devBaseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', timeout: 90_000, }, diff --git a/e2e/solid-start/serialization-adapters/package.json b/e2e/solid-start/serialization-adapters/package.json index 659944ac5f..8945c6ddab 100644 --- a/e2e/solid-start/serialization-adapters/package.json +++ b/e2e/solid-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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/solid-router": "workspace:^", @@ -22,7 +22,7 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/solid-start/serialization-adapters/playwright.config.ts b/e2e/solid-start/serialization-adapters/playwright.config.ts index 630989e41f..badd6db0eb 100644 --- a/e2e/solid-start/serialization-adapters/playwright.config.ts +++ b/e2e/solid-start/serialization-adapters/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/solid-start/server-functions/package.json b/e2e/solid-start/server-functions/package.json index ef8e6a4c5a..3ce529dda8 100644 --- a/e2e/solid-start/server-functions/package.json +++ b/e2e/solid-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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/solid-query": "^5.90.9", @@ -30,7 +30,7 @@ "@types/js-cookie": "^3.0.6", "@types/node": "^22.10.2", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/solid-start/server-functions/playwright.config.ts b/e2e/solid-start/server-functions/playwright.config.ts index 48e14683f4..cb1da03b94 100644 --- a/e2e/solid-start/server-functions/playwright.config.ts +++ b/e2e/solid-start/server-functions/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -export const PORT = Number(process.env.E2E_APP_PORT ?? 0) +export const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/solid-start/server-routes/package.json b/e2e/solid-start/server-routes/package.json index 0caf0cb795..f10fc07c2b 100644 --- a/e2e/solid-start/server-routes/package.json +++ b/e2e/solid-start/server-routes/package.json @@ -30,7 +30,7 @@ "@types/js-cookie": "^3.0.6", "@types/node": "^22.10.2", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/solid-start/server-routes/playwright.config.ts b/e2e/solid-start/server-routes/playwright.config.ts index 48e14683f4..cb1da03b94 100644 --- a/e2e/solid-start/server-routes/playwright.config.ts +++ b/e2e/solid-start/server-routes/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -export const PORT = Number(process.env.E2E_APP_PORT ?? 0) +export const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/solid-start/solid-query-layout-suspense/package.json b/e2e/solid-start/solid-query-layout-suspense/package.json index 67be48d92e..2dc7b98bff 100644 --- a/e2e/solid-start/solid-query-layout-suspense/package.json +++ b/e2e/solid-start/solid-query-layout-suspense/package.json @@ -7,7 +7,7 @@ "dev:e2e": "vite dev --port $PORT", "build": "vite build && tsc --noEmit", "start": "node .output/server/index.mjs", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/solid-query": "^5.90.9", diff --git a/e2e/solid-start/solid-query-layout-suspense/playwright.config.ts b/e2e/solid-start/solid-query-layout-suspense/playwright.config.ts index 9a8034c86c..e7e18e60a7 100644 --- a/e2e/solid-start/solid-query-layout-suspense/playwright.config.ts +++ b/e2e/solid-start/solid-query-layout-suspense/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -10,9 +11,9 @@ export default defineConfig({ reporter: [['line']], use: { baseURL }, webServer: { - command: `PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm dev:e2e --port 0`, - wait: appServerReady, - reuseExistingServer: false, + command: `PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm dev:e2e`, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, projects: [ diff --git a/e2e/solid-start/spa-mode/package.json b/e2e/solid-start/spa-mode/package.json index 614f19dba0..8089ac1c64 100644 --- a/e2e/solid-start/spa-mode/package.json +++ b/e2e/solid-start/spa-mode/package.json @@ -9,7 +9,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "npx serve dist/client", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/solid-router": "workspace:^", diff --git a/e2e/solid-start/spa-mode/playwright.config.ts b/e2e/solid-start/spa-mode/playwright.config.ts index 630989e41f..badd6db0eb 100644 --- a/e2e/solid-start/spa-mode/playwright.config.ts +++ b/e2e/solid-start/spa-mode/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/solid-start/start-manifest/package.json b/e2e/solid-start/start-manifest/package.json index a47d7475b5..beeb6ab258 100644 --- a/e2e/solid-start/start-manifest/package.json +++ b/e2e/solid-start/start-manifest/package.json @@ -18,7 +18,7 @@ "@playwright/test": "^1.61.0", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", diff --git a/e2e/solid-start/start-manifest/playwright.config.ts b/e2e/solid-start/start-manifest/playwright.config.ts index 653e08253f..b9f835c16a 100644 --- a/e2e/solid-start/start-manifest/playwright.config.ts +++ b/e2e/solid-start/start-manifest/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -15,8 +16,8 @@ export default defineConfig({ webServer: { command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/solid-start/start-manifest/tests/start-manifest.spec.ts b/e2e/solid-start/start-manifest/tests/start-manifest.spec.ts index ba74448d54..836f62a97f 100644 --- a/e2e/solid-start/start-manifest/tests/start-manifest.spec.ts +++ b/e2e/solid-start/start-manifest/tests/start-manifest.spec.ts @@ -356,19 +356,24 @@ test('shared widget CSS stays applied when navigating from static to lazy route' const widget = page.getByTestId('shared-widget') await expect(widget).toBeVisible() - await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + expect(await getBackgroundColor('shared-widget', page)).toBe(SHARED_WIDGET_BG) + expect( + await widget.evaluate( + (element) => getComputedStyle(element).borderTopColor, + ), + ).toBe(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(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) }) test('shared widget CSS stays applied when navigating from lazy to static route', async ({ @@ -378,19 +383,27 @@ 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() - 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 expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) 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(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + 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) }) test('shared widget CSS is applied on direct navigation to lazy route', async ({ @@ -402,8 +415,17 @@ 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(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + + 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) }) test('shared widget CSS persists after navigating away from lazy and back', async ({ @@ -413,21 +435,19 @@ 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('lazy-css-lazy-heading')).toBeVisible() - await expect(widget).toBeVisible() + await expect(page.getByTestId('shared-widget')).toBeVisible() await page.getByTestId('nav-home').click() - await page.waitForURL((url) => url.pathname === '/') - await expect(page.getByTestId('home-copy')).toBeVisible() + await page.waitForURL(/\/([^/]*)(\/)?($|\?)/) 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(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) }) diff --git a/e2e/solid-start/streaming-ssr/package.json b/e2e/solid-start/streaming-ssr/package.json deleted file mode 100644 index 135614e439..0000000000 --- a/e2e/solid-start/streaming-ssr/package.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "name": "tanstack-solid-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/solid-query": "^5.90.9", - "@tanstack/solid-router": "workspace:^", - "@tanstack/solid-router-ssr-query": "workspace:^", - "@tanstack/solid-start": "workspace:^", - "solid-js": "^1.9.10" - }, - "devDependencies": { - "@playwright/test": "^1.61.0", - "@tanstack/router-e2e-utils": "workspace:^", - "@types/node": "^22.10.2", - "srvx": "^1.0.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" - }, - "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/solid-start/streaming-ssr/playwright.config.ts b/e2e/solid-start/streaming-ssr/playwright.config.ts deleted file mode 100644 index 1987a5a1bd..0000000000 --- a/e2e/solid-start/streaming-ssr/playwright.config.ts +++ /dev/null @@ -1,38 +0,0 @@ -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/solid-start/streaming-ssr/src/routeTree.gen.ts b/e2e/solid-start/streaming-ssr/src/routeTree.gen.ts deleted file mode 100644 index 7410f165ac..0000000000 --- a/e2e/solid-start/streaming-ssr/src/routeTree.gen.ts +++ /dev/null @@ -1,282 +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 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/solid-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/solid-start' -declare module '@tanstack/solid-start' { - interface Register { - ssr: true - router: Awaited> - } -} diff --git a/e2e/solid-start/streaming-ssr/src/router.tsx b/e2e/solid-start/streaming-ssr/src/router.tsx deleted file mode 100644 index 9e84d8316d..0000000000 --- a/e2e/solid-start/streaming-ssr/src/router.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import { QueryClient } from '@tanstack/solid-query' -import { createRouter } from '@tanstack/solid-router' -import { setupRouterSsrQueryIntegration } from '@tanstack/solid-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/solid-start/streaming-ssr/src/routes/__root.tsx b/e2e/solid-start/streaming-ssr/src/routes/__root.tsx deleted file mode 100644 index 6ddac9188e..0000000000 --- a/e2e/solid-start/streaming-ssr/src/routes/__root.tsx +++ /dev/null @@ -1,99 +0,0 @@ -import { createSignal } from 'solid-js' -import { - HeadContent, - Link, - Outlet, - Scripts, - createRootRouteWithContext, -} from '@tanstack/solid-router' -import { HydrationScript } from 'solid-js/web' -import type { QueryClient } from '@tanstack/solid-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 ( - - - - - - - - - - - - - ) -} - -function HydrationCheck() { - const [status, setStatus] = createSignal<'pending' | 'hydrated'>('pending') - - return ( -
- - - {status()} - -
- ) -} diff --git a/e2e/solid-start/streaming-ssr/src/routes/concurrent.tsx b/e2e/solid-start/streaming-ssr/src/routes/concurrent.tsx deleted file mode 100644 index 5b8b488edc..0000000000 --- a/e2e/solid-start/streaming-ssr/src/routes/concurrent.tsx +++ /dev/null @@ -1,47 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/solid-router' -import { Suspense } from 'solid-js' -import { createConcurrentLoaderData } from '../../../../streaming-ssr-fixtures' - -export const Route = createFileRoute('/concurrent')({ - loader: async () => createConcurrentLoaderData(), - component: Concurrent, -}) - -function PromiseItem(props: { promise: Promise; testId: string }) { - return ( - Loading...
} - > -
{value}
} - /> - - ) -} - -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/solid-start/streaming-ssr/src/routes/deferred-rejection.tsx b/e2e/solid-start/streaming-ssr/src/routes/deferred-rejection.tsx deleted file mode 100644 index 927ce6ed67..0000000000 --- a/e2e/solid-start/streaming-ssr/src/routes/deferred-rejection.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/solid-router' -import { Suspense } from 'solid-js' -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.message}
- ), - component: DeferredRejection, -}) - -function DeferredRejection() { - const data = Route.useLoaderData() - - return ( -
-

Deferred Rejection Test

- Loading deferred...
} - > -
{value}
} - /> - -
- ) -} diff --git a/e2e/solid-start/streaming-ssr/src/routes/deferred.tsx b/e2e/solid-start/streaming-ssr/src/routes/deferred.tsx deleted file mode 100644 index f7e78ee15e..0000000000 --- a/e2e/solid-start/streaming-ssr/src/routes/deferred.tsx +++ /dev/null @@ -1,87 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/solid-router' -import { createServerFn } from '@tanstack/solid-start' -import { Suspense } from 'solid-js' -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().immediateData.name} @{' '} - {data().immediateData.timestamp} -
-
- Immediate source: {data().immediateData.source} -
-
- Loader source: {data().loaderSource} -
- Loading deferred...
} - > - ( -
- {value.message} (source: {value.source}) -
- )} - /> - - Loading server data... - } - > - ( -
- Server: {value.name} @ {value.timestamp} (source: {value.source}) -
- )} - /> -
- - ) -} diff --git a/e2e/solid-start/streaming-ssr/src/routes/fast-serial.tsx b/e2e/solid-start/streaming-ssr/src/routes/fast-serial.tsx deleted file mode 100644 index bbcf9cc59e..0000000000 --- a/e2e/solid-start/streaming-ssr/src/routes/fast-serial.tsx +++ /dev/null @@ -1,48 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-router' -import { createServerFn } from '@tanstack/solid-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().serverData.value} @ {data().serverData.timestamp} -
-
- Server function source: {data().serverData.source} -
-
- Loader source: {data().loaderSource} -
-
Static: {data().staticData}
-
- Loader timestamp: {data().timestamp} -
-
- ) -} diff --git a/e2e/solid-start/streaming-ssr/src/routes/index.tsx b/e2e/solid-start/streaming-ssr/src/routes/index.tsx deleted file mode 100644 index f72998817a..0000000000 --- a/e2e/solid-start/streaming-ssr/src/routes/index.tsx +++ /dev/null @@ -1,58 +0,0 @@ -import { Link, createFileRoute } from '@tanstack/solid-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/solid-start/streaming-ssr/src/routes/many-promises.tsx b/e2e/solid-start/streaming-ssr/src/routes/many-promises.tsx deleted file mode 100644 index 32627be04d..0000000000 --- a/e2e/solid-start/streaming-ssr/src/routes/many-promises.tsx +++ /dev/null @@ -1,91 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/solid-router' -import { Suspense } from 'solid-js' -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 ( - - Loading {props.label}... - - } - > - ( -
- {props.label}: {value} -
- )} - /> -
- ) -} - -function ManyPromises() { - const data = Route.useLoaderData() - - return ( -
-

Many Promises Test (15 deferred)

-

Tests streaming with many concurrent deferred promises.

- - - - - - - - - - - - - - - -
- ) -} diff --git a/e2e/solid-start/streaming-ssr/src/routes/nested-deferred.tsx b/e2e/solid-start/streaming-ssr/src/routes/nested-deferred.tsx deleted file mode 100644 index 27a266129e..0000000000 --- a/e2e/solid-start/streaming-ssr/src/routes/nested-deferred.tsx +++ /dev/null @@ -1,118 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/solid-router' -import { createServerFn } from '@tanstack/solid-start' -import { Suspense } from 'solid-js' -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 ( -
- Loading level 3...
} - > - ( -
- Level 3: {value.level} @ {value.timestamp} -
- )} - /> - - - ) -} - -function Level1Content(props: { - level2: Promise<{ level: number; timestamp: number }> - level3: Promise<{ level: number; timestamp: number }> -}) { - return ( -
- Loading level 2...
} - > - ( -
- Level 2: {value.level} @ {value.timestamp} - -
- )} - /> - - - ) -} - -function NestedDeferred() { - const data = Route.useLoaderData() - - return ( -
-

Nested Deferred Test

-

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

- Loading plain...
} - > -
{value}
} - /> - -
- Loading level 1...
} - > - ( -
- Level 1: {value.level} @ {value.timestamp} - -
- )} - /> - - - - ) -} diff --git a/e2e/solid-start/streaming-ssr/src/routes/query-heavy.tsx b/e2e/solid-start/streaming-ssr/src/routes/query-heavy.tsx deleted file mode 100644 index c1d4fb9159..0000000000 --- a/e2e/solid-start/streaming-ssr/src/routes/query-heavy.tsx +++ /dev/null @@ -1,150 +0,0 @@ -import { queryOptions, useQuery } from '@tanstack/solid-query' -import { createFileRoute } from '@tanstack/solid-router' -import { Suspense } from 'solid-js' - -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 - -export const Route = createFileRoute('/query-heavy')({ - component: QueryHeavy, -}) - -function QueryDisplay(props: { queryOpts: QueryOptions; testId: string }) { - const query = useQuery(() => props.queryOpts) - - return -} - -function QueryDataView(props: { data: QueryData | undefined; testId: string }) { - return ( -
- {props.data?.value ?? 'loading...'} (source:{' '} - {props.data?.source ?? 'loading...'}) -
- ) -} - -function QuerySuspense(props: { - queryOpts: QueryOptions - testId: string - fallback: string -}) { - return ( - {props.fallback} - } - > - - - ) -} - -function QueryHeavy() { - 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)

- - - -
-
-
- ) -} diff --git a/e2e/solid-start/streaming-ssr/src/routes/slow-render.tsx b/e2e/solid-start/streaming-ssr/src/routes/slow-render.tsx deleted file mode 100644 index 60f75256e5..0000000000 --- a/e2e/solid-start/streaming-ssr/src/routes/slow-render.tsx +++ /dev/null @@ -1,72 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/solid-router' -import { createServerFn } from '@tanstack/solid-start' -import { Suspense } from 'solid-js' -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().quickData.name} @ {data().quickData.timestamp} -
-
- Quick data source: {data().quickData.source} -
-
- Loader source: {data().loaderSource} -
- Loading...
}> - ( -
- {value.message} (source: {value.source}) -
- )} - /> - - {slowRenderComponents.map((data, index) => ( - - ))} - - ) -} diff --git a/e2e/solid-start/streaming-ssr/src/routes/stream.tsx b/e2e/solid-start/streaming-ssr/src/routes/stream.tsx deleted file mode 100644 index 7da67becfe..0000000000 --- a/e2e/solid-start/streaming-ssr/src/routes/stream.tsx +++ /dev/null @@ -1,85 +0,0 @@ -import { Await, createFileRoute } from '@tanstack/solid-router' -import { createEffect, createSignal, onCleanup, Suspense } from 'solid-js' -import { - createChunkStream, - createStreamPromise, -} from '../../../../streaming-ssr-fixtures' - -export const Route = createFileRoute('/stream')({ - component: StreamRoute, - loader() { - return { - promise: createStreamPromise(), - stream: createChunkStream(), - } - }, -}) - -const decoder = new TextDecoder('utf-8') - -function StreamRoute() { - const data = Route.useLoaderData() - const [streamData, setStreamData] = createSignal>([]) - const [streamComplete, setStreamComplete] = createSignal(false) - let reader: ReadableStreamDefaultReader | undefined - - createEffect(() => { - const stream = data().stream - if (stream.locked) { - return - } - - setStreamData([]) - setStreamComplete(false) - - async function readStream() { - try { - reader = stream.getReader() - let chunk - while (!(chunk = await reader.read()).done) { - let value = chunk.value - if (typeof value !== 'string') { - value = decoder.decode(value, { stream: !chunk.done }) - } - setStreamData((prev) => [...prev, value]) - } - setStreamComplete(true) - } catch (e) { - if (!(e instanceof TypeError && String(e).includes('cancelled'))) { - console.error('Stream error:', e) - } - } - } - - void readStream() - onCleanup(() => { - reader?.cancel().catch(() => {}) - reader = undefined - }) - }) - - return ( -
-

ReadableStream Test

- Loading promise...
} - > -
{value}
} - /> - -
-

Stream chunks:

-
- {streamData().map((chunk, i) => ( -
{chunk}
- ))} -
- {streamComplete() && ( -
Stream complete!
- )} -
- - ) -} diff --git a/e2e/solid-start/streaming-ssr/src/routes/sync-only.tsx b/e2e/solid-start/streaming-ssr/src/routes/sync-only.tsx deleted file mode 100644 index c411d2e7e5..0000000000 --- a/e2e/solid-start/streaming-ssr/src/routes/sync-only.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import { createFileRoute } from '@tanstack/solid-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().message}

-

Loaded at: {data().timestamp}

-

Source: {data().source}

-
    - {data().items.map((item) => ( -
  • {item}
  • - ))} -
-
- ) -} diff --git a/e2e/solid-start/streaming-ssr/tests/client-navigation.spec.ts b/e2e/solid-start/streaming-ssr/tests/client-navigation.spec.ts deleted file mode 100644 index 8b9b3a8dcc..0000000000 --- a/e2e/solid-start/streaming-ssr/tests/client-navigation.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/client-navigation' diff --git a/e2e/solid-start/streaming-ssr/tests/concurrent.spec.ts b/e2e/solid-start/streaming-ssr/tests/concurrent.spec.ts deleted file mode 100644 index 8625473a58..0000000000 --- a/e2e/solid-start/streaming-ssr/tests/concurrent.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/concurrent' diff --git a/e2e/solid-start/streaming-ssr/tests/deferred-rejection.spec.ts b/e2e/solid-start/streaming-ssr/tests/deferred-rejection.spec.ts deleted file mode 100644 index 355b5019bc..0000000000 --- a/e2e/solid-start/streaming-ssr/tests/deferred-rejection.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/deferred-rejection' diff --git a/e2e/solid-start/streaming-ssr/tests/deferred.spec.ts b/e2e/solid-start/streaming-ssr/tests/deferred.spec.ts deleted file mode 100644 index 3145897d7b..0000000000 --- a/e2e/solid-start/streaming-ssr/tests/deferred.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/deferred' diff --git a/e2e/solid-start/streaming-ssr/tests/fast-serial.spec.ts b/e2e/solid-start/streaming-ssr/tests/fast-serial.spec.ts deleted file mode 100644 index 95df0555e2..0000000000 --- a/e2e/solid-start/streaming-ssr/tests/fast-serial.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/fast-serial' diff --git a/e2e/solid-start/streaming-ssr/tests/home.spec.ts b/e2e/solid-start/streaming-ssr/tests/home.spec.ts deleted file mode 100644 index 5d49d34a56..0000000000 --- a/e2e/solid-start/streaming-ssr/tests/home.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/home' diff --git a/e2e/solid-start/streaming-ssr/tests/many-promises.spec.ts b/e2e/solid-start/streaming-ssr/tests/many-promises.spec.ts deleted file mode 100644 index b747bd7d0a..0000000000 --- a/e2e/solid-start/streaming-ssr/tests/many-promises.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/many-promises' diff --git a/e2e/solid-start/streaming-ssr/tests/nested-deferred.spec.ts b/e2e/solid-start/streaming-ssr/tests/nested-deferred.spec.ts deleted file mode 100644 index 8df20a8a95..0000000000 --- a/e2e/solid-start/streaming-ssr/tests/nested-deferred.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/nested-deferred' diff --git a/e2e/solid-start/streaming-ssr/tests/preview-streaming.spec.ts b/e2e/solid-start/streaming-ssr/tests/preview-streaming.spec.ts deleted file mode 100644 index 34241cfbaa..0000000000 --- a/e2e/solid-start/streaming-ssr/tests/preview-streaming.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/preview-streaming' diff --git a/e2e/solid-start/streaming-ssr/tests/query-heavy.spec.ts b/e2e/solid-start/streaming-ssr/tests/query-heavy.spec.ts deleted file mode 100644 index d15c092f6e..0000000000 --- a/e2e/solid-start/streaming-ssr/tests/query-heavy.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/query-heavy' diff --git a/e2e/solid-start/streaming-ssr/tests/slow-render.spec.ts b/e2e/solid-start/streaming-ssr/tests/slow-render.spec.ts deleted file mode 100644 index 0d5a87363f..0000000000 --- a/e2e/solid-start/streaming-ssr/tests/slow-render.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/slow-render' diff --git a/e2e/solid-start/streaming-ssr/tests/stream.spec.ts b/e2e/solid-start/streaming-ssr/tests/stream.spec.ts deleted file mode 100644 index a51614f09a..0000000000 --- a/e2e/solid-start/streaming-ssr/tests/stream.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/stream' diff --git a/e2e/solid-start/streaming-ssr/tests/sync-only.spec.ts b/e2e/solid-start/streaming-ssr/tests/sync-only.spec.ts deleted file mode 100644 index 0e9278d3f2..0000000000 --- a/e2e/solid-start/streaming-ssr/tests/sync-only.spec.ts +++ /dev/null @@ -1 +0,0 @@ -import '../../../streaming-ssr-specs/sync-only' diff --git a/e2e/solid-start/streaming-ssr/tsconfig.json b/e2e/solid-start/streaming-ssr/tsconfig.json deleted file mode 100644 index ff0556e7a8..0000000000 --- a/e2e/solid-start/streaming-ssr/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "include": ["**/*.ts", "**/*.tsx"], - "compilerOptions": { - "strict": true, - "esModuleInterop": true, - "jsx": "preserve", - "jsxImportSource": "solid-js", - "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/solid-start/streaming-ssr/vite.config.ts b/e2e/solid-start/streaming-ssr/vite.config.ts deleted file mode 100644 index a9913da087..0000000000 --- a/e2e/solid-start/streaming-ssr/vite.config.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { defineConfig } from 'vite' -import { tanstackStart } from '@tanstack/solid-start/plugin/vite' -import viteSolid from 'vite-plugin-solid' - -export default defineConfig({ - server: { - port: 3000, - }, - plugins: [tanstackStart(), viteSolid({ ssr: true })], -}) diff --git a/e2e/solid-start/virtual-routes/package.json b/e2e/solid-start/virtual-routes/package.json index 7c7a12dbdb..537d212ed0 100644 --- a/e2e/solid-start/virtual-routes/package.json +++ b/e2e/solid-start/virtual-routes/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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/solid-router": "workspace:^", @@ -27,7 +27,7 @@ "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/solid-start/virtual-routes/playwright.config.ts b/e2e/solid-start/virtual-routes/playwright.config.ts index 1862174905..b0c365f8bd 100644 --- a/e2e/solid-start/virtual-routes/playwright.config.ts +++ b/e2e/solid-start/virtual-routes/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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}` /** @@ -13,19 +18,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: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', - env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, - }, }, projects: [ diff --git a/e2e/solid-start/virtual-routes/src/posts.tsx b/e2e/solid-start/virtual-routes/src/posts.tsx index 6df270c619..909620abf9 100644 --- a/e2e/solid-start/virtual-routes/src/posts.tsx +++ b/e2e/solid-start/virtual-routes/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/solid-start/virtual-routes/src/utils/posts.tsx b/e2e/solid-start/virtual-routes/src/utils/posts.tsx index d0889bd725..05ca4651fb 100644 --- a/e2e/solid-start/virtual-routes/src/utils/posts.tsx +++ b/e2e/solid-start/virtual-routes/src/utils/posts.tsx @@ -8,7 +8,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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) diff --git a/e2e/solid-start/virtual-routes/src/utils/users.tsx b/e2e/solid-start/virtual-routes/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/solid-start/virtual-routes/src/utils/users.tsx +++ b/e2e/solid-start/virtual-routes/src/utils/users.tsx @@ -3,3 +3,7 @@ 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/solid-start/virtual-routes/tests/app.spec.ts b/e2e/solid-start/virtual-routes/tests/app.spec.ts index e9db98e3f3..3182febfa0 100644 --- a/e2e/solid-start/virtual-routes/tests/app.spec.ts +++ b/e2e/solid-start/virtual-routes/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.goto('/') diff --git a/e2e/solid-start/virtual-routes/tests/setup/global.setup.ts b/e2e/solid-start/virtual-routes/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/solid-start/virtual-routes/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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/solid-start/virtual-routes/tests/setup/global.teardown.ts b/e2e/solid-start/virtual-routes/tests/setup/global.teardown.ts new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/solid-start/virtual-routes/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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/solid-start/website/package.json b/e2e/solid-start/website/package.json index 4c4044d334..4a75a19622 100644 --- a/e2e/solid-start/website/package.json +++ b/e2e/solid-start/website/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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/solid-router": "workspace:^", @@ -25,7 +25,7 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/solid-start/website/playwright.config.ts b/e2e/solid-start/website/playwright.config.ts index e6b92ce385..f6dd61ba6c 100644 --- a/e2e/solid-start/website/playwright.config.ts +++ b/e2e/solid-start/website/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/streaming-ssr-assertions.ts b/e2e/streaming-ssr-assertions.ts deleted file mode 100644 index 51d2a7343e..0000000000 --- a/e2e/streaming-ssr-assertions.ts +++ /dev/null @@ -1,143 +0,0 @@ -import { expect } from '@playwright/test' -import { test } from './e2e-utils/src/fixture' -import type { Page } from '@playwright/test' - -// Router transport markers, mirrored from router-core's hydration scripts. -// Keep every spec's protocol knowledge in this one place. -export const ROUTER_BOOTSTRAP_MARKER = '$_TSR.router=' -export const ROUTER_STREAM_END_MARKER = '$_TSR.e()' -export const STREAM_BOUNDARY_MARKER = '$tsr-stream-boundary' -export const STREAM_PART_SELECTOR = '[data-tsr-stream-part]' -const LATE_RECORD_CLOSE = 'document.currentScript.remove()' - -const immediateDataMarker = 'data-testid="immediate-data"' -const renderedDeferredMarker = 'data-testid="deferred-data"' - -const browserUserAgent = - 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36' - -export async function expectDeferredRouteResponseOrder( - baseURL: string | undefined, -) { - if (!baseURL) { - throw new Error('Playwright baseURL is required') - } - - const response = await fetch(new URL('/deferred', baseURL), { - headers: { - accept: 'text/html', - 'accept-encoding': 'identity', - 'user-agent': browserUserAgent, - }, - }) - - expect(response.status).toBe(200) - expect(response.body).not.toBeNull() - - const html = await response.text() - - const responsePreview = - html.length > 2000 - ? `${html.slice(0, 1000)}\n...\n${html.slice(-1000)}` - : html - - const immediateDataIndex = html.indexOf(immediateDataMarker) - const renderedDeferredIndex = html.indexOf(renderedDeferredMarker) - expect(immediateDataIndex, responsePreview).toBeGreaterThanOrEqual(0) - expect(renderedDeferredIndex, responsePreview).toBeGreaterThan( - immediateDataIndex, - ) - - // SSR Query closes its request-local stream after renderer EOF. Its final - // record is the deterministic late router output for this test. - const boundaryIndex = html.indexOf(STREAM_BOUNDARY_MARKER) - const routerEndIndex = html.indexOf(ROUTER_STREAM_END_MARKER) - - expect(boundaryIndex).toBeGreaterThan(-1) - expect(boundaryIndex).toBeLessThan(routerEndIndex) - expect(renderedDeferredIndex).toBeLessThan(routerEndIndex) - - expectCompleteRouterStreamBeforeDocumentCloses(html, renderedDeferredMarker) -} - -export async function expectQueryHeavyRouteStreamOrder( - baseURL: string | undefined, -) { - if (!baseURL) { - throw new Error('Playwright baseURL is required') - } - - const response = await fetch(new URL('/query-heavy', baseURL), { - headers: { - accept: 'text/html', - 'accept-encoding': 'identity', - 'user-agent': browserUserAgent, - }, - }) - - expect(response.status).toBe(200) - const html = await response.text() - - expect(html).toContain('data-testid="fast-async-query-1"') - expect(html).toContain('data-testid="slow-async-query-3"') - expectCompleteRouterStreamBeforeDocumentCloses(html, '"slow-async-3"') -} - -/** Asserts a route response carries the bootstrap, the boundary, and the end record. */ -export function expectRouterHydrationMarkers(html: string) { - expect(html).toContain(ROUTER_BOOTSTRAP_MARKER) - expect(html).toContain(ROUTER_STREAM_END_MARKER) - expect(html).toContain(STREAM_BOUNDARY_MARKER) -} - -function expectCompleteRouterStreamBeforeDocumentCloses( - html: string, - payloadMarker: string, -) { - const endIndex = html.indexOf(ROUTER_STREAM_END_MARKER) - const payloadIndex = html.indexOf(payloadMarker) - const scriptOpenIndex = html.lastIndexOf('', 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 deleted file mode 100644 index a70ef94459..0000000000 --- a/e2e/streaming-ssr-fixtures/index.ts +++ /dev/null @@ -1,381 +0,0 @@ -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 deleted file mode 100644 index 759f8e0282..0000000000 --- a/e2e/streaming-ssr-specs/client-navigation.ts +++ /dev/null @@ -1,372 +0,0 @@ -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 deleted file mode 100644 index ef14f80367..0000000000 --- a/e2e/streaming-ssr-specs/concurrent.ts +++ /dev/null @@ -1,86 +0,0 @@ -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 deleted file mode 100644 index 3e944b1c0c..0000000000 --- a/e2e/streaming-ssr-specs/deferred-rejection.ts +++ /dev/null @@ -1,21 +0,0 @@ -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 deleted file mode 100644 index abece0b43e..0000000000 --- a/e2e/streaming-ssr-specs/deferred.ts +++ /dev/null @@ -1,113 +0,0 @@ -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 deleted file mode 100644 index 03201f0a55..0000000000 --- a/e2e/streaming-ssr-specs/fast-serial.ts +++ /dev/null @@ -1,74 +0,0 @@ -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 deleted file mode 100644 index d85e19bfa7..0000000000 --- a/e2e/streaming-ssr-specs/home.ts +++ /dev/null @@ -1,34 +0,0 @@ -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 deleted file mode 100644 index 768859c7e4..0000000000 --- a/e2e/streaming-ssr-specs/many-promises.ts +++ /dev/null @@ -1,82 +0,0 @@ -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 deleted file mode 100644 index 0146a23162..0000000000 --- a/e2e/streaming-ssr-specs/nested-deferred.ts +++ /dev/null @@ -1,52 +0,0 @@ -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 deleted file mode 100644 index 5087dff730..0000000000 --- a/e2e/streaming-ssr-specs/preview-streaming.ts +++ /dev/null @@ -1,13 +0,0 @@ -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 deleted file mode 100644 index b33a64f366..0000000000 --- a/e2e/streaming-ssr-specs/query-heavy.ts +++ /dev/null @@ -1,142 +0,0 @@ -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 deleted file mode 100644 index 117559701e..0000000000 --- a/e2e/streaming-ssr-specs/slow-render.ts +++ /dev/null @@ -1,71 +0,0 @@ -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 deleted file mode 100644 index ee61f170de..0000000000 --- a/e2e/streaming-ssr-specs/stream.ts +++ /dev/null @@ -1,55 +0,0 @@ -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 deleted file mode 100644 index 9850265109..0000000000 --- a/e2e/streaming-ssr-specs/sync-only.ts +++ /dev/null @@ -1,80 +0,0 @@ -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 3af9176e83..f39c09dda9 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/vue-router/basepath-file-based/playwright.config.ts b/e2e/vue-router/basepath-file-based/playwright.config.ts index 4eead86444..6069bbe59f 100644 --- a/e2e/vue-router/basepath-file-based/playwright.config.ts +++ b/e2e/vue-router/basepath-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', }, 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basepath-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basepath-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 a51cf9149c..7eec606557 100644 --- a/e2e/vue-router/basic-esbuild-file-based/package.json +++ b/e2e/vue-router/basic-esbuild-file-based/package.json @@ -7,7 +7,7 @@ "build": "node src/esbuild.run.js build && vue-tsc --noEmit", "preview": "node src/esbuild.run.js preview", "start": "pnpm dev", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/router-plugin": "workspace:^", 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 9d9c8d49a3..836ea41bd8 100644 --- a/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-esbuild-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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} pnpm build && VITE_NODE_ENV="test" VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 16f6fbca44..c4aba8798e 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,6 +9,7 @@ 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 0ab294f2bf..19e882c1a9 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,7 +1,8 @@ -import http from 'node:http' -import { createReadStream, promises as fs } from 'node:fs' -import path from 'node:path' import * as esbuild from 'esbuild' +import http from 'node:http' +import { createReadStream } from 'node:fs' +import { promises as fs } from 'node:fs' +import path from 'node:path' import esbuildConfig from './esbuild.config.js' const args = process.argv.slice(2) @@ -17,7 +18,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 @@ -137,7 +138,7 @@ function startStaticServer({ port }) { return new Promise((resolve) => { server.listen(port, () => { - console.log(`E2E app: http://localhost:${server.address().port}`) + console.log(`http://localhost:${port}`) resolve(server) }) }) 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 7380859e7b..543746d64d 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-esbuild-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 9ab7f21e82..0cdca0cd87 100644 --- a/e2e/vue-router/basic-file-based-jsx/package.json +++ b/e2e/vue-router/basic-file-based-jsx/package.json @@ -8,7 +8,7 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", 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 4eead86444..836ea41bd8 100644 --- a/e2e/vue-router/basic-file-based-jsx/playwright.config.ts +++ b/e2e/vue-router/basic-file-based-jsx/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 f7a1941605..1b4c92b41d 100644 --- a/e2e/vue-router/basic-file-based-jsx/src/posts.tsx +++ b/e2e/vue-router/basic-file-based-jsx/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 = 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 5922c5f7b1..3922025c82 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 @@ -364,7 +364,7 @@ declare module '@tanstack/vue-router' { '/(group)/_layout': { id: '/(group)/_layout' path: '' - fullPath: '/' + fullPath: '' preLoaderRoute: typeof groupLayoutRouteImport parentRoute: typeof rootRouteImport } 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 7380859e7b..543746d64d 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-file-based-jsx/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-file-based-jsx/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 e6ffa156f9..c3e7d69bfa 100644 --- a/e2e/vue-router/basic-file-based-sfc/package.json +++ b/e2e/vue-router/basic-file-based-sfc/package.json @@ -8,7 +8,7 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", 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 4eead86444..836ea41bd8 100644 --- a/e2e/vue-router/basic-file-based-sfc/playwright.config.ts +++ b/e2e/vue-router/basic-file-based-sfc/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 f7a1941605..1b4c92b41d 100644 --- a/e2e/vue-router/basic-file-based-sfc/src/posts.ts +++ b/e2e/vue-router/basic-file-based-sfc/src/posts.ts @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 = 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 0bfdddab3d..09d62b0706 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 @@ -454,7 +454,7 @@ declare module '@tanstack/vue-router' { '/(group)/_layout': { id: '/(group)/_layout' path: '' - fullPath: '/' + fullPath: '' preLoaderRoute: typeof groupLayoutRouteImport 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 7380859e7b..543746d64d 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-file-based-sfc/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-file-based-sfc/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 f4616a5651..965a59aa79 100644 --- a/e2e/vue-router/basic-scroll-restoration/package.json +++ b/e2e/vue-router/basic-scroll-restoration/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/vue-router/basic-scroll-restoration/playwright.config.ts b/e2e/vue-router/basic-scroll-restoration/playwright.config.ts index 6a684ac89e..0c5cee43e4 100644 --- a/e2e/vue-router/basic-scroll-restoration/playwright.config.ts +++ b/e2e/vue-router/basic-scroll-restoration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, 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 3701c2254c..374ea348e2 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", 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 4eead86444..836ea41bd8 100644 --- a/e2e/vue-router/basic-virtual-file-based/playwright.config.ts +++ b/e2e/vue-router/basic-virtual-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 5f5463a668..8576a3799a 100644 --- a/e2e/vue-router/basic-virtual-file-based/src/posts.tsx +++ b/e2e/vue-router/basic-virtual-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) 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 fbf093cd51..3e5a69ccaa 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-virtual-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-virtual-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 d3a69ed573..2e368cbd72 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", 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 4eead86444..836ea41bd8 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,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 5f5463a668..8576a3799a 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,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) 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 fbf093cd51..3e5a69ccaa 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 3b4422d8d8..9b2e3cca0d 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", 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 fbda9bd451..6e7c123f74 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,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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}` /** @@ -12,15 +17,17 @@ 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: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 1f6cb8e308..1becc2c242 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,7 +8,11 @@ export type PostType = { export class PostNotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +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 = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) 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 2b42d6d589..d80e8dada5 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,23 +1,24 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' +import { getDummyServerPort } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } test.beforeEach(async ({ page }) => { await page.goto('/') }) -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) +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() + 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-vue-query-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-vue-query-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 28889522fc..123a2f4122 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", "node"] + "types": ["vite/client"] }, "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 68f1a8c9ea..ba3f4295d5 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/vue-router/basic-vue-query/playwright.config.ts b/e2e/vue-router/basic-vue-query/playwright.config.ts index 4eead86444..836ea41bd8 100644 --- a/e2e/vue-router/basic-vue-query/playwright.config.ts +++ b/e2e/vue-router/basic-vue-query/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic-vue-query/src/posts.ts b/e2e/vue-router/basic-vue-query/src/posts.ts index 69e1814af5..18f8a9f93f 100644 --- a/e2e/vue-router/basic-vue-query/src/posts.ts +++ b/e2e/vue-router/basic-vue-query/src/posts.ts @@ -9,7 +9,11 @@ type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} 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 fbf093cd51..3e5a69ccaa 100644 --- a/e2e/vue-router/basic-vue-query/tests/app.spec.ts +++ b/e2e/vue-router/basic-vue-query/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic-vue-query/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic-vue-query/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 1b57dae772..e1b7f0ae1a 100644 --- a/e2e/vue-router/basic/package.json +++ b/e2e/vue-router/basic/package.json @@ -8,7 +8,7 @@ "build": "vite build && vue-tsc --noEmit", "preview": "vite preview", "start": "vite", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/vue-router/basic/playwright.config.ts b/e2e/vue-router/basic/playwright.config.ts index 4eead86444..836ea41bd8 100644 --- a/e2e/vue-router/basic/playwright.config.ts +++ b/e2e/vue-router/basic/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', }, diff --git a/e2e/vue-router/basic/src/posts.ts b/e2e/vue-router/basic/src/posts.ts index f72d16fee3..e859645746 100644 --- a/e2e/vue-router/basic/src/posts.ts +++ b/e2e/vue-router/basic/src/posts.ts @@ -8,7 +8,11 @@ type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 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 9c0a6b6901..ec0e24d8a4 100644 --- a/e2e/vue-router/basic/tests/app.spec.ts +++ b/e2e/vue-router/basic/tests/app.spec.ts @@ -1,7 +1,8 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from '../package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) 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 f673138047..ac18f39864 100644 --- a/e2e/vue-router/basic/tests/params.spec.ts +++ b/e2e/vue-router/basic/tests/params.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/basic/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/basic/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 f9324643ac..53e2cc1366 100644 --- a/e2e/vue-router/generator-cli-only/package.json +++ b/e2e/vue-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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/vue-router/generator-cli-only/playwright.config.ts b/e2e/vue-router/generator-cli-only/playwright.config.ts index 4eead86444..c9d9a76ae7 100644 --- a/e2e/vue-router/generator-cli-only/playwright.config.ts +++ b/e2e/vue-router/generator-cli-only/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 f72d16fee3..e859645746 100644 --- a/e2e/vue-router/generator-cli-only/src/posts.ts +++ b/e2e/vue-router/generator-cli-only/src/posts.ts @@ -8,7 +8,11 @@ type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 fetchPosts = async () => { console.info('Fetching posts...') 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 ced5ac9310..5a83a314f2 100644 --- a/e2e/vue-router/generator-cli-only/tests/app.spec.ts +++ b/e2e/vue-router/generator-cli-only/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/generator-cli-only/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/generator-cli-only/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 cda098978c..0ac86a7a56 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", 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 0925936d55..4f93bc1413 100644 --- a/e2e/vue-router/js-only-file-based/playwright.config.ts +++ b/e2e/vue-router/js-only-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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}` /** @@ -13,15 +18,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 36c1c281f6..979e5e381c 100644 --- a/e2e/vue-router/js-only-file-based/src/posts.js +++ b/e2e/vue-router/js-only-file-based/src/posts.js @@ -2,7 +2,11 @@ import axios from 'redaxios' export class NotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +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 fetchPosts = async () => { console.info('Fetching posts...') 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 ced5ac9310..5a83a314f2 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/js-only-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/js-only-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 93439f7d5b..449511d8fd 100644 --- a/e2e/vue-router/rspack-basic-file-based/package.json +++ b/e2e/vue-router/rspack-basic-file-based/package.json @@ -7,7 +7,7 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -17,7 +17,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-babel": "^1.1.2", "@rsbuild/plugin-vue": "^1.2.7", "@rsbuild/plugin-vue-jsx": "^2.0.0", 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 4eead86444..5f20415459 100644 --- a/e2e/vue-router/rspack-basic-file-based/playwright.config.ts +++ b/e2e/vue-router/rspack-basic-file-based/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 c91449b6c3..d5e4b7456c 100644 --- a/e2e/vue-router/rspack-basic-file-based/rsbuild.config.ts +++ b/e2e/vue-router/rspack-basic-file-based/rsbuild.config.ts @@ -12,6 +12,19 @@ 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 5f5463a668..0b557a0f65 100644 --- a/e2e/vue-router/rspack-basic-file-based/src/posts.tsx +++ b/e2e/vue-router/rspack-basic-file-based/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.PUBLIC_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` +} export const fetchPost = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) 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 d230263bfe..10beff655f 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/rspack-basic-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/rspack-basic-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 536435a09e..944210cd10 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,7 +7,7 @@ "build": "rsbuild build && tsc --noEmit", "preview": "rsbuild preview", "start": "rsbuild preview", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -17,7 +17,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-babel": "^1.1.2", "@rsbuild/plugin-vue": "^1.2.7", "@rsbuild/plugin-vue-jsx": "^2.0.0", 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 1c1d021f2f..bf3adc082c 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,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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. @@ -12,15 +17,18 @@ 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 build && pnpm start --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 e5c7e8b77e..b09f6ccda8 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,6 +12,19 @@ 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 5f5463a668..0b557a0f65 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,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.PUBLIC_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.PUBLIC_EXTERNAL_PORT}` +} 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/tests/app.spec.ts b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/app.spec.ts index d230263bfe..10beff655f 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/rspack-basic-virtual-named-export-config-file-based/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 d071ee546a..f735fce364 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/package.json +++ b/e2e/vue-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": "pnpm run test:e2e:browser && pnpm run test:e2e:hash" + "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:browser && pnpm run test:e2e:hash" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", @@ -31,15 +31,5 @@ "typescript": "~5.8.3", "vite": "^8.0.14", "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 e2681daea5..9d7691f0fd 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,7 +1,15 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, + resolveRuntimeSuffix, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + packageJson.name + `-${resolveRuntimeSuffix('browser')}`, +) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +20,18 @@ 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_APP_HISTORY=browser pnpm build && VITE_APP_HISTORY=browser pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 445616b9bd..80a340cef4 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,7 +1,15 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, + resolveRuntimeSuffix, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort( + packageJson.name + `-${resolveRuntimeSuffix('hash')}`, +) +const EXTERNAL_PORT = await getDummyServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -12,15 +20,18 @@ 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_APP_HISTORY=hash vite build --outDir dist-hash && VITE_APP_HISTORY=hash pnpm preview --port ${PORT} --outDir dist-hash`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 bc56dff904..c6cba486ab 100644 --- a/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/src/posts.tsx @@ -12,7 +12,11 @@ export type PostType = { export class PostNotFoundError extends Error {} -const queryURL = 'https://jsonplaceholder.typicode.com' +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 = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) 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 067f0341c4..5f226c6db3 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,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/scroll-restoration-sandbox-vite/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 b47cca9589..3e5b04987f 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", "dist-hash"] + "exclude": ["node_modules", "dist"] } diff --git a/e2e/vue-router/sentry-integration/package.json b/e2e/vue-router/sentry-integration/package.json index 045ddd99be..344a338a27 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@sentry/vue": "^10.32.0", diff --git a/e2e/vue-router/sentry-integration/playwright.config.ts b/e2e/vue-router/sentry-integration/playwright.config.ts index 6a684ac89e..0c5cee43e4 100644 --- a/e2e/vue-router/sentry-integration/playwright.config.ts +++ b/e2e/vue-router/sentry-integration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && VITE_SERVER_PORT=${PORT} pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-router/view-transitions/package.json b/e2e/vue-router/view-transitions/package.json index 21a0f1d8a0..5466ded0ed 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tailwindcss/vite": "^4.2.2", diff --git a/e2e/vue-router/view-transitions/playwright.config.ts b/e2e/vue-router/view-transitions/playwright.config.ts index 4eead86444..c5de6b5611 100644 --- a/e2e/vue-router/view-transitions/playwright.config.ts +++ b/e2e/vue-router/view-transitions/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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,10 +22,13 @@ export default defineConfig({ baseURL, }, + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + webServer: { - command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + 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, stdout: 'pipe', }, diff --git a/e2e/vue-router/view-transitions/tests/app.spec.ts b/e2e/vue-router/view-transitions/tests/app.spec.ts index 6c1ccf1a6e..472bd6ed0b 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 { apiTest as test } from '@tanstack/router-e2e-utils' +import { test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-router/view-transitions/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-router/view-transitions/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 e62662a1d2..31d8b12b04 100644 --- a/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts +++ b/e2e/vue-router/view-transitions/tests/view-transitions.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' test.beforeEach(async ({ page }) => { await page.addInitScript(() => { diff --git a/e2e/vue-start/basic-auth/package.json b/e2e/vue-start/basic-auth/package.json index 7f6fb798da..0c22edfc4c 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": "mkdir -p .tmp; rm -f .tmp/dev.db .tmp/dev.db-journal .tmp/dev.db-wal .tmp/dev.db-shm; export DATABASE_URL=file:./.tmp/dev.db; pnpm run prisma-generate && pnpm exec prisma migrate deploy && playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; mkdir -p .tmp; rm -f .tmp/dev.db .tmp/dev.db-journal .tmp/dev.db-wal .tmp/dev.db-shm; export DATABASE_URL=file:./.tmp/dev.db; pnpm run prisma-generate && pnpm exec prisma migrate deploy && playwright test --project=chromium" }, "dependencies": { "@libsql/client": "^0.15.15", @@ -19,7 +19,6 @@ "@tanstack/vue-router": "workspace:^", "@tanstack/vue-router-devtools": "workspace:^", "@tanstack/vue-start": "workspace:^", - "iron-session": "^9.0.1", "redaxios": "catalog:", "tailwind-merge": "^3.6.0", "vue": "^3.5.25" @@ -33,21 +32,10 @@ "@vitejs/plugin-vue-jsx": "^5.1.5", "dotenv": "^17.2.3", "prisma": "^7.0.0", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.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 82678ac00b..18b8905468 100644 --- a/e2e/vue-start/basic-auth/playwright.config.ts +++ b/e2e/vue-start/basic-auth/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/basic-auth/src/routes/__root.tsx b/e2e/vue-start/basic-auth/src/routes/__root.tsx index e5b6f6778f..f486bf4cb7 100644 --- a/e2e/vue-start/basic-auth/src/routes/__root.tsx +++ b/e2e/vue-start/basic-auth/src/routes/__root.tsx @@ -16,18 +16,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 { getAppSession } from '~/utils/session.js' +import { useAppSession } 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 getAppSession() + const session = await useAppSession() - if (!session.userEmail) { + if (!session.data.userEmail) { return null } return { - email: session.userEmail, + email: session.data.userEmail, } }) diff --git a/e2e/vue-start/basic-auth/src/routes/_authed.tsx b/e2e/vue-start/basic-auth/src/routes/_authed.tsx index 606de3e487..ba88e3beac 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 { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST', @@ -37,11 +37,12 @@ export const loginFn = createServerFn({ } // Create a session - const session = await getAppSession() + const session = await useAppSession() // Store the user's email in the session - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) }) export const Route = createFileRoute('/_authed')({ diff --git a/e2e/vue-start/basic-auth/src/routes/logout.tsx b/e2e/vue-start/basic-auth/src/routes/logout.tsx index 8372b33608..f1d7b58e29 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 { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' const logoutFn = createServerFn({ method: 'POST' }).handler(async () => { - const session = await getAppSession() + const session = await useAppSession() - session.destroy() + session.clear() 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 5f37f109c7..eade8363e6 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 { getAppSession } from '~/utils/session' +import { useAppSession } 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 getAppSession() + const session = await useAppSession() if (found) { if (found.password !== password) { @@ -37,8 +37,9 @@ export const signupFn = createServerFn({ } // Store the user's email in the session - session.userEmail = found.email - await session.save() + await session.update({ + userEmail: found.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -55,8 +56,9 @@ export const signupFn = createServerFn({ }) // Store the user's email in the session - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) // 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 7d078225a0..7cf2a41792 100644 --- a/e2e/vue-start/basic-auth/src/utils/session.ts +++ b/e2e/vue-start/basic-auth/src/utils/session.ts @@ -1,25 +1,13 @@ -import { getIronSession } from 'iron-session' -import { getCookie, setCookie } from '@tanstack/vue-start/server' +// src/services/session.server.ts +import { useSession } from '@tanstack/vue-start/server' import type { User } from '~/prisma-generated/client' type SessionUser = { userEmail: User['email'] } -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: '/', - }, - }, - ) +export function useAppSession() { + return useSession({ + password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', + }) } diff --git a/e2e/vue-start/basic-cloudflare/package.json b/e2e/vue-start/basic-cloudflare/package.json index 5ab77db8fc..612a6b8d19 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -31,15 +31,5 @@ "@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 0925936d55..a545dff891 100644 --- a/e2e/vue-start/basic-cloudflare/playwright.config.ts +++ b/e2e/vue-start/basic-cloudflare/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -13,6 +14,9 @@ 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, @@ -20,8 +24,8 @@ export default defineConfig({ webServer: { command: `pnpm build && pnpm preview --port ${PORT}`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/basic-cloudflare/tests/setup/global.setup.ts b/e2e/vue-start/basic-cloudflare/tests/setup/global.setup.ts new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-start/basic-cloudflare/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/basic-cloudflare/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 828dce5b2a..9884efa343 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -19,7 +19,7 @@ "devDependencies": { "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "@vitejs/plugin-vue": "^6.0.5", diff --git a/e2e/vue-start/basic-tsr-config/playwright.config.ts b/e2e/vue-start/basic-tsr-config/playwright.config.ts index e6b92ce385..f6dd61ba6c 100644 --- a/e2e/vue-start/basic-tsr-config/playwright.config.ts +++ b/e2e/vue-start/basic-tsr-config/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/basic-vue-query/package.json b/e2e/vue-start/basic-vue-query/package.json index ab9589376d..1003bd2e27 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-query": "^5.92.1", @@ -30,7 +30,7 @@ "@types/node": "^22.10.2", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/vue-start/basic-vue-query/playwright.config.ts b/e2e/vue-start/basic-vue-query/playwright.config.ts index 0618b7272a..84636ab0f9 100644 --- a/e2e/vue-start/basic-vue-query/playwright.config.ts +++ b/e2e/vue-start/basic-vue-query/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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}` @@ -11,18 +16,18 @@ export default defineConfig({ reporter: [['line']], + globalSetup: './tests/setup/global.setup.ts', + globalTeardown: './tests/setup/global.teardown.ts', + use: { baseURL, }, webServer: { - command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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/routes/api.users.ts b/e2e/vue-start/basic-vue-query/src/routes/api.users.ts index f9330a87db..cab4cafc3f 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,7 +2,11 @@ import { createFileRoute } from '@tanstack/vue-router' import axios from 'redaxios' import type { User } from '../utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +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: { 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 d138746730..4cc4b33a0b 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,7 +2,11 @@ import { createFileRoute } from '@tanstack/vue-router' import axios from 'redaxios' import type { User } from '../../utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +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: { 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 c6b5e70a0b..b0a0b8f60d 100644 --- a/e2e/vue-start/basic-vue-query/src/utils/posts.tsx +++ b/e2e/vue-start/basic-vue-query/src/utils/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 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 fe7a902fa2..29bf08c315 100644 --- a/e2e/vue-start/basic-vue-query/src/utils/users.tsx +++ b/e2e/vue-start/basic-vue-query/src/utils/users.tsx @@ -1,6 +1,4 @@ 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 = { @@ -9,16 +7,17 @@ export type User = { email: string } -const getOrigin = createIsomorphicFn() - .server(() => getRequestUrl().origin) - .client(() => window.location.origin) +const PORT = + import.meta.env.VITE_SERVER_PORT || process.env.VITE_SERVER_PORT || 3000 + +export const DEPLOY_URL = `http://localhost:${PORT}` export const usersQueryOptions = () => queryOptions({ queryKey: ['users'], queryFn: () => axios - .get>(getOrigin() + '/api/users') + .get>(DEPLOY_URL + '/api/users') .then((r) => r.data) .catch(() => { throw new Error('Failed to fetch users') @@ -30,7 +29,7 @@ export const userQueryOptions = (id: string) => queryKey: ['users', id], queryFn: () => axios - .get(getOrigin() + '/api/users/' + id) + .get(DEPLOY_URL + '/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 4ce5c20ef7..ab2469f68d 100644 --- a/e2e/vue-start/basic-vue-query/tests/app.spec.ts +++ b/e2e/vue-start/basic-vue-query/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-start/basic-vue-query/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/basic-vue-query/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 a0f3bf0964..2c28fc72a2 100644 --- a/e2e/vue-start/basic-vue-query/tests/transition.spec.ts +++ b/e2e/vue-start/basic-vue-query/tests/transition.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 2ff8329543..6d456525b5 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": "pnpm build:vite", + "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "node server.js", - "test:e2e:local": "playwright test --project=chromium", - "build:vite": "vite build && tsc --noEmit", - "build:rsbuild": "rsbuild build && tsc --noEmit" + "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": { "@tanstack/vue-router": "workspace:^", @@ -27,7 +27,7 @@ }, "devDependencies": { "@playwright/test": "^1.61.0", - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-babel": "^1.1.2", "@rsbuild/plugin-vue": "^1.2.7", "@rsbuild/plugin-vue-jsx": "^2.0.0", @@ -39,7 +39,7 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", @@ -59,10 +59,7 @@ }, { "toolchain": "vite", - "mode": "prerender", - "env": { - "NODE_OPTIONS": "--import=@tanstack/router-e2e-utils/mock-api" - } + "mode": "prerender" }, { "toolchain": "vite", diff --git a/e2e/vue-start/basic/playwright.config.ts b/e2e/vue-start/basic/playwright.config.ts index 9322874f3a..6924134cd1 100644 --- a/e2e/vue-start/basic/playwright.config.ts +++ b/e2e/vue-start/basic/playwright.config.ts @@ -1,37 +1,59 @@ +import fs from 'node:fs' import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } const mode = process.env.MODE ?? 'ssr' - +const e2ePortKey = process.env.E2E_PORT_KEY ?? packageJson.name const distDir = process.env.E2E_DIST_DIR ?? 'dist' -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +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 baseURL = `http://localhost:${PORT}` const commandByMode = mode === 'preview' - ? `pnpm preview --host 0.0.0.0 --outDir ${distDir} --port ${PORT}` - : `pnpm start` + ? `pnpm run test:e2e:startDummyServer && pnpm preview --outDir ${distDir} --port ${PORT}` + : `pnpm run test:e2e:startDummyServer && pnpm start` export default defineConfig({ testDir: './tests', workers: 1, reporter: [['line']], + globalTeardown: './tests/setup/global.teardown.ts', + use: { baseURL, }, webServer: { command: commandByMode, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', env: { - NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ''} --import=@tanstack/router-e2e-utils/mock-api`, MODE: mode, - START_PORT: '0', + VITE_NODE_ENV: 'test', + VITE_EXTERNAL_PORT: String(EXTERNAL_PORT), + VITE_SERVER_PORT: String(PORT), + START_PORT: String(START_PORT), PORT: String(PORT), E2E_DIST_DIR: distDir, + E2E_PORT_KEY: e2ePortKey, }, }, diff --git a/e2e/vue-start/basic/server.js b/e2e/vue-start/basic/server.js index 3e1ddab400..69c1e4ca91 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 = Number(process.env.PORT ?? 3000) +const port = process.env.PORT || 3000 -const startPort = Number(process.env.START_PORT ?? 0) +const startPort = process.env.START_PORT || 3001 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(backendPort) { +export async function createSpaServer() { const app = express() app.use( '/api', createProxyMiddleware({ - target: `http://localhost:${backendPort}/api`, // Replace with your target server's URL + target: `http://localhost:${startPort}/api`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -63,7 +63,7 @@ export async function createSpaServer(backendPort) { app.use( '/_serverFn', createProxyMiddleware({ - target: `http://localhost:${backendPort}/_serverFn`, // Replace with your target server's URL + target: `http://localhost:${startPort}/_serverFn`, // Replace with your target server's URL changeOrigin: false, // Needed for virtual hosted sites, }), ) @@ -71,28 +71,31 @@ export async function createSpaServer(backendPort) { app.use(express.static(distClientDir)) app.get('/{*splat}', (req, res) => { - res.sendFile('index.html', { root: distClientDir }) + res.sendFile(path.resolve(distClientDir, 'index.html')) }) return { app } } -// 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}`) - } -}) +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}`) + }), + ) +} 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 24938d51c2..50b9ca995a 100644 --- a/e2e/vue-start/basic/src/routes/api/users.$userId.ts +++ b/e2e/vue-start/basic/src/routes/api/users.$userId.ts @@ -1,15 +1,19 @@ 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( - `https://jsonplaceholder.typicode.com/users/${params.userId}`, - ) + const res = await fetch(`${queryURL}/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 c6045977b8..97989b93ca 100644 --- a/e2e/vue-start/basic/src/routes/api/users.ts +++ b/e2e/vue-start/basic/src/routes/api/users.ts @@ -38,13 +38,19 @@ 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('https://jsonplaceholder.typicode.com/users') + const res = await fetch(`${queryURL}/users`) if (!res.ok) { throw new Error('Failed to fetch users') } diff --git a/e2e/vue-start/basic/src/utils/posts.tsx b/e2e/vue-start/basic/src/utils/posts.tsx index d8e2dc7450..66cb298f83 100644 --- a/e2e/vue-start/basic/src/utils/posts.tsx +++ b/e2e/vue-start/basic/src/utils/posts.tsx @@ -8,12 +8,18 @@ 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(`https://jsonplaceholder.typicode.com/posts/${postId}`) + .get(`${queryURL}/posts/${postId}`) .then((r) => r.data) .catch((err) => { console.error(err) @@ -30,7 +36,7 @@ export const fetchPosts = createServerFn({ method: 'GET' }).handler( async () => { console.info('Fetching posts...') return axios - .get>('https://jsonplaceholder.typicode.com/posts') + .get>(`${queryURL}/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 7ba645b383..46be4b1580 100644 --- a/e2e/vue-start/basic/src/utils/users.tsx +++ b/e2e/vue-start/basic/src/utils/users.tsx @@ -3,3 +3,7 @@ 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 4da6234c8a..e8259b1e33 100644 --- a/e2e/vue-start/basic/src/vite-env.d.ts +++ b/e2e/vue-start/basic/src/vite-env.d.ts @@ -2,6 +2,7 @@ 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 deleted file mode 100644 index 6c9b26dc4c..0000000000 --- a/e2e/vue-start/basic/tests/fixture-api.spec.ts +++ /dev/null @@ -1,11 +0,0 @@ -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 8e6ceba5b9..2f6354aa81 100644 --- a/e2e/vue-start/basic/tests/redirect.spec.ts +++ b/e2e/vue-start/basic/tests/redirect.spec.ts @@ -1,14 +1,19 @@ import queryString from 'node:querystring' -import { expect } from '@playwright/test' -import { test } from '@tanstack/router-e2e-utils' +import { expect, type Page } from '@playwright/test' import combinateImport from 'combinate' -import type { Page } from '@playwright/test' +import { + getDummyServerPort, + getTestServerPort, + test, +} from '@tanstack/router-e2e-utils' +import { getE2EPortKey } from './utils/getE2EPortKey.ts' // somehow playwright does not correctly import default exports const combinate = (combinateImport as any).default as typeof combinateImport -const PORT = Number(process.env.E2E_APP_PORT ?? 0) -const EXTERNAL_ORIGIN = `http://127.0.0.1:${PORT}` +const e2ePortKey = getE2EPortKey() +const PORT = await getTestServerPort(e2ePortKey) +const EXTERNAL_HOST_PORT = await getDummyServerPort(e2ePortKey) const POSTS_URL = `http://localhost:${PORT}/posts` async function waitForRouterIdle(page: Page) { @@ -101,7 +106,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, }) if (scenario === 'navigate') { @@ -114,7 +119,7 @@ test.describe('redirects', () => { await page.goto(`/redirect/external/via-${thrower}?${q}`) } - const url = `${EXTERNAL_ORIGIN}/` + const url = `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) @@ -135,7 +140,7 @@ test.describe('redirects', () => { }) => { let fullPageLoad = false const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, reloadDocument, }) @@ -154,7 +159,10 @@ test.describe('redirects', () => { await page.goto(`/redirect/${target}/serverFn/via-${thrower}?${q}`) } - const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` + const url = + target === 'internal' + ? POSTS_URL + : `http://localhost:${EXTERNAL_HOST_PORT}/` await page.waitForURL(url) expect(page.url()).toBe(url) if (target === 'internal' && scenario === 'navigate') { @@ -176,7 +184,7 @@ test.describe('redirects', () => { page, }) => { const q = queryString.stringify({ - externalHost: `${EXTERNAL_ORIGIN}/`, + externalHost: `http://localhost:${EXTERNAL_HOST_PORT}/`, reloadDocument, }) @@ -193,7 +201,10 @@ test.describe('redirects', () => { await button.click() - const url = target === 'internal' ? POSTS_URL : `${EXTERNAL_ORIGIN}/` + const url = + target === 'internal' + ? POSTS_URL + : `http://localhost:${EXTERNAL_HOST_PORT}/` 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 new file mode 100644 index 0000000000..cd38c35885 --- /dev/null +++ b/e2e/vue-start/basic/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..36e5c92858 --- /dev/null +++ b/e2e/vue-start/basic/tests/setup/global.teardown.ts @@ -0,0 +1,8 @@ +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 new file mode 100644 index 0000000000..88c18fd79e --- /dev/null +++ b/e2e/vue-start/basic/tests/setup/waitForDummyServer.ts @@ -0,0 +1,24 @@ +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 new file mode 100644 index 0000000000..48be6a9027 --- /dev/null +++ b/e2e/vue-start/basic/tests/utils/getE2EPortKey.ts @@ -0,0 +1,5 @@ +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 3671774644..c739f09ea0 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": "pnpm run test:e2e:dev" + "test:e2e": "rm -rf port*.txt; pnpm run test:e2e:dev" }, "dependencies": { "@tanstack/vue-router": "workspace:*", @@ -24,7 +24,7 @@ "@types/node": "^22.10.2", "@vitejs/plugin-vue-jsx": "^5.1.5", "sass": "^1.97.2", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@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 a50ac5ae63..0b810d5372 100644 --- a/e2e/vue-start/css-modules/playwright.config.ts +++ b/e2e/vue-start/css-modules/playwright.config.ts @@ -1,9 +1,10 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +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 = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -12,17 +13,16 @@ 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 --port 0` - : `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + command: isDev ? `pnpm dev:e2e` : `pnpm build && PORT=${PORT} pnpm start`, + url: baseURL, + reuseExistingServer: !process.env.CI, 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 17be637f77..2d3a1db946 100644 --- a/e2e/vue-start/css-modules/tests/setup/global.setup.ts +++ b/e2e/vue-start/css-modules/tests/setup/global.setup.ts @@ -1,9 +1,17 @@ -import { preOptimizeDevServer, waitForServer } from '@tanstack/router-e2e-utils' +import { + e2eStartDummyServer, + getTestServerPort, + preOptimizeDevServer, + waitForServer, +} from '@tanstack/router-e2e-utils' +import packageJson from '../../package.json' with { type: 'json' } export default async function setup() { + await e2eStartDummyServer(packageJson.name) + if (process.env.MODE !== 'dev') return - const port = Number(process.env.E2E_APP_PORT ?? 0) + const port = await getTestServerPort(packageJson.name) 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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/css-modules/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 b9bf393466..1884c5eb5a 100644 --- a/e2e/vue-start/custom-basepath/express-server.ts +++ b/e2e/vue-start/custom-basepath/express-server.ts @@ -1,6 +1,5 @@ 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' @@ -41,11 +40,7 @@ if (DEVELOPMENT) { }) } -const httpServer = app.listen(PORT, (error) => { - if (error) { - throw error - } - console.log( - `E2E app: http://localhost:${(httpServer.address() as AddressInfo).port}`, - ) +app.listen(PORT, (error) => { + if (error) throw error + console.log(`Server is running on http://localhost:${PORT}`) }) diff --git a/e2e/vue-start/custom-basepath/package.json b/e2e/vue-start/custom-basepath/package.json index c1032ea88b..afc7d13c25 100644 --- a/e2e/vue-start/custom-basepath/package.json +++ b/e2e/vue-start/custom-basepath/package.json @@ -8,7 +8,7 @@ "build": "vite build && tsc --noEmit", "preview": "vite preview", "start": "tsx express-server.ts", - "test:e2e": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -25,7 +25,7 @@ "@types/express": "^5.0.6", "@types/node": "^22.10.2", "cross-env": "^10.0.0", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "tsx": "^4.20.3", "@typescript/native": "npm:typescript@^7.0.2", diff --git a/e2e/vue-start/custom-basepath/playwright.config.ts b/e2e/vue-start/custom-basepath/playwright.config.ts index e113ce64ad..5095425f47 100644 --- a/e2e/vue-start/custom-basepath/playwright.config.ts +++ b/e2e/vue-start/custom-basepath/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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}/custom/basepath` /** @@ -13,19 +18,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: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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/routes/api/users.$userId.ts b/e2e/vue-start/custom-basepath/src/routes/api/users.$userId.ts index 7e3f528d68..50b9ca995a 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,7 +1,11 @@ import { createFileRoute } from '@tanstack/vue-router' import type { User } from '~/utils/users' -const queryURL = 'https://jsonplaceholder.typicode.com' +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: { 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 dfdb5cd844..97989b93ca 100644 --- a/e2e/vue-start/custom-basepath/src/routes/api/users.ts +++ b/e2e/vue-start/custom-basepath/src/routes/api/users.ts @@ -38,7 +38,11 @@ const testMiddleware = createMiddleware() return result }) -const queryURL = 'https://jsonplaceholder.typicode.com' +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: { diff --git a/e2e/vue-start/custom-basepath/src/utils/posts.tsx b/e2e/vue-start/custom-basepath/src/utils/posts.tsx index 11d80d08b5..66cb298f83 100644 --- a/e2e/vue-start/custom-basepath/src/utils/posts.tsx +++ b/e2e/vue-start/custom-basepath/src/utils/posts.tsx @@ -8,7 +8,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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) diff --git a/e2e/vue-start/custom-basepath/src/utils/users.tsx b/e2e/vue-start/custom-basepath/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/vue-start/custom-basepath/src/utils/users.tsx +++ b/e2e/vue-start/custom-basepath/src/utils/users.tsx @@ -3,3 +3,7 @@ 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-start/custom-basepath/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/custom-basepath/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 deleted file mode 100644 index 950326609c..0000000000 --- a/e2e/vue-start/dev-ssr-styles/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -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 deleted file mode 100644 index 0033a0a5cc..0000000000 --- a/e2e/vue-start/dev-ssr-styles/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "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 deleted file mode 100644 index 723cd32789..0000000000 --- a/e2e/vue-start/dev-ssr-styles/playwright.config.ts +++ /dev/null @@ -1,28 +0,0 @@ -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 deleted file mode 100644 index bd92215136..0000000000 --- a/e2e/vue-start/dev-ssr-styles/src/components/SfcStyledBox.vue +++ /dev/null @@ -1,14 +0,0 @@ - - - diff --git a/e2e/vue-start/dev-ssr-styles/src/router.tsx b/e2e/vue-start/dev-ssr-styles/src/router.tsx deleted file mode 100644 index c0d7f2b200..0000000000 --- a/e2e/vue-start/dev-ssr-styles/src/router.tsx +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index 0dec479a07..0000000000 --- a/e2e/vue-start/dev-ssr-styles/src/routes/__root.tsx +++ /dev/null @@ -1,27 +0,0 @@ -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 deleted file mode 100644 index 733bc1d559..0000000000 --- a/e2e/vue-start/dev-ssr-styles/src/routes/index.tsx +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index 9a67f9b153..0000000000 --- a/e2e/vue-start/dev-ssr-styles/src/styles/app.css +++ /dev/null @@ -1,5 +0,0 @@ -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 deleted file mode 100644 index fe00a856b2..0000000000 --- a/e2e/vue-start/dev-ssr-styles/src/vue-shim.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index 0e052441b7..0000000000 --- a/e2e/vue-start/dev-ssr-styles/tests/app.spec.ts +++ /dev/null @@ -1,61 +0,0 @@ -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 deleted file mode 100644 index b03b6485c8..0000000000 --- a/e2e/vue-start/dev-ssr-styles/tests/setup/global.setup.ts +++ /dev/null @@ -1,15 +0,0 @@ -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 deleted file mode 100644 index 898ea214b1..0000000000 --- a/e2e/vue-start/dev-ssr-styles/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "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 deleted file mode 100644 index f8b7293af9..0000000000 --- a/e2e/vue-start/dev-ssr-styles/vite.config.ts +++ /dev/null @@ -1,14 +0,0 @@ -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 617ce4f430..a3b775e0eb 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-query": "^5.90.0", diff --git a/e2e/vue-start/query-integration/playwright.config.ts b/e2e/vue-start/query-integration/playwright.config.ts index 82678ac00b..4d86a1dbe7 100644 --- a/e2e/vue-start/query-integration/playwright.config.ts +++ b/e2e/vue-start/query-integration/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { derivePort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await derivePort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/scroll-restoration/package.json b/e2e/vue-start/scroll-restoration/package.json index 025b0225be..21a4fbff8d 100644 --- a/e2e/vue-start/scroll-restoration/package.json +++ b/e2e/vue-start/scroll-restoration/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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -28,7 +28,7 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/vue-start/scroll-restoration/playwright.config.ts b/e2e/vue-start/scroll-restoration/playwright.config.ts index 1862174905..b0c365f8bd 100644 --- a/e2e/vue-start/scroll-restoration/playwright.config.ts +++ b/e2e/vue-start/scroll-restoration/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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}` /** @@ -13,19 +18,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: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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/utils/posts.tsx b/e2e/vue-start/scroll-restoration/src/utils/posts.tsx index c4a2d0dcca..e45ef52969 100644 --- a/e2e/vue-start/scroll-restoration/src/utils/posts.tsx +++ b/e2e/vue-start/scroll-restoration/src/utils/posts.tsx @@ -10,7 +10,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +let queryURL = 'https://jsonplaceholder.typicode.com' + +if (import.meta.env.VITE_NODE_ENV === 'test') { + queryURL = `http://localhost:${import.meta.env.VITE_EXTERNAL_PORT}` +} 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 7ba645b383..46be4b1580 100644 --- a/e2e/vue-start/scroll-restoration/src/utils/users.tsx +++ b/e2e/vue-start/scroll-restoration/src/utils/users.tsx @@ -3,3 +3,7 @@ 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 deleted file mode 100644 index df75cba73c..0000000000 --- a/e2e/vue-start/scroll-restoration/tests/scroll-restoration-lifecycle.spec.ts +++ /dev/null @@ -1,4 +0,0 @@ -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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-start/scroll-restoration/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/scroll-restoration/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 b555a01c26..7ffcaae743 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -22,7 +22,7 @@ "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/vue-start/selective-ssr/playwright.config.ts b/e2e/vue-start/selective-ssr/playwright.config.ts index 630989e41f..badd6db0eb 100644 --- a/e2e/vue-start/selective-ssr/playwright.config.ts +++ b/e2e/vue-start/selective-ssr/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/serialization-adapters/package.json b/e2e/vue-start/serialization-adapters/package.json index a056e21da3..c5b80bdced 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -23,7 +23,7 @@ "@tanstack/router-e2e-utils": "workspace:^", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/vue-start/serialization-adapters/playwright.config.ts b/e2e/vue-start/serialization-adapters/playwright.config.ts index 630989e41f..badd6db0eb 100644 --- a/e2e/vue-start/serialization-adapters/playwright.config.ts +++ b/e2e/vue-start/serialization-adapters/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/server-functions/package.json b/e2e/vue-start/server-functions/package.json index dd1a7a9c6b..3bf9ba33a8 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-query": "^5.90.9", @@ -32,7 +32,7 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/vue-start/server-functions/playwright.config.ts b/e2e/vue-start/server-functions/playwright.config.ts index 48e14683f4..cb1da03b94 100644 --- a/e2e/vue-start/server-functions/playwright.config.ts +++ b/e2e/vue-start/server-functions/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -export const PORT = Number(process.env.E2E_APP_PORT ?? 0) +export const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/server-routes/package.json b/e2e/vue-start/server-routes/package.json index 6a8e1babed..40d285d1d9 100644 --- a/e2e/vue-start/server-routes/package.json +++ b/e2e/vue-start/server-routes/package.json @@ -32,7 +32,7 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/vue-start/server-routes/playwright.config.ts b/e2e/vue-start/server-routes/playwright.config.ts index 48e14683f4..cb1da03b94 100644 --- a/e2e/vue-start/server-routes/playwright.config.ts +++ b/e2e/vue-start/server-routes/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -export const PORT = Number(process.env.E2E_APP_PORT ?? 0) +export const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/spa-mode/package.json b/e2e/vue-start/spa-mode/package.json index c4270cfccd..b33ed9c859 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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", diff --git a/e2e/vue-start/spa-mode/playwright.config.ts b/e2e/vue-start/spa-mode/playwright.config.ts index 630989e41f..badd6db0eb 100644 --- a/e2e/vue-start/spa-mode/playwright.config.ts +++ b/e2e/vue-start/spa-mode/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** * See https://playwright.dev/docs/test-configuration. @@ -19,8 +20,8 @@ export default defineConfig({ webServer: { command: `VITE_SERVER_PORT=${PORT} pnpm build && NODE_ENV=production PORT=${PORT} VITE_SERVER_PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/e2e/vue-start/start-manifest/package.json b/e2e/vue-start/start-manifest/package.json index ae682f7a9d..dbf889db71 100644 --- a/e2e/vue-start/start-manifest/package.json +++ b/e2e/vue-start/start-manifest/package.json @@ -19,7 +19,7 @@ "@tanstack/router-e2e-utils": "workspace:^", "@types/node": "^22.10.2", "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14" diff --git a/e2e/vue-start/start-manifest/playwright.config.ts b/e2e/vue-start/start-manifest/playwright.config.ts index 653e08253f..b9f835c16a 100644 --- a/e2e/vue-start/start-manifest/playwright.config.ts +++ b/e2e/vue-start/start-manifest/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` export default defineConfig({ @@ -15,8 +16,8 @@ export default defineConfig({ webServer: { command: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, 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 4d5bea0a33..6c0f0d15ab 100644 --- a/e2e/vue-start/start-manifest/tests/start-manifest.spec.ts +++ b/e2e/vue-start/start-manifest/tests/start-manifest.spec.ts @@ -372,19 +372,24 @@ test('shared widget CSS stays applied when navigating from static to lazy route' const widget = page.getByTestId('shared-widget') await expect(widget).toBeVisible() - await expect(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + expect(await getBackgroundColor('shared-widget', page)).toBe(SHARED_WIDGET_BG) + expect( + await widget.evaluate( + (element) => getComputedStyle(element).borderTopColor, + ), + ).toBe(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(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) }) test('shared widget CSS stays applied when navigating from lazy to static route', async ({ @@ -394,19 +399,27 @@ 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() - 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 expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) 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(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + 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) }) test('shared widget CSS is applied on direct navigation to lazy route', async ({ @@ -418,8 +431,17 @@ 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(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + + 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) }) test('shared widget CSS persists after navigating away from lazy and back', async ({ @@ -429,21 +451,19 @@ 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('lazy-css-lazy-heading')).toBeVisible() - await expect(widget).toBeVisible() + await expect(page.getByTestId('shared-widget')).toBeVisible() await page.getByTestId('nav-home').click() - await page.waitForURL((url) => url.pathname === '/') - await expect(page.getByTestId('home-copy')).toBeVisible() + await page.waitForURL(/\/([^/]*)(\/)?($|\?)/) 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(widget).toHaveCSS('background-color', SHARED_WIDGET_BG) - await expect(widget).toHaveCSS('border-top-color', SHARED_WIDGET_BORDER) + await expect + .poll(() => getBackgroundColor('shared-widget', page), { + timeout: 5_000, + }) + .toBe(SHARED_WIDGET_BG) }) diff --git a/e2e/vue-start/streaming-ssr/package.json b/e2e/vue-start/streaming-ssr/package.json deleted file mode 100644 index 382120860a..0000000000 --- a/e2e/vue-start/streaming-ssr/package.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "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 deleted file mode 100644 index c2f3b67a0c..0000000000 --- a/e2e/vue-start/streaming-ssr/playwright.config.ts +++ /dev/null @@ -1,39 +0,0 @@ -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 deleted file mode 100644 index ac4c9ab156..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routeTree.gen.ts +++ /dev/null @@ -1,282 +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 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 deleted file mode 100644 index 257eb8dac9..0000000000 --- a/e2e/vue-start/streaming-ssr/src/router.tsx +++ /dev/null @@ -1,18 +0,0 @@ -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 deleted file mode 100644 index d3b3339720..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/__root.tsx +++ /dev/null @@ -1,103 +0,0 @@ -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 deleted file mode 100644 index 5fed8ab517..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/concurrent.tsx +++ /dev/null @@ -1,54 +0,0 @@ -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 deleted file mode 100644 index 5018f9e07c..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/deferred-rejection.tsx +++ /dev/null @@ -1,49 +0,0 @@ -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 deleted file mode 100644 index 6a8affe1b4..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/deferred.tsx +++ /dev/null @@ -1,100 +0,0 @@ -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 deleted file mode 100644 index ac004b041c..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/fast-serial.tsx +++ /dev/null @@ -1,49 +0,0 @@ -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 deleted file mode 100644 index 0350eb5d4a..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/index.tsx +++ /dev/null @@ -1,58 +0,0 @@ -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 deleted file mode 100644 index 4361696107..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/many-promises.tsx +++ /dev/null @@ -1,94 +0,0 @@ -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 deleted file mode 100644 index b24336ec40..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/nested-deferred.tsx +++ /dev/null @@ -1,143 +0,0 @@ -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 deleted file mode 100644 index b22154b78e..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/query-heavy.tsx +++ /dev/null @@ -1,168 +0,0 @@ -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 deleted file mode 100644 index f897e03ff0..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/slow-render.tsx +++ /dev/null @@ -1,77 +0,0 @@ -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 deleted file mode 100644 index 31368bedfc..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/stream.tsx +++ /dev/null @@ -1,171 +0,0 @@ -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 deleted file mode 100644 index bbad10839e..0000000000 --- a/e2e/vue-start/streaming-ssr/src/routes/sync-only.tsx +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index 8b9b3a8dcc..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/client-navigation.spec.ts +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index 8625473a58..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/concurrent.spec.ts +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index 355b5019bc..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/deferred-rejection.spec.ts +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index 3145897d7b..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/deferred.spec.ts +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index 95df0555e2..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/fast-serial.spec.ts +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index 5d49d34a56..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/home.spec.ts +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index b747bd7d0a..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/many-promises.spec.ts +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index 8df20a8a95..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/nested-deferred.spec.ts +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index 34241cfbaa..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/preview-streaming.spec.ts +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index d15c092f6e..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/query-heavy.spec.ts +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index 0d5a87363f..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/slow-render.spec.ts +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index 9dfc6820ad..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/stream.spec.ts +++ /dev/null @@ -1,22 +0,0 @@ -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 deleted file mode 100644 index b25572f615..0000000000 --- a/e2e/vue-start/streaming-ssr/tests/sync-only.spec.ts +++ /dev/null @@ -1,7 +0,0 @@ -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 deleted file mode 100644 index 390dad84c0..0000000000 --- a/e2e/vue-start/streaming-ssr/tsconfig.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "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 deleted file mode 100644 index 6519ec54c8..0000000000 --- a/e2e/vue-start/streaming-ssr/vite.config.ts +++ /dev/null @@ -1,10 +0,0 @@ -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 90f09ce911..3697e87e52 100644 --- a/e2e/vue-start/virtual-routes/package.json +++ b/e2e/vue-start/virtual-routes/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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/virtual-file-routes": "workspace:^", @@ -29,7 +29,7 @@ "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", "combinate": "^1.1.11", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/vue-start/virtual-routes/playwright.config.ts b/e2e/vue-start/virtual-routes/playwright.config.ts index 1862174905..b0c365f8bd 100644 --- a/e2e/vue-start/virtual-routes/playwright.config.ts +++ b/e2e/vue-start/virtual-routes/playwright.config.ts @@ -1,7 +1,12 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { + getDummyServerPort, + getTestServerPort, +} from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -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}` /** @@ -13,19 +18,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: `pnpm build && PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + 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, 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 f7a1941605..1b4c92b41d 100644 --- a/e2e/vue-start/virtual-routes/src/posts.tsx +++ b/e2e/vue-start/virtual-routes/src/posts.tsx @@ -7,7 +7,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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 = async (postId: string) => { console.info(`Fetching post with id ${postId}...`) diff --git a/e2e/vue-start/virtual-routes/src/utils/posts.tsx b/e2e/vue-start/virtual-routes/src/utils/posts.tsx index 11d80d08b5..66cb298f83 100644 --- a/e2e/vue-start/virtual-routes/src/utils/posts.tsx +++ b/e2e/vue-start/virtual-routes/src/utils/posts.tsx @@ -8,7 +8,11 @@ export type PostType = { body: string } -const queryURL = 'https://jsonplaceholder.typicode.com' +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) diff --git a/e2e/vue-start/virtual-routes/src/utils/users.tsx b/e2e/vue-start/virtual-routes/src/utils/users.tsx index 7ba645b383..46be4b1580 100644 --- a/e2e/vue-start/virtual-routes/src/utils/users.tsx +++ b/e2e/vue-start/virtual-routes/src/utils/users.tsx @@ -3,3 +3,7 @@ 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 e9db98e3f3..3182febfa0 100644 --- a/e2e/vue-start/virtual-routes/tests/app.spec.ts +++ b/e2e/vue-start/virtual-routes/tests/app.spec.ts @@ -1,5 +1,4 @@ -import { expect } from '@playwright/test' -import { apiTest as test } from '@tanstack/router-e2e-utils' +import { expect, test } from '@playwright/test' 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 new file mode 100644 index 0000000000..3593d10ab9 --- /dev/null +++ b/e2e/vue-start/virtual-routes/tests/setup/global.setup.ts @@ -0,0 +1,6 @@ +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 new file mode 100644 index 0000000000..62fd79911c --- /dev/null +++ b/e2e/vue-start/virtual-routes/tests/setup/global.teardown.ts @@ -0,0 +1,6 @@ +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 6c30b1500f..5e92c93769 100644 --- a/e2e/vue-start/website/package.json +++ b/e2e/vue-start/website/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": "playwright test --project=chromium" + "test:e2e": "rm -rf port*.txt; playwright test --project=chromium" }, "dependencies": { "@tanstack/vue-router": "workspace:^", @@ -27,7 +27,7 @@ "@types/node": "^22.10.2", "@vitejs/plugin-vue": "^6.0.5", "@vitejs/plugin-vue-jsx": "^5.1.5", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/e2e/vue-start/website/playwright.config.ts b/e2e/vue-start/website/playwright.config.ts index e6b92ce385..f6dd61ba6c 100644 --- a/e2e/vue-start/website/playwright.config.ts +++ b/e2e/vue-start/website/playwright.config.ts @@ -1,7 +1,8 @@ import { defineConfig, devices } from '@playwright/test' -import { appServerReady } from '@tanstack/router-e2e-utils' +import { getTestServerPort } from '@tanstack/router-e2e-utils' +import packageJson from './package.json' with { type: 'json' } -const PORT = Number(process.env.E2E_APP_PORT ?? 0) +const PORT = await getTestServerPort(packageJson.name) const baseURL = `http://localhost:${PORT}` /** @@ -20,8 +21,8 @@ export default defineConfig({ webServer: { command: `pnpm build && VITE_SERVER_PORT=${PORT} PORT=${PORT} pnpm start`, - wait: appServerReady, - reuseExistingServer: false, + url: baseURL, + reuseExistingServer: !process.env.CI, stdout: 'pipe', }, diff --git a/examples/AGENTS.md b/examples/AGENTS.md deleted file mode 100644 index eb47fbd925..0000000000 --- a/examples/AGENTS.md +++ /dev/null @@ -1,4 +0,0 @@ -# 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 1efa172047..8c117f0692 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.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.37", "firebase": "^11.4.0", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/authenticated-routes/package.json b/examples/react/authenticated-routes/package.json index 6af48f1d34..fe774daf2e 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.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.37", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/basic-default-search-params/package.json b/examples/react/basic-default-search-params/package.json index 96c68fecd4..3221a1f185 100644 --- a/examples/react/basic-default-search-params/package.json +++ b/examples/react/basic-default-search-params/package.json @@ -11,8 +11,8 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/basic-devtools-panel/package.json b/examples/react/basic-devtools-panel/package.json index ccae95d73f..c91dbd3c07 100644 --- a/examples/react/basic-devtools-panel/package.json +++ b/examples/react/basic-devtools-panel/package.json @@ -12,8 +12,8 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.67.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/basic-file-based/package.json b/examples/react/basic-file-based/package.json index 9c3cacada1..50e23b461c 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.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.37", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/basic-non-nested-devtools/package.json b/examples/react/basic-non-nested-devtools/package.json index 32e856ebcf..283d0dcb14 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.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/basic-react-query-file-based/package.json b/examples/react/basic-react-query-file-based/package.json index d01a02872e..3d1a59a030 100644 --- a/examples/react/basic-react-query-file-based/package.json +++ b/examples/react/basic-react-query-file-based/package.json @@ -12,9 +12,9 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.37", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/basic-react-query/package.json b/examples/react/basic-react-query/package.json index edab96afac..48b8b0c186 100644 --- a/examples/react/basic-react-query/package.json +++ b/examples/react/basic-react-query/package.json @@ -12,8 +12,8 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/basic-ssr-file-based/package.json b/examples/react/basic-ssr-file-based/package.json index 3222c33e19..d3b3a4beab 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.46", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.35", + "@tanstack/router-plugin": "^1.168.37", "compression": "^1.8.0", "express": "^5.2.1", "get-port": "^7.1.0", @@ -21,7 +21,7 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router-devtools": "^1.167.1", "@types/express": "^5.0.6", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.1", diff --git a/examples/react/basic-ssr-streaming-file-based/package.json b/examples/react/basic-ssr-streaming-file-based/package.json index c3c87c8d88..a79bbe88b3 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.46", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.35", + "@tanstack/router-plugin": "^1.168.37", "compression": "^1.8.0", "express": "^5.2.1", "get-port": "^7.1.0", @@ -21,7 +21,7 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router-devtools": "^1.167.1", "@types/express": "^5.0.6", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.1", diff --git a/examples/react/basic-virtual-file-based/package.json b/examples/react/basic-virtual-file-based/package.json index 84d326435c..03cafd37a3 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.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.37", "@tanstack/virtual-file-routes": "^1.162.0", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/basic-virtual-inside-file-based/package.json b/examples/react/basic-virtual-inside-file-based/package.json index c04cb6012e..ddc71963ab 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.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.37", "@tanstack/virtual-file-routes": "^1.162.0", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/basic/package.json b/examples/react/basic/package.json index 2c09a3dfdf..9938d4400b 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.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/deferred-data/package.json b/examples/react/deferred-data/package.json index 99afb661ee..0e43adba25 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.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/i18n-paraglide/package.json b/examples/react/i18n-paraglide/package.json index 88140e8911..857e2b598f 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.46", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.35", + "@tanstack/router-plugin": "^1.168.37", "react": "^19.1.1", "react-dom": "^19.1.1", "tailwindcss": "^4.2.2" @@ -26,16 +26,5 @@ "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/kitchen-sink-file-based/package.json b/examples/react/kitchen-sink-file-based/package.json index e02defb3ce..221d97cf44 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.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.37", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", 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 e3dd032ac2..012bc20c5c 100644 --- a/examples/react/kitchen-sink-react-query-file-based/package.json +++ b/examples/react/kitchen-sink-react-query-file-based/package.json @@ -12,9 +12,9 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.37", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/kitchen-sink-react-query/package.json b/examples/react/kitchen-sink-react-query/package.json index 14d0dc8e86..19bd29a6f7 100644 --- a/examples/react/kitchen-sink-react-query/package.json +++ b/examples/react/kitchen-sink-react-query/package.json @@ -12,8 +12,8 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/kitchen-sink/package.json b/examples/react/kitchen-sink/package.json index f738efc37e..6bb895d361 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.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", "immer": "^10.1.1", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/large-file-based/package.json b/examples/react/large-file-based/package.json index 23d469d120..0da9f08318 100644 --- a/examples/react/large-file-based/package.json +++ b/examples/react/large-file-based/package.json @@ -13,9 +13,9 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@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/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.37", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/location-masking/package.json b/examples/react/location-masking/package.json index fe005c0d2f..e6144131f0 100644 --- a/examples/react/location-masking/package.json +++ b/examples/react/location-masking/package.json @@ -12,8 +12,8 @@ "@radix-ui/react-dialog": "^1.1.6", "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/navigation-blocking/package.json b/examples/react/navigation-blocking/package.json index a7677dfd51..e5c4ff09d0 100644 --- a/examples/react/navigation-blocking/package.json +++ b/examples/react/navigation-blocking/package.json @@ -11,8 +11,8 @@ "dependencies": { "@tailwindcss/vite": "^4.2.2", "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/quickstart-esbuild-file-based/esbuild.config.js b/examples/react/quickstart-esbuild-file-based/esbuild.config.js index 2f83a79984..fb7950d1fa 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' })], + plugins: [tanstackRouter({ target: 'react', autoCodeSplitting: true })], } diff --git a/examples/react/quickstart-esbuild-file-based/package.json b/examples/react/quickstart-esbuild-file-based/package.json index d855694fec..829ce87bb6 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.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.37", "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 976ec838d1..abe05c4172 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.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.37", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/quickstart-rspack-file-based/package.json b/examples/react/quickstart-rspack-file-based/package.json index 824998f428..a36d234608 100644 --- a/examples/react/quickstart-rspack-file-based/package.json +++ b/examples/react/quickstart-rspack-file-based/package.json @@ -9,17 +9,17 @@ }, "dependencies": { "@tailwindcss/postcss": "^4.2.2", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", "postcss": "^8.5.1", "react": "^19.0.0", "react-dom": "^19.0.0", "tailwindcss": "^4.2.2" }, "devDependencies": { - "@rsbuild/core": "^2.3.1", + "@rsbuild/core": "^2.1.0", "@rsbuild/plugin-react": "^2.0.0", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/router-plugin": "^1.168.37", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@typescript/native": "npm:typescript@^7.0.2", diff --git a/examples/react/quickstart-webpack-file-based/package.json b/examples/react/quickstart-webpack-file-based/package.json index baa14b89dd..fae05b7955 100644 --- a/examples/react/quickstart-webpack-file-based/package.json +++ b/examples/react/quickstart-webpack-file-based/package.json @@ -7,14 +7,14 @@ "build": "webpack build && tsc --noEmit" }, "dependencies": { - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", "react": "^19.0.0", "react-dom": "^19.0.0" }, "devDependencies": { "@swc/core": "^1.15.33", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/router-plugin": "^1.168.37", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "html-webpack-plugin": "^5.6.3", diff --git a/examples/react/quickstart/package.json b/examples/react/quickstart/package.json index b6db476ea8..d8f7a64c2a 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.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", "react": "^19.0.0", "react-dom": "^19.0.0", "tailwindcss": "^4.2.2" diff --git a/examples/react/router-monorepo-react-query/package.json b/examples/react/router-monorepo-react-query/package.json index b158eeda56..7bac03d213 100644 --- a/examples/react/router-monorepo-react-query/package.json +++ b/examples/react/router-monorepo-react-query/package.json @@ -12,9 +12,9 @@ "dependencies": { "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.37", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" 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 f0994165c2..cbbf07dac5 100644 --- a/examples/react/router-monorepo-react-query/packages/app/package.json +++ b/examples/react/router-monorepo-react-query/packages/app/package.json @@ -16,7 +16,7 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router-devtools": "^1.167.1", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", @@ -33,12 +33,6 @@ "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 196cb055a9..ce3a7d2339 100644 --- a/examples/react/router-monorepo-react-query/packages/app/tsconfig.json +++ b/examples/react/router-monorepo-react-query/packages/app/tsconfig.json @@ -8,6 +8,5 @@ "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], "skipLibCheck": true - }, - "exclude": ["node_modules", "dist"] + } } 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 1397db14b5..144140d0f1 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.5", + "@tanstack/history": "^1.162.3", "@tanstack/react-query": "^5.102.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.35", + "@tanstack/router-plugin": "^1.168.37", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/router-monorepo-simple-lazy/package.json b/examples/react/router-monorepo-simple-lazy/package.json index e044d86681..07e1b19351 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.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.37", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" 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 cfc7a94942..a1e792cc3d 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/app/package.json +++ b/examples/react/router-monorepo-simple-lazy/packages/app/package.json @@ -15,7 +15,7 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router-devtools": "^1.167.1", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", @@ -32,12 +32,6 @@ "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 196cb055a9..ce3a7d2339 100644 --- a/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json +++ b/examples/react/router-monorepo-simple-lazy/packages/app/tsconfig.json @@ -8,6 +8,5 @@ "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], "skipLibCheck": true - }, - "exclude": ["node_modules", "dist"] + } } 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 afd4702b5d..29d2b39cb3 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.5", - "@tanstack/react-router": "^1.170.46", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/history": "^1.162.3", + "@tanstack/react-router": "^1.170.35", + "@tanstack/router-plugin": "^1.168.37", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/router-monorepo-simple/package.json b/examples/react/router-monorepo-simple/package.json index 800d948c81..b0d629e142 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.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.37", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1" diff --git a/examples/react/router-monorepo-simple/packages/app/package.json b/examples/react/router-monorepo-simple/packages/app/package.json index a06431ef86..01da864c38 100644 --- a/examples/react/router-monorepo-simple/packages/app/package.json +++ b/examples/react/router-monorepo-simple/packages/app/package.json @@ -15,7 +15,7 @@ "react-dom": "^19.0.0" }, "devDependencies": { - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router-devtools": "^1.167.1", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", @@ -32,12 +32,6 @@ "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 196cb055a9..ce3a7d2339 100644 --- a/examples/react/router-monorepo-simple/packages/app/tsconfig.json +++ b/examples/react/router-monorepo-simple/packages/app/tsconfig.json @@ -8,6 +8,5 @@ "module": "ESNext", "lib": ["DOM", "DOM.Iterable", "ES2022"], "skipLibCheck": true - }, - "exclude": ["node_modules", "dist"] + } } diff --git a/examples/react/router-monorepo-simple/packages/router/package.json b/examples/react/router-monorepo-simple/packages/router/package.json index 391b72e610..ec94aa87d6 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.5", - "@tanstack/react-router": "^1.170.46", - "@tanstack/router-plugin": "^1.169.0", + "@tanstack/history": "^1.162.3", + "@tanstack/react-router": "^1.170.35", + "@tanstack/router-plugin": "^1.168.37", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/scroll-restoration/package.json b/examples/react/scroll-restoration/package.json index 704ff13838..8141904381 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.46", - "@tanstack/react-router-devtools": "^1.167.3", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", "@tanstack/react-virtual": "^3.13.0", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/search-validator-adapters/package.json b/examples/react/search-validator-adapters/package.json index 35e041e825..f301a0a7e2 100644 --- a/examples/react/search-validator-adapters/package.json +++ b/examples/react/search-validator-adapters/package.json @@ -13,9 +13,9 @@ "@tailwindcss/vite": "^4.2.2", "@tanstack/arktype-adapter": "^1.167.0", "@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/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/router-plugin": "^1.168.37", "@tanstack/valibot-adapter": "^1.167.0", "@tanstack/zod-adapter": "^1.167.0", "arktype": "^2.1.7", @@ -26,7 +26,7 @@ "zod": "^3.24.2" }, "devDependencies": { - "@testing-library/jest-dom": "^7.0.1", + "@testing-library/jest-dom": "^6.6.3", "@testing-library/react": "^16.2.0", "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", @@ -35,6 +35,6 @@ "jsdom": "^27.0.0", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", - "vitest": "^5.0.4" + "vitest": "^4.1.4" } } diff --git a/examples/react/search-validator-adapters/tests/arktype.test.tsx b/examples/react/search-validator-adapters/tests/arktype.test.tsx index 776cc8369e..1c3a1baf76 100644 --- a/examples/react/search-validator-adapters/tests/arktype.test.tsx +++ b/examples/react/search-validator-adapters/tests/arktype.test.tsx @@ -8,6 +8,7 @@ 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 deleted file mode 100644 index 8f7cbf15be..0000000000 --- a/examples/react/search-validator-adapters/tests/jest-dom.setup.ts +++ /dev/null @@ -1,18 +0,0 @@ -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 d3e18db414..3680d2302c 100644 --- a/examples/react/search-validator-adapters/tests/valibot.test.tsx +++ b/examples/react/search-validator-adapters/tests/valibot.test.tsx @@ -8,6 +8,7 @@ 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 e4b93f5cc3..5b41e6e26b 100644 --- a/examples/react/search-validator-adapters/vite.config.ts +++ b/examples/react/search-validator-adapters/vite.config.ts @@ -11,7 +11,6 @@ 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 4ab9aff272..3a279b9547 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.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.52", "react": "^19.0.0", "react-dom": "^19.0.0", "zod": "^4.4.3" diff --git a/examples/react/start-basic-auth/README.md b/examples/react/start-basic-auth/README.md index 7f1b093ba5..4e5ee29b40 100644 --- a/examples/react/start-basic-auth/README.md +++ b/examples/react/start-basic-auth/README.md @@ -39,13 +39,3 @@ 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 9ab89bdac9..4390a35207 100644 --- a/examples/react/start-basic-auth/package.json +++ b/examples/react/start-basic-auth/package.json @@ -14,10 +14,9 @@ "@libsql/client": "^0.15.15", "@prisma/adapter-libsql": "^7.0.0", "@prisma/client": "^7.0.0", - "@tanstack/react-router": "^1.170.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", - "iron-session": "^9.0.1", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.52", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/start-basic-auth/src/routes/__root.tsx b/examples/react/start-basic-auth/src/routes/__root.tsx index 3367c62f27..5728345fcf 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 { getAppSession } from '~/utils/session.js' +import { useAppSession } 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 getAppSession() + const session = await useAppSession() - if (!session.userEmail) { + if (!session.data.userEmail) { return null } return { - email: session.userEmail, + email: session.data.userEmail, } }) diff --git a/examples/react/start-basic-auth/src/routes/_authed.tsx b/examples/react/start-basic-auth/src/routes/_authed.tsx index 0b5c6f9047..3af371e844 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 { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const loginFn = createServerFn({ method: 'POST' }) .validator((d: { email: string; password: string }) => d) @@ -33,10 +33,13 @@ export const loginFn = createServerFn({ method: 'POST' }) } } + // Create a session + const session = await useAppSession() + // Store the user's email in the session - const session = await getAppSession() - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) }) export const Route = createFileRoute('/_authed')({ diff --git a/examples/react/start-basic-auth/src/routes/logout.tsx b/examples/react/start-basic-auth/src/routes/logout.tsx index 73cdaf1600..28f3c9f8fe 100644 --- a/examples/react/start-basic-auth/src/routes/logout.tsx +++ b/examples/react/start-basic-auth/src/routes/logout.tsx @@ -1,10 +1,11 @@ import { redirect, createFileRoute } from '@tanstack/react-router' import { createServerFn } from '@tanstack/react-start' -import { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' const logoutFn = createServerFn().handler(async () => { - const session = await getAppSession() - session.destroy() + const session = await useAppSession() + + session.clear() 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 4dc8e350ac..247a94c03c 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 { getAppSession } from '~/utils/session' +import { useAppSession } from '~/utils/session' export const signupFn = createServerFn({ method: 'POST' }) .validator( @@ -20,6 +20,9 @@ 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 { @@ -30,9 +33,9 @@ export const signupFn = createServerFn({ method: 'POST' }) } // Store the user's email in the session - const session = await getAppSession() - session.userEmail = found.email - await session.save() + await session.update({ + userEmail: found.email, + }) // Redirect to the prev page stored in the "redirect" search param throw redirect({ @@ -49,9 +52,9 @@ export const signupFn = createServerFn({ method: 'POST' }) }) // Store the user's email in the session - const session = await getAppSession() - session.userEmail = user.email - await session.save() + await session.update({ + userEmail: user.email, + }) // 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 7df7bc4da2..c38bac1e48 100644 --- a/examples/react/start-basic-auth/src/utils/session.ts +++ b/examples/react/start-basic-auth/src/utils/session.ts @@ -1,29 +1,13 @@ -import { getIronSession } from 'iron-session' -import { getCookie, setCookie } from '@tanstack/react-start/server' +// src/services/session.server.ts +import { useSession } from '@tanstack/react-start/server' import type { User } from '@prisma/client' type SessionUser = { userEmail: User['email'] } -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: '/', - }, - }, - ) +export function useAppSession() { + return useSession({ + password: 'ChangeThisBeforeShippingToProdOrYouWillBeFired', + }) } diff --git a/examples/react/start-basic-authjs/package.json b/examples/react/start-basic-authjs/package.json index e9fa789ea6..6d773c3e0a 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.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.52", "react": "^19.0.0", "react-dom": "^19.0.0", "start-authjs": "^1.0.0", diff --git a/examples/react/start-basic-cloudflare/package.json b/examples/react/start-basic-cloudflare/package.json index 2108922446..b47789c61a 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.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.52", "react": "^19.0.0", "react-dom": "^19.0.0" }, diff --git a/examples/react/start-basic-react-query/package.json b/examples/react/start-basic-react-query/package.json index 9d819d4390..bed46f2c3b 100644 --- a/examples/react/start-basic-react-query/package.json +++ b/examples/react/start-basic-react-query/package.json @@ -13,10 +13,10 @@ "dependencies": { "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@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/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-router-ssr-query": "^1.167.2", + "@tanstack/react-start": "^1.168.52", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/start-basic-rsbuild/package.json b/examples/react/start-basic-rsbuild/package.json index bea4ba26ef..d2dbce7fb6 100644 --- a/examples/react/start-basic-rsbuild/package.json +++ b/examples/react/start-basic-rsbuild/package.json @@ -10,22 +10,22 @@ "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", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.52", "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/core": "^2.0.11", "@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", + "srvx": "^0.11.18", "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-static/package.json b/examples/react/start-basic-static/package.json index 58d573ca36..c65664e078 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.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", - "@tanstack/start-static-server-functions": "^1.167.44", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.52", + "@tanstack/start-static-server-functions": "^1.167.34", "@vitejs/plugin-react": "^6.0.1", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/examples/react/start-basic/package.json b/examples/react/start-basic/package.json index 46df8e4650..5cf41bc904 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.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.52", "react": "^19.0.0", "react-dom": "^19.0.0", "tailwind-merge": "^3.6.0", @@ -24,7 +24,7 @@ "@types/react": "^19.0.8", "@types/react-dom": "^19.0.3", "@vitejs/plugin-react": "^6.0.1", - "nitro": "^3.0.260903-beta", + "nitro": "^3.0.260311-beta", "tailwindcss": "^4.2.2", "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", diff --git a/examples/react/start-bun/package.json b/examples/react/start-bun/package.json index 24f7113912..96ad7192b2 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.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", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-router-ssr-query": "^1.167.2", + "@tanstack/react-start": "^1.168.52", + "@tanstack/router-plugin": "^1.168.37", "react": "^19.1.1", "react-dom": "^19.1.1", "tailwindcss": "^4.2.2" @@ -38,7 +38,7 @@ "@typescript/native": "npm:typescript@^7.0.2", "typescript": "npm:@typescript/typescript6@^6.0.2", "vite": "^8.0.14", - "vitest": "^5.0.4", + "vitest": "^4.1.4", "web-vitals": "^5.1.0" } } diff --git a/examples/react/start-clerk-basic/package.json b/examples/react/start-clerk-basic/package.json index 022300e159..ed37e68dbb 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.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.52", "@vitejs/plugin-react": "^6.0.1", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", - "srvx": "^1.0.0", + "srvx": "^0.11.9", "tailwind-merge": "^3.6.0" }, "devDependencies": { diff --git a/examples/react/start-convex-trellaux/package.json b/examples/react/start-convex-trellaux/package.json index 3452f910d0..c0e1828d68 100644 --- a/examples/react/start-convex-trellaux/package.json +++ b/examples/react/start-convex-trellaux/package.json @@ -15,10 +15,10 @@ "@convex-dev/react-query": "0.0.0-alpha.8", "@tanstack/react-query": "^5.102.0", "@tanstack/react-query-devtools": "^5.90.0", - "@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/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-router-ssr-query": "^1.167.2", + "@tanstack/react-start": "^1.168.52", "concurrently": "^8.2.2", "convex": "^1.19.0", "ky": "^1.7.4", diff --git a/examples/react/start-counter/package.json b/examples/react/start-counter/package.json index 8f4673143e..708f027cbb 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.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.52", "react": "^19.0.0", "react-dom": "^19.0.0" }, diff --git a/examples/react/start-i18n-paraglide/package.json b/examples/react/start-i18n-paraglide/package.json index 074f714d5c..12ec13aa97 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.46", - "@tanstack/react-router-devtools": "^1.167.3", - "@tanstack/react-start": "^1.169.6", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.52", "react": "^19.1.1", "react-dom": "^19.1.1" }, @@ -27,16 +27,5 @@ "@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-large/package.json b/examples/react/start-large/package.json index f9f86b81d1..683035eb0e 100644 --- a/examples/react/start-large/package.json +++ b/examples/react/start-large/package.json @@ -13,9 +13,9 @@ }, "dependencies": { "@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", + "@tanstack/react-router": "^1.170.35", + "@tanstack/react-router-devtools": "^1.167.1", + "@tanstack/react-start": "^1.168.52", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/examples/react/start-learn/.env.example b/examples/react/start-learn/.env.example new file mode 100644 index 0000000000..c95fabf1c0 --- /dev/null +++ b/examples/react/start-learn/.env.example @@ -0,0 +1,4 @@ +DATABASE_URL="postgresql://start_demo:start_demo@localhost:5433/learn_start" +AUTH_DATABASE_URL="postgresql://start_demo:start_demo@localhost:5433/learn_start_auth" +BETTER_AUTH_SECRET="" +APP_ORIGIN="http://localhost:3144" diff --git a/examples/react/start-learn/.gitignore b/examples/react/start-learn/.gitignore new file mode 100644 index 0000000000..daeca4bd11 --- /dev/null +++ b/examples/react/start-learn/.gitignore @@ -0,0 +1,9 @@ +node_modules +.env +.output +.tanstack +test-results +playwright-report +**/src/generated/ +.postgres/ +.postgres-password diff --git a/examples/react/start-learn/README.md b/examples/react/start-learn/README.md new file mode 100644 index 0000000000..9d93d0e30d --- /dev/null +++ b/examples/react/start-learn/README.md @@ -0,0 +1,72 @@ +# Learn Start + +Build Field notes through eight independently runnable checkpoints. The [course](https://tanstack.com/start/latest/docs/framework/react/tutorial/learn-start) explains each change, from a single route to an app with accounts and published notes. + +This example lives in the TanStack Router workspace. Follow the repository's [contribution setup](../../../CONTRIBUTING.md) to install dependencies and build the framework packages first. Run the commands below from `examples/react/start-learn`. + +## Start the course + +```sh +pnpm dev +``` + +Open http://localhost:3140. This first checkpoint needs no database or auth secret. + +| Checkpoint | Source root | Port | +| -------------- | ------------------------------- | ---- | +| Setup | `checkpoints/01-setup` | 3140 | +| Routes | `checkpoints/02-routes` | 3141 | +| Data | `checkpoints/03-data` | 3142 | +| Forms | `checkpoints/04-forms` | 3143 | +| Authentication | `checkpoints/05-authentication` | 3144 | +| SEO | `checkpoints/06-seo` | 3145 | +| Deployment | `checkpoints/07-deployment` | 3146 | +| Tests | `checkpoints/08-tests` | 3147 | + +Select another source root with Vite, for example `pnpm exec vite checkpoints/02-routes --port 3141`. Each source root has its own generated route tree and production output. + +## Run the complete app + +Create a PostgreSQL database for the account checkpoints. Copy `.env.example` to `.env`, set `AUTH_DATABASE_URL`, set `APP_ORIGIN` to `http://localhost:3147`, and generate `BETTER_AUTH_SECRET` with `openssl rand -base64 48`. Keep `.env` private. + +```sh +pnpm db:generate:08 +pnpm db:migrate:08 +pnpm db:seed:08 +pnpm exec vite checkpoints/08-tests --port 3147 +``` + +Create an account from **My notes**. New notes are private until their owner publishes them. The seed adds two public sample notes. + +Checkpoints 03 and 04 are anonymous local demos. They use `DATABASE_URL`, which must point to a separate database from `AUTH_DATABASE_URL`. Do not expose that anonymous app to a database containing private notes. Each database chapter documents its own generation, migration, and seed commands. + +## Build and test + +Stop the development server before running Playwright: + +```sh +pnpm exec playwright install chromium +COURSE_CHECKPOINT=08-tests pnpm test:e2e +pnpm build:08 +COURSE_PRODUCTION=1 COURSE_CHECKPOINT=08-tests pnpm test:e2e +``` + +`COURSE_CHECKPOINT` starts only the selected app and runs its matching tests. Without it, tests select `01-setup`. Generate the selected database checkpoint's client before testing. Production tests require its current build. + +The final suite checks account isolation, session renewal and expiry, protected mutations, validation and rollback, server HTML, canonical URLs, sitemap exclusions, readiness, public-asset secrets, and a copied production artifact. The artifact test uses port 3148 and is skipped in development mode. Use disposable test databases; these tests write and clean up their own fixtures. + +To start the final build locally with `.env`: + +```sh +APP_ORIGIN=http://localhost:3147 PORT=3147 node --env-file=.env checkpoints/08-tests/.output/server/index.mjs +``` + +A host that injects environment variables can use `pnpm start:08` from the checkout, or copy the complete `.output` directory and run `node .output/server/index.mjs`. Apply migrations from the source checkout as a release step. + +Local production checks do not verify hosting, DNS, TLS, mail delivery, or a remote deployment. Configure verification, recovery, rate-limit storage, and trusted proxy handling for your public service before opening registration to real users. See the [deployment chapter](https://tanstack.com/start/latest/docs/framework/react/tutorial/learn-start/deployment). + +## SEO example + +Checkpoint 06 adds structured data, a shared PNG social cover, and permanent redirects alongside canonical URLs, sitemap.txt, robots.txt, and publication checks. Checkpoints 07 and 08 keep the same behavior. `pnpm social:image` regenerates the checked-in 1200 by 630 cover from `artwork/notebook.svg` using Sharp. Both artwork formats are MIT-licensed with the repository. The asset is served statically; no image-service account is required. + +The SEO tests run with an HTML-limited crawler, verify the actual PNG dimensions, and check that script-like note text remains data in both server HTML and client navigation. Generic CreativeWork metadata is not a promise of search-engine rich results. diff --git a/examples/react/start-learn/artwork/notebook.svg b/examples/react/start-learn/artwork/notebook.svg new file mode 100644 index 0000000000..4493482412 --- /dev/null +++ b/examples/react/start-learn/artwork/notebook.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/examples/react/start-learn/checkpoints/01-setup/src/routeTree.gen.ts b/examples/react/start-learn/checkpoints/01-setup/src/routeTree.gen.ts new file mode 100644 index 0000000000..dceedffdc1 --- /dev/null +++ b/examples/react/start-learn/checkpoints/01-setup/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/examples/react/start-learn/checkpoints/01-setup/src/router.tsx b/examples/react/start-learn/checkpoints/01-setup/src/router.tsx new file mode 100644 index 0000000000..bb899b1fdf --- /dev/null +++ b/examples/react/start-learn/checkpoints/01-setup/src/router.tsx @@ -0,0 +1,5 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' +export function getRouter() { + return createRouter({ routeTree }) +} diff --git a/examples/react/start-learn/checkpoints/01-setup/src/routes/__root.tsx b/examples/react/start-learn/checkpoints/01-setup/src/routes/__root.tsx new file mode 100644 index 0000000000..35c22bc682 --- /dev/null +++ b/examples/react/start-learn/checkpoints/01-setup/src/routes/__root.tsx @@ -0,0 +1,28 @@ +import { HeadContent, 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: 'Field notes | Learn Start' }, + ], + }), + shellComponent: ({ children }: { children: ReactNode }) => ( + + + + + + {children} + + + + ), + notFoundComponent: () => ( +
+

Note not found

+ All notes +
+ ), +}) diff --git a/examples/react/start-learn/checkpoints/01-setup/src/routes/index.tsx b/examples/react/start-learn/checkpoints/01-setup/src/routes/index.tsx new file mode 100644 index 0000000000..9bce218b85 --- /dev/null +++ b/examples/react/start-learn/checkpoints/01-setup/src/routes/index.tsx @@ -0,0 +1,10 @@ +import { createFileRoute } from '@tanstack/react-router' +export const Route = createFileRoute('/')({ component: Home }) +function Home() { + return ( +
+

Field notes

+

Keep a record of what you learn.

+
+ ) +} diff --git a/examples/react/start-learn/checkpoints/01-setup/tsconfig.json b/examples/react/start-learn/checkpoints/01-setup/tsconfig.json new file mode 100644 index 0000000000..3d61827d71 --- /dev/null +++ b/examples/react/start-learn/checkpoints/01-setup/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["src", "vite.config.ts"] +} diff --git a/e2e/react-start/session-handling/vite.config.ts b/examples/react/start-learn/checkpoints/01-setup/vite.config.ts similarity index 53% rename from e2e/react-start/session-handling/vite.config.ts rename to examples/react/start-learn/checkpoints/01-setup/vite.config.ts index ef9695579b..195c5224e2 100644 --- a/e2e/react-start/session-handling/vite.config.ts +++ b/examples/react/start-learn/checkpoints/01-setup/vite.config.ts @@ -1,13 +1,7 @@ -import { defineConfig } from 'vite' import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import { defineConfig } from 'vite' import viteReact from '@vitejs/plugin-react' - -const outDir = process.env.E2E_DIST_DIR ?? 'dist' - +import { nitro } from 'nitro/vite' export default defineConfig({ - resolve: { tsconfigPaths: true }, - build: { - outDir, - }, - plugins: [tanstackStart(), viteReact()], + plugins: [tanstackStart(), viteReact(), nitro()], }) diff --git a/examples/react/start-learn/checkpoints/02-routes/src/notes.ts b/examples/react/start-learn/checkpoints/02-routes/src/notes.ts new file mode 100644 index 0000000000..11b2e90778 --- /dev/null +++ b/examples/react/start-learn/checkpoints/02-routes/src/notes.ts @@ -0,0 +1,12 @@ +export const notes = [ + { + slug: 'first-route', + title: 'My first route', + body: 'A route connects a URL to the content it displays.', + }, + { + slug: 'server-html', + title: 'Reading server HTML', + body: 'A direct request can contain useful content before JavaScript runs.', + }, +] diff --git a/examples/react/start-learn/checkpoints/02-routes/src/routeTree.gen.ts b/examples/react/start-learn/checkpoints/02-routes/src/routeTree.gen.ts new file mode 100644 index 0000000000..816f25acfb --- /dev/null +++ b/examples/react/start-learn/checkpoints/02-routes/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 NotesSlugRouteImport } from './routes/notes.$slug' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const NotesSlugRoute = NotesSlugRouteImport.update({ + id: '/notes/$slug', + path: '/notes/$slug', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/notes/$slug': typeof NotesSlugRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/notes/$slug': typeof NotesSlugRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/notes/$slug': typeof NotesSlugRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/notes/$slug' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/notes/$slug' + id: '__root__' | '/' | '/notes/$slug' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + NotesSlugRoute: typeof NotesSlugRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/notes/$slug': { + id: '/notes/$slug' + path: '/notes/$slug' + fullPath: '/notes/$slug' + preLoaderRoute: typeof NotesSlugRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + NotesSlugRoute: NotesSlugRoute, +} +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-learn/checkpoints/02-routes/src/router.tsx b/examples/react/start-learn/checkpoints/02-routes/src/router.tsx new file mode 100644 index 0000000000..bb899b1fdf --- /dev/null +++ b/examples/react/start-learn/checkpoints/02-routes/src/router.tsx @@ -0,0 +1,5 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' +export function getRouter() { + return createRouter({ routeTree }) +} diff --git a/examples/react/start-learn/checkpoints/02-routes/src/routes/__root.tsx b/examples/react/start-learn/checkpoints/02-routes/src/routes/__root.tsx new file mode 100644 index 0000000000..35c22bc682 --- /dev/null +++ b/examples/react/start-learn/checkpoints/02-routes/src/routes/__root.tsx @@ -0,0 +1,28 @@ +import { HeadContent, 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: 'Field notes | Learn Start' }, + ], + }), + shellComponent: ({ children }: { children: ReactNode }) => ( + + + + + + {children} + + + + ), + notFoundComponent: () => ( +
+

Note not found

+ All notes +
+ ), +}) diff --git a/examples/react/start-learn/checkpoints/02-routes/src/routes/index.tsx b/examples/react/start-learn/checkpoints/02-routes/src/routes/index.tsx new file mode 100644 index 0000000000..db31c799b6 --- /dev/null +++ b/examples/react/start-learn/checkpoints/02-routes/src/routes/index.tsx @@ -0,0 +1,35 @@ +import { createFileRoute, Link } from '@tanstack/react-router' +import { notes } from '../notes' +export const Route = createFileRoute('/')({ + validateSearch: (search: Record) => ({ + q: typeof search.q === 'string' ? search.q : '', + }), + component: Home, +}) +function Home() { + const { q } = Route.useSearch() + const matches = notes.filter((note) => + note.title.toLowerCase().includes(q.toLowerCase()), + ) + return ( +
+

Field notes

+
+ + +
+
    + {matches.map((note) => ( +
  • + + {note.title} + +
  • + ))} +
+ {matches.length === 0 ?

No matching notes.

: null} +
+ ) +} diff --git a/examples/react/start-learn/checkpoints/02-routes/src/routes/notes.$slug.tsx b/examples/react/start-learn/checkpoints/02-routes/src/routes/notes.$slug.tsx new file mode 100644 index 0000000000..d7b36c8fa0 --- /dev/null +++ b/examples/react/start-learn/checkpoints/02-routes/src/routes/notes.$slug.tsx @@ -0,0 +1,24 @@ +import { createFileRoute, Link, notFound } from '@tanstack/react-router' +import { notes } from '../notes' +export const Route = createFileRoute('/notes/$slug')({ + loader: ({ params }) => { + const note = notes.find((item) => item.slug === params.slug) + if (!note) { + throw notFound() + } + return note + }, + component: Note, +}) +function Note() { + const note = Route.useLoaderData() + return ( +
+ + All notes + +

{note.title}

+

{note.body}

+
+ ) +} diff --git a/examples/react/start-learn/checkpoints/02-routes/tsconfig.json b/examples/react/start-learn/checkpoints/02-routes/tsconfig.json new file mode 100644 index 0000000000..3d61827d71 --- /dev/null +++ b/examples/react/start-learn/checkpoints/02-routes/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["src", "vite.config.ts"] +} diff --git a/examples/react/start-learn/checkpoints/02-routes/vite.config.ts b/examples/react/start-learn/checkpoints/02-routes/vite.config.ts new file mode 100644 index 0000000000..195c5224e2 --- /dev/null +++ b/examples/react/start-learn/checkpoints/02-routes/vite.config.ts @@ -0,0 +1,7 @@ +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import { defineConfig } from 'vite' +import viteReact from '@vitejs/plugin-react' +import { nitro } from 'nitro/vite' +export default defineConfig({ + plugins: [tanstackStart(), viteReact(), nitro()], +}) diff --git a/examples/react/start-learn/checkpoints/03-data/prisma.config.ts b/examples/react/start-learn/checkpoints/03-data/prisma.config.ts new file mode 100644 index 0000000000..0daa8973bf --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/prisma.config.ts @@ -0,0 +1,7 @@ +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' +export default defineConfig({ + schema: './prisma/schema.prisma', + migrations: { path: './prisma/migrations' }, + datasource: { url: env('DATABASE_URL') }, +}) diff --git a/examples/react/start-learn/checkpoints/03-data/prisma/migrations/20260911000000_notes/migration.sql b/examples/react/start-learn/checkpoints/03-data/prisma/migrations/20260911000000_notes/migration.sql new file mode 100644 index 0000000000..52a674f82c --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/prisma/migrations/20260911000000_notes/migration.sql @@ -0,0 +1,12 @@ +CREATE TABLE "Category" ( + "name" TEXT NOT NULL, + CONSTRAINT "Category_pkey" PRIMARY KEY ("name") +); +CREATE TABLE "Note" ( + "slug" TEXT NOT NULL, + "title" TEXT NOT NULL, + "body" TEXT NOT NULL, + "categoryName" TEXT NOT NULL, + CONSTRAINT "Note_pkey" PRIMARY KEY ("slug") +); +ALTER TABLE "Note" ADD CONSTRAINT "Note_categoryName_fkey" FOREIGN KEY ("categoryName") REFERENCES "Category"("name") ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/examples/react/start-learn/checkpoints/03-data/prisma/migrations/migration_lock.toml b/examples/react/start-learn/checkpoints/03-data/prisma/migrations/migration_lock.toml new file mode 100644 index 0000000000..2fe25d87cc --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/prisma/migrations/migration_lock.toml @@ -0,0 +1 @@ +provider = "postgresql" diff --git a/examples/react/start-learn/checkpoints/03-data/prisma/schema.prisma b/examples/react/start-learn/checkpoints/03-data/prisma/schema.prisma new file mode 100644 index 0000000000..fc70787077 --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/prisma/schema.prisma @@ -0,0 +1,18 @@ +generator client { + provider = "prisma-client" + output = "../src/generated/prisma" +} +datasource db { + provider = "postgresql" +} +model Category { + name String @id + notes Note[] +} +model Note { + slug String @id + title String + body String + categoryName String + category Category @relation(fields: [categoryName], references: [name]) +} diff --git a/examples/react/start-learn/checkpoints/03-data/prisma/seed.sql b/examples/react/start-learn/checkpoints/03-data/prisma/seed.sql new file mode 100644 index 0000000000..32401cee94 --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/prisma/seed.sql @@ -0,0 +1,5 @@ +INSERT INTO "Category" ("name") VALUES ('Routing') ON CONFLICT DO NOTHING; +INSERT INTO "Note" ("slug", "title", "body", "categoryName") VALUES +('first-route', 'My first route', 'A route connects a URL to the content it displays.', 'Routing'), +('server-html', 'Reading server HTML', 'A direct request can contain useful content before JavaScript runs.', 'Routing') +ON CONFLICT DO NOTHING; diff --git a/examples/react/start-learn/checkpoints/03-data/src/routeTree.gen.ts b/examples/react/start-learn/checkpoints/03-data/src/routeTree.gen.ts new file mode 100644 index 0000000000..a8c21a8b9e --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/src/routeTree.gen.ts @@ -0,0 +1,87 @@ +/* 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 NotesSlugRouteImport } from './routes/notes.$slug' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const NotesSlugRoute = NotesSlugRouteImport.update({ + id: '/notes/$slug', + path: '/notes/$slug', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/notes/$slug': typeof NotesSlugRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/notes/$slug': typeof NotesSlugRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/notes/$slug': typeof NotesSlugRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/notes/$slug' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/notes/$slug' + id: '__root__' | '/' | '/notes/$slug' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + NotesSlugRoute: typeof NotesSlugRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/notes/$slug': { + id: '/notes/$slug' + path: '/notes/$slug' + fullPath: '/notes/$slug' + preLoaderRoute: typeof NotesSlugRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + NotesSlugRoute: NotesSlugRoute, +} +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-learn/checkpoints/03-data/src/router.tsx b/examples/react/start-learn/checkpoints/03-data/src/router.tsx new file mode 100644 index 0000000000..bb899b1fdf --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/src/router.tsx @@ -0,0 +1,5 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' +export function getRouter() { + return createRouter({ routeTree }) +} diff --git a/examples/react/start-learn/checkpoints/03-data/src/routes/__root.tsx b/examples/react/start-learn/checkpoints/03-data/src/routes/__root.tsx new file mode 100644 index 0000000000..9a21c3c91a --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/src/routes/__root.tsx @@ -0,0 +1,34 @@ +import { HeadContent, 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: 'Field notes | Learn Start' }, + ], + }), + shellComponent: ({ children }: { children: ReactNode }) => ( + + + + + + {children} + + + + ), + errorComponent: () => ( +
+

Could not load notes

+ Try again +
+ ), + notFoundComponent: () => ( +
+

Note not found

+ All notes +
+ ), +}) diff --git a/examples/react/start-learn/checkpoints/03-data/src/routes/index.tsx b/examples/react/start-learn/checkpoints/03-data/src/routes/index.tsx new file mode 100644 index 0000000000..e1e7dba030 --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/src/routes/index.tsx @@ -0,0 +1,36 @@ +import { createFileRoute, Link } from '@tanstack/react-router' +import { z } from 'zod' +import { listNotes } from '../server/notes' +export const Route = createFileRoute('/')({ + validateSearch: z.object({ q: z.string().max(200).catch('') }), + loaderDeps: ({ search }) => ({ q: search.q }), + loader: ({ deps }) => listNotes({ data: deps }), + headers: () => ({ 'Cache-Control': 'no-store' }), + component: Home, +}) +function Home() { + const { q } = Route.useSearch() + const notes = Route.useLoaderData() + return ( +
+

Field notes

+
+ + +
+
    + {notes.map((note) => ( +
  • + + {note.title} + {' '} + ({note.categoryName}) +
  • + ))} +
+ {notes.length === 0 ?

No matching notes.

: null} +
+ ) +} diff --git a/examples/react/start-learn/checkpoints/03-data/src/routes/notes.$slug.tsx b/examples/react/start-learn/checkpoints/03-data/src/routes/notes.$slug.tsx new file mode 100644 index 0000000000..683f524721 --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/src/routes/notes.$slug.tsx @@ -0,0 +1,28 @@ +import { createFileRoute, Link, notFound } from '@tanstack/react-router' +import { getNote } from '../server/notes' +export const Route = createFileRoute('/notes/$slug')({ + loader: async ({ params }) => { + if (params.slug.length > 80) { + throw notFound() + } + const note = await getNote({ data: params.slug }) + if (!note) { + throw notFound() + } + return note + }, + headers: () => ({ 'Cache-Control': 'no-store' }), + component: Note, +}) +function Note() { + const note = Route.useLoaderData() + return ( +
+ + All notes + +

{note.title}

+

{note.body}

+
+ ) +} diff --git a/examples/react/start-learn/checkpoints/03-data/src/server/db.server.ts b/examples/react/start-learn/checkpoints/03-data/src/server/db.server.ts new file mode 100644 index 0000000000..19959c5a2e --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/src/server/db.server.ts @@ -0,0 +1,10 @@ +import '@tanstack/react-start/server-only' +import { PrismaPg } from '@prisma/adapter-pg' +import { PrismaClient } from '../generated/prisma/client' +const connectionString = process.env.DATABASE_URL +if (!connectionString) { + throw new Error('Set DATABASE_URL before starting the server') +} +export const db = new PrismaClient({ + adapter: new PrismaPg({ connectionString, max: 5 }), +}) diff --git a/examples/react/start-learn/checkpoints/03-data/src/server/notes.ts b/examples/react/start-learn/checkpoints/03-data/src/server/notes.ts new file mode 100644 index 0000000000..6ad79632fa --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/src/server/notes.ts @@ -0,0 +1,25 @@ +import { createServerFn } from '@tanstack/react-start' +import { setResponseHeader } from '@tanstack/react-start/server' +import { z } from 'zod' +import { db } from './db.server' + +export const listNotes = createServerFn({ method: 'GET' }) + .validator(z.object({ q: z.string().max(200) })) + .handler(async ({ data }) => { + setResponseHeader('Cache-Control', 'no-store') + return db.note.findMany({ + where: { title: { contains: data.q, mode: 'insensitive' } }, + select: { slug: true, title: true, categoryName: true }, + orderBy: { slug: 'asc' }, + }) + }) + +export const getNote = createServerFn({ method: 'GET' }) + .validator(z.string().min(1).max(80)) + .handler(async ({ data }) => { + setResponseHeader('Cache-Control', 'no-store') + return db.note.findUnique({ + where: { slug: data }, + select: { slug: true, title: true, body: true, categoryName: true }, + }) + }) diff --git a/examples/react/start-learn/checkpoints/03-data/src/start.ts b/examples/react/start-learn/checkpoints/03-data/src/start.ts new file mode 100644 index 0000000000..5fb1e247fb --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/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-learn/checkpoints/03-data/tsconfig.json b/examples/react/start-learn/checkpoints/03-data/tsconfig.json new file mode 100644 index 0000000000..3d61827d71 --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["src", "vite.config.ts"] +} diff --git a/examples/react/start-learn/checkpoints/03-data/vite.config.ts b/examples/react/start-learn/checkpoints/03-data/vite.config.ts new file mode 100644 index 0000000000..e7dc90847a --- /dev/null +++ b/examples/react/start-learn/checkpoints/03-data/vite.config.ts @@ -0,0 +1,8 @@ +import 'dotenv/config' +import { tanstackStart } from '@tanstack/react-start/plugin/vite' +import { defineConfig } from 'vite' +import viteReact from '@vitejs/plugin-react' +import { nitro } from 'nitro/vite' +export default defineConfig({ + plugins: [tanstackStart(), viteReact(), nitro()], +}) diff --git a/examples/react/start-learn/checkpoints/04-forms/prisma.config.ts b/examples/react/start-learn/checkpoints/04-forms/prisma.config.ts new file mode 100644 index 0000000000..0daa8973bf --- /dev/null +++ b/examples/react/start-learn/checkpoints/04-forms/prisma.config.ts @@ -0,0 +1,7 @@ +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' +export default defineConfig({ + schema: './prisma/schema.prisma', + migrations: { path: './prisma/migrations' }, + datasource: { url: env('DATABASE_URL') }, +}) diff --git a/examples/react/start-learn/checkpoints/04-forms/prisma/migrations/20260911000000_notes/migration.sql b/examples/react/start-learn/checkpoints/04-forms/prisma/migrations/20260911000000_notes/migration.sql new file mode 100644 index 0000000000..52a674f82c --- /dev/null +++ b/examples/react/start-learn/checkpoints/04-forms/prisma/migrations/20260911000000_notes/migration.sql @@ -0,0 +1,12 @@ +CREATE TABLE "Category" ( + "name" TEXT NOT NULL, + CONSTRAINT "Category_pkey" PRIMARY KEY ("name") +); +CREATE TABLE "Note" ( + "slug" TEXT NOT NULL, + "title" TEXT NOT NULL, + "body" TEXT NOT NULL, + "categoryName" TEXT NOT NULL, + CONSTRAINT "Note_pkey" PRIMARY KEY ("slug") +); +ALTER TABLE "Note" ADD CONSTRAINT "Note_categoryName_fkey" FOREIGN KEY ("categoryName") REFERENCES "Category"("name") ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/examples/react/start-learn/checkpoints/04-forms/prisma/migrations/migration_lock.toml b/examples/react/start-learn/checkpoints/04-forms/prisma/migrations/migration_lock.toml new file mode 100644 index 0000000000..2fe25d87cc --- /dev/null +++ b/examples/react/start-learn/checkpoints/04-forms/prisma/migrations/migration_lock.toml @@ -0,0 +1 @@ +provider = "postgresql" diff --git a/examples/react/start-learn/checkpoints/04-forms/prisma/schema.prisma b/examples/react/start-learn/checkpoints/04-forms/prisma/schema.prisma new file mode 100644 index 0000000000..fc70787077 --- /dev/null +++ b/examples/react/start-learn/checkpoints/04-forms/prisma/schema.prisma @@ -0,0 +1,18 @@ +generator client { + provider = "prisma-client" + output = "../src/generated/prisma" +} +datasource db { + provider = "postgresql" +} +model Category { + name String @id + notes Note[] +} +model Note { + slug String @id + title String + body String + categoryName String + category Category @relation(fields: [categoryName], references: [name]) +} diff --git a/examples/react/start-learn/checkpoints/04-forms/prisma/seed.sql b/examples/react/start-learn/checkpoints/04-forms/prisma/seed.sql new file mode 100644 index 0000000000..32401cee94 --- /dev/null +++ b/examples/react/start-learn/checkpoints/04-forms/prisma/seed.sql @@ -0,0 +1,5 @@ +INSERT INTO "Category" ("name") VALUES ('Routing') ON CONFLICT DO NOTHING; +INSERT INTO "Note" ("slug", "title", "body", "categoryName") VALUES +('first-route', 'My first route', 'A route connects a URL to the content it displays.', 'Routing'), +('server-html', 'Reading server HTML', 'A direct request can contain useful content before JavaScript runs.', 'Routing') +ON CONFLICT DO NOTHING; diff --git a/examples/react/start-learn/checkpoints/04-forms/src/routeTree.gen.ts b/examples/react/start-learn/checkpoints/04-forms/src/routeTree.gen.ts new file mode 100644 index 0000000000..a8c21a8b9e --- /dev/null +++ b/examples/react/start-learn/checkpoints/04-forms/src/routeTree.gen.ts @@ -0,0 +1,87 @@ +/* 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 NotesSlugRouteImport } from './routes/notes.$slug' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const NotesSlugRoute = NotesSlugRouteImport.update({ + id: '/notes/$slug', + path: '/notes/$slug', + getParentRoute: () => rootRouteImport, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/notes/$slug': typeof NotesSlugRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/notes/$slug': typeof NotesSlugRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/notes/$slug': typeof NotesSlugRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/notes/$slug' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/notes/$slug' + id: '__root__' | '/' | '/notes/$slug' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + NotesSlugRoute: typeof NotesSlugRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/notes/$slug': { + id: '/notes/$slug' + path: '/notes/$slug' + fullPath: '/notes/$slug' + preLoaderRoute: typeof NotesSlugRouteImport + parentRoute: typeof rootRouteImport + } + } +} + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + NotesSlugRoute: NotesSlugRoute, +} +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-learn/checkpoints/04-forms/src/router.tsx b/examples/react/start-learn/checkpoints/04-forms/src/router.tsx new file mode 100644 index 0000000000..bb899b1fdf --- /dev/null +++ b/examples/react/start-learn/checkpoints/04-forms/src/router.tsx @@ -0,0 +1,5 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' +export function getRouter() { + return createRouter({ routeTree }) +} diff --git a/examples/react/start-learn/checkpoints/04-forms/src/routes/__root.tsx b/examples/react/start-learn/checkpoints/04-forms/src/routes/__root.tsx new file mode 100644 index 0000000000..9a21c3c91a --- /dev/null +++ b/examples/react/start-learn/checkpoints/04-forms/src/routes/__root.tsx @@ -0,0 +1,34 @@ +import { HeadContent, 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: 'Field notes | Learn Start' }, + ], + }), + shellComponent: ({ children }: { children: ReactNode }) => ( + + + + + + {children} + + + + ), + errorComponent: () => ( +
+

Could not load notes

+ Try again +
+ ), + notFoundComponent: () => ( +
+

Note not found

+ All notes +
+ ), +}) diff --git a/examples/react/start-learn/checkpoints/04-forms/src/routes/index.tsx b/examples/react/start-learn/checkpoints/04-forms/src/routes/index.tsx new file mode 100644 index 0000000000..bd1e014062 --- /dev/null +++ b/examples/react/start-learn/checkpoints/04-forms/src/routes/index.tsx @@ -0,0 +1,114 @@ +import { useState } from 'react' +import { useServerFn } from '@tanstack/react-start' +import { + createFileRoute, + Link, + useHydrated, + useRouter, +} from '@tanstack/react-router' +import { z } from 'zod' +import { createNote, listNotes } from '../server/notes' +export const Route = createFileRoute('/')({ + validateSearch: z.object({ q: z.string().max(200).catch('') }), + loaderDeps: ({ search }) => ({ q: search.q }), + loader: ({ deps }) => listNotes({ data: deps }), + headers: () => ({ 'Cache-Control': 'no-store' }), + component: Home, +}) +function Home() { + const { q } = Route.useSearch() + const notes = Route.useLoaderData() + const save = useServerFn(createNote) + const router = useRouter() + const hydrated = useHydrated() + const [pending, setPending] = useState(false) + const [error, setError] = useState('') + return ( +
+

Field notes

+

+ This checkpoint is a shared local notebook. Accounts come in the next + chapter. +

+
{ + event.preventDefault() + const form = event.currentTarget + const fields = new FormData(form) + setPending(true) + setError('') + try { + const result = await save({ + data: { + slug: String(fields.get('slug') ?? ''), + title: String(fields.get('title') ?? ''), + body: String(fields.get('body') ?? ''), + category: String(fields.get('category') ?? ''), + }, + }) + if (result.error) { + setError(result.error) + } else { + await router.invalidate() + form.reset() + } + } catch { + setError('Could not save. Check your input and try again.') + } finally { + setPending(false) + } + }} + > +
+ Create a note +

+ +

+

+ +

+

+

+

Note not found

+
All notes +